Use AppLog and System.Logger for logging - static imports

This commit is contained in:
Rob Bygrave committed 2022-08-23 15:18:46 +12:00
1 parent a23f241fff
commit 4252445eb4
73 files changed
+473 -416

No files matched your search

@@ -4,11 +4,12 @@ import io.ebean.config.BeanNotEnhancedException;
import io.ebean.datasource.DataSourceConfigurationException; import io.ebean.datasource.DataSourceConfigurationException;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import java.lang.System.Logger.Level;
import java.util.HashMap; import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Holds Database instances. * Holds Database instances.
*/ */
@@ -52,7 +53,7 @@ final class DbContext {
throw new DataSourceConfigurationException(msg, e); throw new DataSourceConfigurationException(msg, e);
} catch (Throwable e) { } catch (Throwable e) {
log.log(Level.ERROR, "Error trying to create the default Database", e); log.log(ERROR, "Error trying to create the default Database", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@@ -6,9 +6,10 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.LineNumberReader; import java.io.LineNumberReader;
import java.lang.System.Logger.Level;
import java.util.Properties; import java.util.Properties;
import static java.lang.System.Logger.Level.*;
/** /**
* Class to determine the ebean version. * Class to determine the ebean version.
* *
@@ -36,12 +37,12 @@ public final class EbeanVersion {
if (in != null) { if (in != null) {
try (LineNumberReader reader = new LineNumberReader(new InputStreamReader(in))) { try (LineNumberReader reader = new LineNumberReader(new InputStreamReader(in))) {
version = reader.readLine(); version = reader.readLine();
log.log(Level.INFO, "ebean version: {0}", version); log.log(INFO, "ebean version: {0}", version);
} }
} }
} }
} catch (IOException e) { } catch (IOException e) {
log.log(Level.WARNING, "Could not determine ebean version: {0}", e.getMessage()); log.log(WARNING, "Could not determine ebean version: {0}", e.getMessage());
} }
} }
@@ -53,13 +54,13 @@ public final class EbeanVersion {
String agentVersion = readVersion(in); String agentVersion = readVersion(in);
if (agentVersion != null) { if (agentVersion != null) {
if (checkMinAgentVersion(agentVersion)) { if (checkMinAgentVersion(agentVersion)) {
log.log(Level.ERROR, "Expected minimum ebean-agent version {0}.{1}.0 but we have {2}, please update the ebean-agent", MIN_AGENT_MAJOR_VERSION, MIN_AGENT_MINOR_VERSION, agentVersion); log.log(ERROR, "Expected minimum ebean-agent version {0}.{1}.0 but we have {2}, please update the ebean-agent", MIN_AGENT_MAJOR_VERSION, MIN_AGENT_MINOR_VERSION, agentVersion);
} }
} }
} }
} }
} catch (IOException e) { } catch (IOException e) {
log.log(Level.WARNING, "Could not check minimum ebean-agent version {0}.{1}.0 required due to - {2}", MIN_AGENT_MAJOR_VERSION, MIN_AGENT_MINOR_VERSION, e.getMessage()); log.log(WARNING, "Could not check minimum ebean-agent version {0}.{1}.0 required due to - {2}", MIN_AGENT_MAJOR_VERSION, MIN_AGENT_MINOR_VERSION, e.getMessage());
} }
} }
@@ -11,9 +11,10 @@ import io.ebean.util.JdbcClose;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.lang.System.Logger.Level;
import java.sql.*; import java.sql.*;
import static java.lang.System.Logger.Level.*;
/** /**
* Database platform specific settings. * Database platform specific settings.
*/ */
@@ -659,7 +660,7 @@ public class DatabasePlatform {
if (isQuote(dbName.charAt(dbName.length() - 1))) { if (isQuote(dbName.charAt(dbName.length() - 1))) {
return openQuote + dbName.substring(1, dbName.length() - 1) + closeQuote; return openQuote + dbName.substring(1, dbName.length() - 1) + closeQuote;
} else { } else {
log.log(Level.ERROR, "Missing backquote on [" + dbName + "]"); log.log(ERROR, "Missing backquote on [" + dbName + "]");
} }
} else if (allQuotedIdentifiers) { } else if (allQuotedIdentifiers) {
return openQuote + dbName + closeQuote; return openQuote + dbName + closeQuote;
@@ -722,7 +723,7 @@ public class DatabasePlatform {
protected String withForUpdate(String sql, Query.LockWait lockWait, Query.LockType lockType) { protected String withForUpdate(String sql, Query.LockWait lockWait, Query.LockType lockType) {
// silently assume the database does not support the "for update" clause. // silently assume the database does not support the "for update" clause.
log.log(Level.INFO, "it seems your database does not support the 'for update' clause"); log.log(INFO, "it seems your database does not support the 'for update' clause");
return sql; return sql;
} }
@@ -756,7 +757,7 @@ public class DatabasePlatform {
if (!schemaExists(dbSchema, connection)) { if (!schemaExists(dbSchema, connection)) {
Statement query = connection.createStatement(); Statement query = connection.createStatement();
try { try {
log.log(Level.DEBUG, "create schema:{0}", dbSchema); log.log(DEBUG, "create schema:{0}", dbSchema);
query.executeUpdate("create schema " + dbSchema); query.executeUpdate("create schema " + dbSchema);
} finally { } finally {
JdbcClose.close(query); JdbcClose.close(query);
@@ -7,7 +7,6 @@ import io.ebean.util.JdbcClose;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@@ -19,6 +18,9 @@ import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Database sequence based IdGenerator. * Database sequence based IdGenerator.
*/ */
@@ -120,7 +122,7 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
protected void loadInBackground(final int requestSize) { protected void loadInBackground(final int requestSize) {
if (currentlyBackgroundLoading.get()) { if (currentlyBackgroundLoading.get()) {
// skip as already background loading // skip as already background loading
log.log(Level.DEBUG, "... skip background sequence load (another load in progress)"); log.log(DEBUG, "... skip background sequence load (another load in progress)");
return; return;
} }
currentlyBackgroundLoading.set(true); currentlyBackgroundLoading.set(true);
@@ -161,7 +163,7 @@ public abstract class SequenceIdGenerator implements PlatformIdGenerator {
} catch (SQLException e) { } catch (SQLException e) {
if (e.getMessage().contains("Database is already closed")) { if (e.getMessage().contains("Database is already closed")) {
String msg = "Error getting SEQ when DB shutting down " + e.getMessage(); String msg = "Error getting SEQ when DB shutting down " + e.getMessage();
log.log(Level.ERROR, msg); log.log(ERROR, msg);
System.out.println(msg); System.out.println(msg);
return Collections.emptyList(); return Collections.emptyList();
} else { } else {
@@ -4,7 +4,6 @@ import io.ebean.Database;
import io.ebean.EbeanVersion; import io.ebean.EbeanVersion;
import io.ebean.service.SpiContainer; import io.ebean.service.SpiContainer;
import java.lang.System.Logger.Level;
import java.sql.Driver; import java.sql.Driver;
import java.sql.DriverManager; import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
@@ -13,6 +12,8 @@ import java.util.Enumeration;
import java.util.List; import java.util.List;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.*;
/** /**
* Manages the shutdown of Ebean. * Manages the shutdown of Ebean.
* <p> * <p>
@@ -121,8 +122,8 @@ public final class ShutdownManager {
// Already run shutdown... // Already run shutdown...
return; return;
} }
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
log.log(Level.DEBUG, "Ebean shutting down"); log.log(DEBUG, "Ebean shutting down");
} }
stopping = true; stopping = true;
deregisterShutdownHook(); deregisterShutdownHook();
@@ -134,7 +135,7 @@ public final class ShutdownManager {
Runnable r = (Runnable) ClassUtil.newInstance(shutdownRunner); Runnable r = (Runnable) ClassUtil.newInstance(shutdownRunner);
r.run(); r.run();
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Error running custom shutdown runnable", e); log.log(ERROR, "Error running custom shutdown runnable", e);
} }
} }
@@ -148,7 +149,7 @@ public final class ShutdownManager {
try { try {
server.shutdown(); server.shutdown();
} catch (Exception ex) { } catch (Exception ex) {
log.log(Level.ERROR, "Error executing shutdown runnable", ex); log.log(ERROR, "Error executing shutdown runnable", ex);
ex.printStackTrace(); ex.printStackTrace();
} }
} }
@@ -166,10 +167,10 @@ public final class ShutdownManager {
while (drivers.hasMoreElements()) { while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement(); Driver driver = drivers.nextElement();
try { try {
log.log(Level.INFO, "De-registering jdbc driver: " + driver); log.log(INFO, "De-registering jdbc driver: " + driver);
DriverManager.deregisterDriver(driver); DriverManager.deregisterDriver(driver);
} catch (SQLException e) { } catch (SQLException e) {
log.log(Level.ERROR, "Error de-registering driver " + driver, e); log.log(ERROR, "Error de-registering driver " + driver, e);
} }
} }
} }
@@ -4,7 +4,8 @@ import io.ebean.Database;
import io.ebean.EbeanVersion; import io.ebean.EbeanVersion;
import io.ebean.Transaction; import io.ebean.Transaction;
import java.lang.System.Logger.Level; import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Provides the default implementation of CsvCallback. * Provides the default implementation of CsvCallback.
@@ -129,7 +130,7 @@ public class DefaultCsvCallback<T> implements CsvCallback<T> {
// related beans (e.g. customer -> customer.billingAddress // related beans (e.g. customer -> customer.billingAddress
server.save(bean, transaction); server.save(bean, transaction);
if (logInfoFrequency > 0 && (row % logInfoFrequency == 0)) { if (logInfoFrequency > 0 && (row % logInfoFrequency == 0)) {
log.log(Level.DEBUG, "processed {0} rows", row); log.log(DEBUG, "processed {0} rows", row);
} }
} }
@@ -140,7 +141,7 @@ public class DefaultCsvCallback<T> implements CsvCallback<T> {
public void end(int row) { public void end(int row) {
commitTransactionIfCreated(); commitTransactionIfCreated();
exeTime = System.currentTimeMillis() - startTime; exeTime = System.currentTimeMillis() - startTime;
log.log(Level.INFO, "Csv finished, rows[{0}] exeMillis[{1}]", row, exeTime); log.log(INFO, "Csv finished, rows[{0}] exeMillis[{1}]", row, exeTime);
} }
/** /**
@@ -2,12 +2,13 @@ package io.ebean.util;
import io.ebean.EbeanVersion; import io.ebean.EbeanVersion;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import static java.lang.System.Logger.Level.WARNING;
/** /**
* Utility for closing raw Jdbc resources. * Utility for closing raw Jdbc resources.
*/ */
@@ -24,7 +25,7 @@ public final class JdbcClose {
statement.close(); statement.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
log.log(Level.WARNING, "Error closing statement", e); log.log(WARNING, "Error closing statement", e);
} }
} }
@@ -37,7 +38,7 @@ public final class JdbcClose {
resultSet.close(); resultSet.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
log.log(Level.WARNING, "Error closing resultSet", e); log.log(WARNING, "Error closing resultSet", e);
} }
} }
@@ -50,7 +51,7 @@ public final class JdbcClose {
connection.close(); connection.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
log.log(Level.WARNING, "Error closing connection", e); log.log(WARNING, "Error closing connection", e);
} }
} }
@@ -63,7 +64,7 @@ public final class JdbcClose {
connection.rollback(); connection.rollback();
} }
} catch (SQLException e) { } catch (SQLException e) {
log.log(Level.WARNING, "Error on connection rollback", e); log.log(WARNING, "Error on connection rollback", e);
} }
} }
@@ -76,7 +77,7 @@ public final class JdbcClose {
stmt.cancel(); stmt.cancel();
} }
} catch (SQLException e) { } catch (SQLException e) {
log.log(Level.WARNING, "Error on cancelling statement", e); log.log(WARNING, "Error on cancelling statement", e);
} }
} }
} }
@@ -12,10 +12,11 @@ import io.ebeaninternal.server.autotune.model.Origin;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.System.Logger.Level;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.*;
/** /**
* Implementation of the AutoTuneService which is comprised of profiling and query tuning. * Implementation of the AutoTuneService which is comprised of profiling and query tuning.
*/ */
@@ -111,7 +112,7 @@ public class DefaultAutoTuneService implements AutoTuneService {
if (stream != null) { if (stream != null) {
loadAutoTuneProfiling(AutoTuneXmlReader.read(stream)); loadAutoTuneProfiling(AutoTuneXmlReader.read(stream));
} else { } else {
logger.log(Level.WARNING, "AutoTune file {0} not found - no initial automatic query tuning", tuningFile); logger.log(WARNING, "AutoTune file {0} not found - no initial automatic query tuning", tuningFile);
} }
} catch (IOException e) { } catch (IOException e) {
throw new IllegalStateException("Error on auto close of " + tuningFile, e); throw new IllegalStateException("Error on auto close of " + tuningFile, e);
@@ -120,7 +121,7 @@ public class DefaultAutoTuneService implements AutoTuneService {
} }
private void loadAutoTuneProfiling(Autotune profiling) { private void loadAutoTuneProfiling(Autotune profiling) {
logger.log(Level.INFO, "AutoTune loading {0} tuning entries", profiling.getOrigin().size()); logger.log(INFO, "AutoTune loading {0} tuning entries", profiling.getOrigin().size());
for (Origin origin : profiling.getOrigin()) { for (Origin origin : profiling.getOrigin()) {
queryTuner.put(origin); queryTuner.put(origin);
} }
@@ -141,17 +142,17 @@ public class DefaultAutoTuneService implements AutoTuneService {
event.process(); event.process();
if (event.isEmpty()) { if (event.isEmpty()) {
long exeMillis = System.currentTimeMillis() - start; long exeMillis = System.currentTimeMillis() - start;
logger.log(Level.DEBUG, "No query tuning updates for server:{0} executionMillis:{1}", serverName, exeMillis); logger.log(DEBUG, "No query tuning updates for server:{0} executionMillis:{1}", serverName, exeMillis);
} else { } else {
// report the query tuning changes that have been made // report the query tuning changes that have been made
runtimeChangeCount += event.getChangeCount(); runtimeChangeCount += event.getChangeCount();
event.writeFile(profilingFile + "-" + serverName + "-update"); event.writeFile(profilingFile + "-" + serverName + "-update");
long exeMillis = System.currentTimeMillis() - start; long exeMillis = System.currentTimeMillis() - start;
logger.log(Level.INFO, "query tuning updates - new:{0} diff:{1} for server:{2} executionMillis:{3}", event.getNewCount(), event.getDiffCount(), serverName, exeMillis); logger.log(INFO, "query tuning updates - new:{0} diff:{1} for server:{2} executionMillis:{3}", event.getNewCount(), event.getDiffCount(), serverName, exeMillis);
} }
} catch (Throwable e) { } catch (Throwable e) {
logger.log(Level.ERROR, "Error collecting or applying automatic query tuning", e); logger.log(ERROR, "Error collecting or applying automatic query tuning", e);
} }
} finally { } finally {
lock.unlock(); lock.unlock();
@@ -172,11 +173,11 @@ public class DefaultAutoTuneService implements AutoTuneService {
AutoTuneDiffCollection event = new AutoTuneDiffCollection(profiling, queryTuner, false); AutoTuneDiffCollection event = new AutoTuneDiffCollection(profiling, queryTuner, false);
event.process(); event.process();
if (event.isEmpty()) { if (event.isEmpty()) {
logger.log(Level.INFO, "No new or diff entries for profiling server:{0}", serverName); logger.log(INFO, "No new or diff entries for profiling server:{0}", serverName);
} else { } else {
event.writeFile(profilingFile + "-" + serverName); event.writeFile(profilingFile + "-" + serverName);
logger.log(Level.INFO, "writing new:{0} diff:{1} profiling entries for server:{2}", event.getNewCount(), event.getDiffCount(), serverName); logger.log(INFO, "writing new:{0} diff:{1} profiling entries for server:{2}", event.getNewCount(), event.getDiffCount(), serverName);
} }
} }
} finally { } finally {
@@ -196,7 +197,7 @@ public class DefaultAutoTuneService implements AutoTuneService {
private void outputAllTuning() { private void outputAllTuning() {
if (runtimeChangeCount == 0) { if (runtimeChangeCount == 0) {
logger.log(Level.INFO, "no runtime query tuning changes for server:{0}", serverName); logger.log(INFO, "no runtime query tuning changes for server:{0}", serverName);
} else { } else {
AutoTuneAllCollection event = new AutoTuneAllCollection(queryTuner); AutoTuneAllCollection event = new AutoTuneAllCollection(queryTuner);
@@ -205,12 +206,12 @@ public class DefaultAutoTuneService implements AutoTuneService {
if (existingTuning.exists()) { if (existingTuning.exists()) {
// rename the existing autotune.xml file (appending 'now') // rename the existing autotune.xml file (appending 'now')
if (!existingTuning.renameTo(new File(tuningFile + "." + AutoTuneXmlWriter.now()))) { if (!existingTuning.renameTo(new File(tuningFile + "." + AutoTuneXmlWriter.now()))) {
logger.log(Level.WARNING, "Failed to rename autotune file [{0}]", tuningFile); logger.log(WARNING, "Failed to rename autotune file [{0}]", tuningFile);
} }
} }
event.writeFile(tuningFile, false); event.writeFile(tuningFile, false);
logger.log(Level.INFO, "query tuning detected [{0}] changes, writing all [{1}] tuning entries for server:{2}", runtimeChangeCount, size, serverName); logger.log(INFO, "query tuning detected [{0}] changes, writing all [{1}] tuning entries for server:{2}", runtimeChangeCount, size, serverName);
} }
} }
@@ -279,7 +280,7 @@ public class DefaultAutoTuneService implements AutoTuneService {
} catch (InterruptedException e) { } catch (InterruptedException e) {
// restore the interrupted status // restore the interrupted status
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
logger.log(Level.WARNING, "Error while sleeping after System.gc() request.", e); logger.log(WARNING, "Error while sleeping after System.gc() request.", e);
} }
} }
@@ -9,11 +9,12 @@ import io.ebeaninternal.server.deploy.BeanProperty;
import io.ebeaninternal.server.deploy.BeanPropertyAssoc; import io.ebeaninternal.server.deploy.BeanPropertyAssoc;
import io.ebeaninternal.server.el.ElPropertyValue; import io.ebeaninternal.server.el.ElPropertyValue;
import java.lang.System.Logger.Level;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.WARNING;
/** /**
* Collects usages statistics for a given node in the object graph. * Collects usages statistics for a given node in the object graph.
*/ */
@@ -45,7 +46,7 @@ public class ProfileOriginNodeUsage {
if (path != null) { if (path != null) {
ElPropertyValue elGetValue = rootDesc.elGetValue(path); ElPropertyValue elGetValue = rootDesc.elGetValue(path);
if (elGetValue == null) { if (elGetValue == null) {
logger.log(Level.WARNING, "AutoTune: Can't find join for path[" + path + "] for " + rootDesc.name()); logger.log(WARNING, "AutoTune: Can't find join for path[" + path + "] for " + rootDesc.name());
return; return;
} else { } else {
BeanProperty beanProperty = elGetValue.beanProperty(); BeanProperty beanProperty = elGetValue.beanProperty();
@@ -61,7 +62,7 @@ public class ProfileOriginNodeUsage {
for (String propName : aggregateUsed) { for (String propName : aggregateUsed) {
BeanProperty beanProp = desc.findPropertyFromPath(propName); BeanProperty beanProp = desc.findPropertyFromPath(propName);
if (beanProp == null) { if (beanProp == null) {
logger.log(Level.WARNING, "AutoTune: Can't find property[" + propName + "] for " + desc.name()); logger.log(WARNING, "AutoTune: Can't find property[" + propName + "] for " + desc.name());
} else { } else {
if (beanProp.isId()) { if (beanProp.isId()) {
@@ -9,12 +9,14 @@ import io.ebean.config.CurrentTenantProvider;
import io.ebean.meta.MetricVisitor; import io.ebean.meta.MetricVisitor;
import io.ebean.util.AnnotationUtil; import io.ebean.util.AnnotationUtil;
import java.lang.System.Logger.Level;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.TRACE;
/** /**
* Manages the construction of caches. * Manages the construction of caches.
*/ */
@@ -89,7 +91,7 @@ final class DefaultCacheHolder {
} }
void clearAll() { void clearAll() {
log.log(Level.DEBUG, "clearAll"); log.log(DEBUG, "clearAll");
for (ServerCache serverCache : allCaches.values()) { for (ServerCache serverCache : allCaches.values()) {
serverCache.clear(); serverCache.clear();
} }
@@ -97,7 +99,7 @@ final class DefaultCacheHolder {
public void clear(String name) { public void clear(String name) {
log.log(Level.DEBUG, "clear {0}", name); log.log(DEBUG, "clear {0}", name);
clearIfExists(key(name, ServerCacheType.QUERY)); clearIfExists(key(name, ServerCacheType.QUERY));
clearIfExists(key(name, ServerCacheType.BEAN)); clearIfExists(key(name, ServerCacheType.BEAN));
clearIfExists(key(name, ServerCacheType.NATURAL_KEY)); clearIfExists(key(name, ServerCacheType.NATURAL_KEY));
@@ -112,7 +114,7 @@ final class DefaultCacheHolder {
private void clearIfExists(String fullKey) { private void clearIfExists(String fullKey) {
ServerCache cache = allCaches.get(fullKey); ServerCache cache = allCaches.get(fullKey);
if (cache != null) { if (cache != null) {
log.log(Level.TRACE, "clear cache {0}", fullKey); log.log(TRACE, "clear cache {0}", fullKey);
cache.clear(); cache.clear();
} }
} }
@@ -9,13 +9,15 @@ import io.ebean.metric.CountMetric;
import io.ebean.metric.MetricFactory; import io.ebean.metric.MetricFactory;
import java.io.Serializable; import java.io.Serializable;
import java.lang.System.Logger.Level;
import java.lang.ref.SoftReference; import java.lang.ref.SoftReference;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.TRACE;
import static java.lang.System.Logger.Level.WARNING;
/** /**
* The default cache implementation. * The default cache implementation.
* <p> * <p>
@@ -287,13 +289,13 @@ public class DefaultServerCache implements ServerCache {
evictCount.add(trimmedByGC); evictCount.add(trimmedByGC);
evictCount.add(trimmedByTTL); evictCount.add(trimmedByTTL);
evictCount.add(trimmedByLRU); evictCount.add(trimmedByLRU);
if (logger.isLoggable(Level.TRACE)) { if (logger.isLoggable(TRACE)) {
long exeMicros = TimeUnit.MICROSECONDS.convert(System.nanoTime() - startNanos, TimeUnit.NANOSECONDS); long exeMicros = TimeUnit.MICROSECONDS.convert(System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
logger.log(Level.TRACE, "Executed trim of cache {0} in [{1}]millis idle[{2}] timeToLive[{3}] accessTime[{4}] gc[{5}]", logger.log(TRACE, "Executed trim of cache {0} in [{1}]millis idle[{2}] timeToLive[{3}] accessTime[{4}] gc[{5}]",
name, exeMicros, trimmedByIdle, trimmedByTTL, trimmedByLRU, trimmedByGC); name, exeMicros, trimmedByIdle, trimmedByTTL, trimmedByLRU, trimmedByGC);
} }
} catch (Throwable e) { } catch (Throwable e) {
logger.log(Level.WARNING, "Error during trim of DefaultServerCache [" + name + "]. Cache might be bigger than desired.", e); logger.log(WARNING, "Error during trim of DefaultServerCache [" + name + "]. Cache might be bigger than desired.", e);
} }
} finally { } finally {
lock.unlock(); lock.unlock();
@@ -9,9 +9,11 @@ import io.ebeaninternal.api.SpiCacheRegion;
import io.ebeaninternal.server.cluster.ClusterManager; import io.ebeaninternal.server.cluster.ClusterManager;
import io.ebeaninternal.server.deploy.DCacheRegion; import io.ebeaninternal.server.deploy.DCacheRegion;
import java.lang.System.Logger.Level;
import java.util.*; import java.util.*;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Manages the bean and query caches. * Manages the bean and query caches.
*/ */
@@ -65,23 +67,23 @@ public final class DefaultServerCacheManager implements SpiCacheManager {
enabled.add(region.name()); enabled.add(region.name());
if (!region.isEnabled()) { if (!region.isEnabled()) {
region.setEnabled(true); region.setEnabled(true);
log.log(Level.DEBUG, "Cache region[{0}] enabled", region.name()); log.log(DEBUG, "Cache region[{0}] enabled", region.name());
} }
} else { } else {
disabled.add(region.name()); disabled.add(region.name());
if (region.isEnabled()) { if (region.isEnabled()) {
region.setEnabled(false); region.setEnabled(false);
log.log(Level.DEBUG, "Cache region[{0}] disabled", region.name()); log.log(DEBUG, "Cache region[{0}] disabled", region.name());
} }
} }
} }
log.log(Level.INFO, "Cache regions enabled:{0} disabled:{1}", enabled, disabled); log.log(INFO, "Cache regions enabled:{0} disabled:{1}", enabled, disabled);
} }
} }
@Override @Override
public void setAllRegionsEnabled(boolean enabled) { public void setAllRegionsEnabled(boolean enabled) {
log.log(Level.DEBUG, "All cache regions enabled[{0}]", enabled); log.log(DEBUG, "All cache regions enabled[{0}]", enabled);
for (SpiCacheRegion region : regionMap.values()) { for (SpiCacheRegion region : regionMap.values()) {
region.setEnabled(enabled); region.setEnabled(enabled);
} }
@@ -10,9 +10,11 @@ import io.ebean.plugin.SpiServer;
import io.ebeaninternal.api.CoreLog; import io.ebeaninternal.api.CoreLog;
import java.io.StringWriter; import java.io.StringWriter;
import java.lang.System.Logger.Level;
import java.util.Properties; import java.util.Properties;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Simply logs the change sets in JSON form to logger named <code>io.ebean.ChangeLog</code>. * Simply logs the change sets in JSON form to logger named <code>io.ebean.ChangeLog</code>.
*/ */
@@ -65,9 +67,9 @@ public final class DefaultChangeLogListener implements ChangeLogListener, Plugin
try { try {
StringWriter writer = new StringWriter(getBufferSize(beanChange)); StringWriter writer = new StringWriter(getBufferSize(beanChange));
jsonBuilder.writeBeanJson(writer, beanChange, changeSet); jsonBuilder.writeBeanJson(writer, beanChange, changeSet);
changeLog.log(Level.INFO, writer.toString()); changeLog.log(INFO, writer.toString());
} catch (Exception e) { } catch (Exception e) {
CoreLog.log.log(Level.ERROR, "Exception logging beanChange " + beanChange, e); CoreLog.log.log(ERROR, "Exception logging beanChange " + beanChange, e);
} }
} }
} }
@@ -5,12 +5,13 @@ import io.ebean.Database;
import io.ebean.config.ContainerConfig; import io.ebean.config.ContainerConfig;
import io.ebeaninternal.server.transaction.RemoteTransactionEvent; import io.ebeaninternal.server.transaction.RemoteTransactionEvent;
import java.lang.System.Logger.Level;
import java.util.Iterator; import java.util.Iterator;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.DEBUG;
/** /**
* Manages the cluster service. * Manages the cluster service.
*/ */
@@ -112,8 +113,8 @@ public class ClusterManager implements ServerLookup {
*/ */
public void broadcast(RemoteTransactionEvent event) { public void broadcast(RemoteTransactionEvent event) {
if (broadcast != null) { if (broadcast != null) {
if (clusterLogger.isLoggable(Level.DEBUG)) { if (clusterLogger.isLoggable(DEBUG)) {
clusterLogger.log(Level.DEBUG, "sending: {0}", event); clusterLogger.log(DEBUG, "sending: {0}", event);
} }
broadcast.broadcast(event); broadcast.broadcast(event);
} }
@@ -6,7 +6,7 @@ import io.ebeaninternal.api.SpiEbeanServer;
import io.ebeaninternal.api.SpiTransaction; import io.ebeaninternal.api.SpiTransaction;
import io.ebeaninternal.server.core.timezone.DataTimeZone; import io.ebeaninternal.server.core.timezone.DataTimeZone;
import java.lang.System.Logger.Level; import static java.lang.System.Logger.Level.ERROR;
/** /**
* Base class for find and persist requests. * Base class for find and persist requests.
@@ -63,7 +63,7 @@ public abstract class BeanRequest {
// Just log this and carry on. A previous exception has been // Just log this and carry on. A previous exception has been
// thrown and if this rollback throws exception it likely means // thrown and if this rollback throws exception it likely means
// that the connection is broken (and the dataSource and db will cleanup) // that the connection is broken (and the dataSource and db will cleanup)
CoreLog.log.log(Level.ERROR, "Error trying to rollback a transaction (after a prior exception thrown)", e); CoreLog.log.log(ERROR, "Error trying to rollback a transaction (after a prior exception thrown)", e);
} }
} }
} }
@@ -8,7 +8,6 @@ import io.ebeaninternal.api.DbOffline;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DatabaseMetaData; import java.sql.DatabaseMetaData;
import java.sql.SQLException; import java.sql.SQLException;
@@ -16,6 +15,9 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Create a DatabasePlatform from the configuration. * Create a DatabasePlatform from the configuration.
* <p> * <p>
@@ -39,7 +41,7 @@ public class DatabasePlatformFactory {
try { try {
String offlinePlatform = DbOffline.getPlatform(); String offlinePlatform = DbOffline.getPlatform();
if (offlinePlatform != null) { if (offlinePlatform != null) {
CoreLog.log.log(Level.INFO, "offline platform [{0}]", offlinePlatform); CoreLog.log.log(INFO, "offline platform [{0}]", offlinePlatform);
return byDatabaseName(offlinePlatform); return byDatabaseName(offlinePlatform);
} }
if (config.getDatabasePlatformName() != null) { if (config.getDatabasePlatformName() != null) {
@@ -88,7 +90,7 @@ public class DatabasePlatformFactory {
String dbProductName = metaData.getDatabaseProductName().toLowerCase(); String dbProductName = metaData.getDatabaseProductName().toLowerCase();
final int majorVersion = metaData.getDatabaseMajorVersion(); final int majorVersion = metaData.getDatabaseMajorVersion();
final int minorVersion = metaData.getDatabaseMinorVersion(); final int minorVersion = metaData.getDatabaseMinorVersion();
CoreLog.log.log(Level.DEBUG, "platform for productName[{0}] version[{1}.{2}]", dbProductName, majorVersion, minorVersion); CoreLog.log.log(DEBUG, "platform for productName[{0}] version[{1}.{2}]", dbProductName, majorVersion, minorVersion);
for (DatabasePlatformProvider provider : providers) { for (DatabasePlatformProvider provider : providers) {
if (provider.matchByProductName(dbProductName)) { if (provider.matchByProductName(dbProductName)) {
return provider.create(majorVersion, minorVersion, metaData, connection); return provider.create(majorVersion, minorVersion, metaData, connection);
@@ -14,10 +14,11 @@ import io.ebeaninternal.server.deploy.BeanPropertyAssocMany;
import io.ebeaninternal.server.transaction.DefaultPersistenceContext; import io.ebeaninternal.server.transaction.DefaultPersistenceContext;
import javax.persistence.EntityNotFoundException; import javax.persistence.EntityNotFoundException;
import java.lang.System.Logger.Level;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static java.lang.System.Logger.Level.DEBUG;
/** /**
* Helper to handle lazy loading and refreshing of beans. * Helper to handle lazy loading and refreshing of beans.
*/ */
@@ -108,8 +109,8 @@ final class DefaultBeanLoader {
server.findOne(query, null); server.findOne(query, null);
if (beanCollection != null) { if (beanCollection != null) {
if (beanCollection.checkEmptyLazyLoad()) { if (beanCollection.checkEmptyLazyLoad()) {
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
log.log(Level.DEBUG, "BeanCollection after load was empty. Owner:" + beanCollection.getOwnerBean()); log.log(DEBUG, "BeanCollection after load was empty. Owner:" + beanCollection.getOwnerBean());
} }
} else if (useManyIdCache) { } else if (useManyIdCache) {
parentDesc.cacheManyPropPut(many, beanCollection, parentId); parentDesc.cacheManyPropPut(many, beanCollection, parentId);
@@ -14,7 +14,6 @@ import io.ebeaninternal.server.core.bootup.BootupClasses;
import io.ebeaninternal.server.executor.DefaultBackgroundExecutor; import io.ebeaninternal.server.executor.DefaultBackgroundExecutor;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import java.lang.System.Logger.Level;
import java.net.URL; import java.net.URL;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
@@ -22,6 +21,8 @@ import java.util.List;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.*;
/** /**
* Default Server side implementation of ServerFactory. * Default Server side implementation of ServerFactory.
*/ */
@@ -107,7 +108,7 @@ public final class DefaultContainer implements SpiContainer {
startServer(online, server); startServer(online, server);
} }
DbOffline.reset(); DbOffline.reset();
log.log(Level.INFO, "Started database[{0}] platform[{1}] in {2}ms", config.getName(), config.getDatabasePlatform().getPlatform(), System.currentTimeMillis() - start); log.log(INFO, "Started database[{0}] platform[{1}] in {2}ms", config.getName(), config.getDatabasePlatform().getPlatform(), System.currentTimeMillis() - start);
return server; return server;
} finally { } finally {
lock.unlock(); lock.unlock();
@@ -136,7 +137,7 @@ public final class DefaultContainer implements SpiContainer {
private void checkMissingModulePathProvides() { private void checkMissingModulePathProvides() {
URL servicesFile = ClassLoader.getSystemResource("META-INF/services/io.ebean.config.EntityClassRegister"); URL servicesFile = ClassLoader.getSystemResource("META-INF/services/io.ebean.config.EntityClassRegister");
if (servicesFile != null) { if (servicesFile != null) {
log.log(Level.ERROR, "module-info.java is probably missing 'provides io.ebean.config.EntityClassRegister with EbeanEntityRegister' clause. EntityClassRegister exists but was not service loaded."); log.log(ERROR, "module-info.java is probably missing 'provides io.ebean.config.EntityClassRegister with EbeanEntityRegister' clause. EntityClassRegister exists but was not service loaded.");
} }
} }
@@ -214,7 +215,7 @@ public final class DefaultContainer implements SpiContainer {
*/ */
private void setDataSource(DatabaseConfig config) { private void setDataSource(DatabaseConfig config) {
if (isOfflineMode(config)) { if (isOfflineMode(config)) {
log.log(Level.DEBUG, "... DbOffline using platform [{0}]", DbOffline.getPlatform()); log.log(DEBUG, "... DbOffline using platform [{0}]", DbOffline.getPlatform());
} else { } else {
InitDataSource.init(config); InitDataSource.init(config);
} }
@@ -250,7 +251,7 @@ public final class DefaultContainer implements SpiContainer {
} }
try (Connection connection = config.getDataSource().getConnection()) { try (Connection connection = config.getDataSource().getConnection()) {
if (connection.getAutoCommit()) { if (connection.getAutoCommit()) {
log.log(Level.WARNING, "DataSource [{0}] has autoCommit defaulting to true!", config.getName()); log.log(WARNING, "DataSource [{0}] has autoCommit defaulting to true!", config.getName());
} }
return true; return true;
} catch (SQLException ex) { } catch (SQLException ex) {
@@ -51,7 +51,6 @@ import javax.persistence.NonUniqueResultException;
import javax.persistence.OptimisticLockException; import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
@@ -65,6 +64,7 @@ import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Stream; import java.util.stream.Stream;
import static java.lang.System.Logger.Level.*;
import static java.util.Spliterators.spliteratorUnknownSize; import static java.util.Spliterators.spliteratorUnknownSize;
import static java.util.stream.StreamSupport.stream; import static java.util.stream.StreamSupport.stream;
@@ -331,7 +331,7 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer {
if (config.isQueryPlanCapture()) { if (config.isQueryPlanCapture()) {
long secs = config.getQueryPlanCapturePeriodSecs(); long secs = config.getQueryPlanCapturePeriodSecs();
if (secs > 10) { if (secs > 10) {
log.log(Level.INFO, "capture query plan enabled, every {0}secs", secs); log.log(INFO, "capture query plan enabled, every {0}secs", secs);
backgroundExecutor.scheduleWithFixedDelay(this::collectQueryPlans, secs, secs, TimeUnit.SECONDS); backgroundExecutor.scheduleWithFixedDelay(this::collectQueryPlans, secs, secs, TimeUnit.SECONDS);
} }
} }
@@ -379,7 +379,7 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer {
* Shutdown the services like threads and DataSource. * Shutdown the services like threads and DataSource.
*/ */
private void shutdownInternal(boolean shutdownDataSource, boolean deregisterDriver) { private void shutdownInternal(boolean shutdownDataSource, boolean deregisterDriver) {
log.log(Level.TRACE, "shutting down instance {0}", serverName); log.log(TRACE, "shutting down instance {0}", serverName);
if (shutdown) { if (shutdown) {
// already shutdown // already shutdown
return; return;
@@ -408,7 +408,7 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer {
try { try {
plugin.shutdown(); plugin.shutdown();
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Error when shutting down plugin", e); log.log(ERROR, "Error when shutting down plugin", e);
} }
} }
} }
@@ -2075,7 +2075,7 @@ public final class DefaultServer implements SpiServer, SpiEbeanServer {
try { try {
serverCacheManager.clearLocal(Class.forName(cache)); serverCacheManager.clearLocal(Class.forName(cache));
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Error clearing local cache for type " + cache, e); log.log(ERROR, "Error clearing local cache for type " + cache, e);
} }
} }
} }
@@ -6,11 +6,12 @@ import io.ebeaninternal.xmapping.api.XmapDto;
import io.ebeaninternal.xmapping.api.XmapEbean; import io.ebeaninternal.xmapping.api.XmapEbean;
import io.ebeaninternal.xmapping.api.XmapRawSql; import io.ebeaninternal.xmapping.api.XmapRawSql;
import java.lang.System.Logger.Level;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Reads the Xml deployment information. * Reads the Xml deployment information.
*/ */
@@ -56,7 +57,7 @@ final class InternalConfigXmlMap {
try { try {
dtoClass = Class.forName(dto.getClazz(), false, classLoader); dtoClass = Class.forName(dto.getClazz(), false, classLoader);
} catch (Exception e) { } catch (Exception e) {
CoreLog.internal.log(Level.ERROR, "Could not load dto bean class " + dto.getClazz() + " for ebean xml entry"); CoreLog.internal.log(ERROR, "Could not load dto bean class " + dto.getClazz() + " for ebean xml entry");
return; return;
} }
DtoNamedQueries namedQueries = dtoNamedQueries.computeIfAbsent(dtoClass, aClass -> new DtoNamedQueries()); DtoNamedQueries namedQueries = dtoNamedQueries.computeIfAbsent(dtoClass, aClass -> new DtoNamedQueries());
@@ -57,9 +57,10 @@ import io.ebeanservice.docstore.api.DocStoreIntegration;
import io.ebeanservice.docstore.api.DocStoreUpdateProcessor; import io.ebeanservice.docstore.api.DocStoreUpdateProcessor;
import io.ebeanservice.docstore.none.NoneDocStoreFactory; import io.ebeanservice.docstore.none.NoneDocStoreFactory;
import java.lang.System.Logger.Level;
import java.util.*; import java.util.*;
import static java.lang.System.Logger.Level.*;
/** /**
* Used to extend the DatabaseConfig with additional objects used to configure and * Used to extend the DatabaseConfig with additional objects used to configure and
* construct an Database. * construct an Database.
@@ -433,7 +434,7 @@ public final class InternalConfiguration {
externalTransactionManager = new JtaTransactionManager(); externalTransactionManager = new JtaTransactionManager();
} }
if (externalTransactionManager != null) { if (externalTransactionManager != null) {
log.log(Level.INFO, "Using Transaction Manager {0}", externalTransactionManager.getClass()); log.log(INFO, "Using Transaction Manager {0}", externalTransactionManager.getClass());
return new ExternalTransactionScopeManager(externalTransactionManager); return new ExternalTransactionScopeManager(externalTransactionManager);
} else { } else {
return new DefaultTransactionScopeManager(); return new DefaultTransactionScopeManager();
@@ -523,7 +524,7 @@ public final class InternalConfiguration {
if (iterator.hasNext()) { if (iterator.hasNext()) {
// use the cacheFactory (via classpath service loader) // use the cacheFactory (via classpath service loader)
plugin = iterator.next(); plugin = iterator.next();
log.log(Level.DEBUG, "using ServerCacheFactory {0}", plugin.getClass()); log.log(DEBUG, "using ServerCacheFactory {0}", plugin.getClass());
} else { } else {
// use the built in default l2 caching which is local cache based // use the built in default l2 caching which is local cache based
localL2Caching = true; localL2Caching = true;
@@ -613,7 +614,7 @@ public final class InternalConfiguration {
@Override @Override
public void execute(boolean online) { public void execute(boolean online) {
if (online && ddlRun) { if (online && ddlRun) {
CoreLog.log.log(Level.ERROR, "Configured to run DDL but ebean-ddl-generator is not in the classpath (or ebean-test in the test classpath?)"); CoreLog.log.log(ERROR, "Configured to run DDL but ebean-ddl-generator is not in the classpath (or ebean-test in the test classpath?)");
} }
} }
} }
@@ -5,10 +5,11 @@ import io.ebean.config.DatabaseConfig;
import io.ebeaninternal.api.CoreLog; import io.ebeaninternal.api.CoreLog;
import io.ebeaninternal.server.core.ClassPathScanners; import io.ebeaninternal.server.core.ClassPathScanners;
import java.lang.System.Logger.Level;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static java.lang.System.Logger.Level.DEBUG;
/** /**
* Searches for interesting classes such as Entities, Embedded and ScalarTypes. * Searches for interesting classes such as Entities, Embedded and ScalarTypes.
*/ */
@@ -58,7 +59,7 @@ public class BootupClassPathSearch {
} }
long searchTime = System.currentTimeMillis() - st; long searchTime = System.currentTimeMillis() - st;
log.log(Level.DEBUG, "Classpath search entities[{0}] searchTime[{1}] in packages[{2}]", bc.getEntities().size(), searchTime, packages); log.log(DEBUG, "Classpath search entities[{0}] searchTime[{1}] in packages[{2}]", bc.getEntities().size(), searchTime, packages);
return bc; return bc;
} catch (Exception ex) { } catch (Exception ex) {
@@ -18,13 +18,15 @@ import javax.persistence.AttributeConverter;
import javax.persistence.Embeddable; import javax.persistence.Embeddable;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Table; import javax.persistence.Table;
import java.lang.System.Logger.Level;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Predicate; import java.util.function.Predicate;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Interesting classes for a EbeanServer such as Embeddable, Entity, * Interesting classes for a EbeanServer such as Embeddable, Entity,
* ScalarTypes, Finders, Listeners and Controllers. * ScalarTypes, Finders, Listeners and Controllers.
@@ -205,13 +207,13 @@ public class BootupClasses implements Predicate<Class<?>> {
try { try {
return cls.getConstructor().newInstance(); return cls.getConstructor().newInstance();
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
log.log(Level.DEBUG, "Ignore/expected - no default constructor: " + e.getMessage()); log.log(DEBUG, "Ignore/expected - no default constructor: " + e.getMessage());
return null; return null;
} catch (Exception e) { } catch (Exception e) {
if (logOnException) { if (logOnException) {
// not expected but we log and carry on // not expected but we log and carry on
log.log(Level.ERROR, "Error creating " + cls, e); log.log(ERROR, "Error creating " + cls, e);
return null; return null;
} else { } else {
@@ -6,7 +6,6 @@ import io.ebeaninternal.util.UrlHelper;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.System.Logger.Level;
import java.net.URL; import java.net.URL;
import java.util.Collections; import java.util.Collections;
import java.util.Enumeration; import java.util.Enumeration;
@@ -15,6 +14,8 @@ import java.util.Set;
import java.util.jar.Attributes; import java.util.jar.Attributes;
import java.util.jar.Manifest; import java.util.jar.Manifest;
import static java.lang.System.Logger.Level.WARNING;
/** /**
* Reads all the META-INF/ebean.mf resources with the package locations of entity beans. * Reads all the META-INF/ebean.mf resources with the package locations of entity beans.
*/ */
@@ -63,7 +64,7 @@ class ManifestReader {
} }
} }
} catch (IOException e) { } catch (IOException e) {
log.log(Level.WARNING, "Error reading " + resourcePath + " manifest resources", e); log.log(WARNING, "Error reading " + resourcePath + " manifest resources", e);
} }
return packageSet; return packageSet;
} }
@@ -58,7 +58,6 @@ import io.ebeanservice.docstore.api.mapping.DocumentMapping;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.lang.System.Logger.Level;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Types; import java.sql.Types;
@@ -68,6 +67,8 @@ import java.util.function.Consumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static io.ebeaninternal.server.persist.DmlUtil.isNullOrZero; import static io.ebeaninternal.server.persist.DmlUtil.isNullOrZero;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Describes Beans including their deployment information. * Describes Beans including their deployment information.
@@ -792,7 +793,7 @@ public class BeanDescriptor<T> implements BeanType<T>, STreeType, SpiBeanType {
changeJson.flush(); changeJson.flush();
return beanChange(ChangeType.UPDATE, request.beanId(), changeJson.newJson(), changeJson.oldJson()); return beanChange(ChangeType.UPDATE, request.beanId(), changeJson.newJson(), changeJson.oldJson());
} catch (RuntimeException e) { } catch (RuntimeException e) {
log.log(Level.ERROR, "Failed to write ChangeLog entry for update", e); log.log(ERROR, "Failed to write ChangeLog entry for update", e);
return null; return null;
} }
} }
@@ -808,7 +809,7 @@ public class BeanDescriptor<T> implements BeanType<T>, STreeType, SpiBeanType {
jsonWriter.flush(); jsonWriter.flush();
return beanChange(ChangeType.INSERT, request.beanId(), writer.toString(), null); return beanChange(ChangeType.INSERT, request.beanId(), writer.toString(), null);
} catch (IOException e) { } catch (IOException e) {
log.log(Level.ERROR, "Failed to write ChangeLog entry for insert", e); log.log(ERROR, "Failed to write ChangeLog entry for insert", e);
return null; return null;
} }
} }
@@ -2288,11 +2289,11 @@ public class BeanDescriptor<T> implements BeanType<T>, STreeType, SpiBeanType {
private ElComparator<T> createPropertyComparator(SortByClause.Property sortProp) { private ElComparator<T> createPropertyComparator(SortByClause.Property sortProp) {
ElPropertyValue elGetValue = elGetValue(sortProp.getName()); ElPropertyValue elGetValue = elGetValue(sortProp.getName());
if (elGetValue == null) { if (elGetValue == null) {
log.log(Level.ERROR, "Sort property [" + sortProp + "] not found in " + beanType + ". Cannot sort."); log.log(ERROR, "Sort property [" + sortProp + "] not found in " + beanType + ". Cannot sort.");
return new ElComparatorNoop<>(); return new ElComparatorNoop<>();
} }
if (elGetValue.isAssocMany()) { if (elGetValue.isAssocMany()) {
log.log(Level.ERROR, "Sort property [" + sortProp + "] in " + beanType + " is a many-property. Cannot sort."); log.log(ERROR, "Sort property [" + sortProp + "] in " + beanType + " is a many-property. Cannot sort.");
return new ElComparatorNoop<>(); return new ElComparatorNoop<>();
} }
Boolean nullsHigh = sortProp.getNullsHigh(); Boolean nullsHigh = sortProp.getNullsHigh();
@@ -2768,7 +2769,7 @@ public class BeanDescriptor<T> implements BeanType<T>, STreeType, SpiBeanType {
public void markAsDeleted(EntityBean bean) { public void markAsDeleted(EntityBean bean) {
if (softDeleteProperty == null) { if (softDeleteProperty == null) {
Object id = getId(bean); Object id = getId(bean);
log.log(Level.INFO, "(Lazy) loading unsuccessful for type:{0} id:{1} - expecting when bean has been deleted", name(), id); log.log(INFO, "(Lazy) loading unsuccessful for type:{0} id:{1} - expecting when bean has been deleted", name(), id);
bean._ebean_getIntercept().setLazyLoadFailure(id); bean._ebean_getIntercept().setLazyLoadFailure(id);
} else { } else {
softDeleteValue(bean); softDeleteValue(bean);
@@ -16,9 +16,10 @@ import io.ebeaninternal.server.core.PersistRequestBean;
import io.ebeaninternal.server.transaction.DefaultPersistenceContext; import io.ebeaninternal.server.transaction.DefaultPersistenceContext;
import java.io.IOException; import java.io.IOException;
import java.lang.System.Logger.Level;
import java.util.*; import java.util.*;
import static java.lang.System.Logger.Level.*;
/** /**
* Helper for BeanDescriptor that manages the bean, query and collection caches. * Helper for BeanDescriptor that manages the bean, query and collection caches.
* *
@@ -104,10 +105,10 @@ final class BeanDescriptorCacheHelp<T> {
void deriveNotifyFlags() { void deriveNotifyFlags() {
cacheNotifyOnAll = (invalidateQueryCache || beanCache != null || queryCache != null); cacheNotifyOnAll = (invalidateQueryCache || beanCache != null || queryCache != null);
cacheNotifyOnDelete = !cacheNotifyOnAll && isNotifyOnDeletes(); cacheNotifyOnDelete = !cacheNotifyOnAll && isNotifyOnDeletes();
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
if (cacheNotifyOnAll || cacheNotifyOnDelete) { if (cacheNotifyOnAll || cacheNotifyOnDelete) {
String notifyMode = cacheNotifyOnAll ? "All" : "Delete"; String notifyMode = cacheNotifyOnAll ? "All" : "Delete";
log.log(Level.DEBUG, "l2 caching on {0} - beanCaching:{1} queryCaching:{2} notifyMode:{3} ", log.log(DEBUG, "l2 caching on {0} - beanCaching:{1} queryCaching:{2} notifyMode:{3} ",
desc.fullName(), isBeanCaching(), isQueryCaching(), notifyMode); desc.fullName(), isBeanCaching(), isQueryCaching(), notifyMode);
} }
} }
@@ -178,8 +179,8 @@ final class BeanDescriptorCacheHelp<T> {
*/ */
void queryCacheClear() { void queryCacheClear() {
if (queryCache != null) { if (queryCache != null) {
if (queryLog.isLoggable(Level.DEBUG)) { if (queryLog.isLoggable(DEBUG)) {
queryLog.log(Level.DEBUG, " CLEAR {0}", cacheName); queryLog.log(DEBUG, " CLEAR {0}", cacheName);
} }
queryCache.clear(); queryCache.clear();
} }
@@ -202,11 +203,11 @@ final class BeanDescriptorCacheHelp<T> {
throw new IllegalStateException("No query cache enabled on " + desc + ". Need explicit @Cache(enableQueryCache=true)"); throw new IllegalStateException("No query cache enabled on " + desc + ". Need explicit @Cache(enableQueryCache=true)");
} }
Object queryResult = queryCache.get(id); Object queryResult = queryCache.get(id);
if (queryLog.isLoggable(Level.DEBUG)) { if (queryLog.isLoggable(DEBUG)) {
if (queryResult == null) { if (queryResult == null) {
queryLog.log(Level.DEBUG, " GET {0}({1}) - cache miss", cacheName, id); queryLog.log(DEBUG, " GET {0}({1}) - cache miss", cacheName, id);
} else { } else {
queryLog.log(Level.DEBUG, " GET {0}({1}) - hit", cacheName, id); queryLog.log(DEBUG, " GET {0}({1}) - hit", cacheName, id);
} }
} }
return queryResult; return queryResult;
@@ -219,8 +220,8 @@ final class BeanDescriptorCacheHelp<T> {
if (queryCache == null) { if (queryCache == null) {
throw new IllegalStateException("No query cache enabled on " + desc + ". Need explicit @Cache(enableQueryCache=true)"); throw new IllegalStateException("No query cache enabled on " + desc + ". Need explicit @Cache(enableQueryCache=true)");
} }
if (queryLog.isLoggable(Level.DEBUG)) { if (queryLog.isLoggable(DEBUG)) {
queryLog.log(Level.DEBUG, " PUT {0}({1})", cacheName, id); queryLog.log(DEBUG, " PUT {0}({1})", cacheName, id);
} }
queryCache.put(id, entry); queryCache.put(id, entry);
} }
@@ -228,16 +229,16 @@ final class BeanDescriptorCacheHelp<T> {
void manyPropRemove(String propertyName, Object parentId) { void manyPropRemove(String propertyName, Object parentId) {
ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, propertyName); ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, propertyName);
if (manyLog.isLoggable(Level.TRACE)) { if (manyLog.isLoggable(TRACE)) {
manyLog.log(Level.TRACE, " REMOVE {0}({1}).{2}", cacheName, parentId, propertyName); manyLog.log(TRACE, " REMOVE {0}({1}).{2}", cacheName, parentId, propertyName);
} }
collectionIdsCache.remove(parentId); collectionIdsCache.remove(parentId);
} }
void manyPropClear(String propertyName) { void manyPropClear(String propertyName) {
ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, propertyName); ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, propertyName);
if (manyLog.isLoggable(Level.DEBUG)) { if (manyLog.isLoggable(DEBUG)) {
manyLog.log(Level.DEBUG, " CLEAR {0}(*).{1} ", cacheName, propertyName); manyLog.log(DEBUG, " CLEAR {0}(*).{1} ", cacheName, propertyName);
} }
collectionIdsCache.clear(); collectionIdsCache.clear();
} }
@@ -249,11 +250,11 @@ final class BeanDescriptorCacheHelp<T> {
ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, propertyName); ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, propertyName);
CachedManyIds entry = (CachedManyIds) collectionIdsCache.get(parentId); CachedManyIds entry = (CachedManyIds) collectionIdsCache.get(parentId);
if (entry == null) { if (entry == null) {
if (manyLog.isLoggable(Level.TRACE)) { if (manyLog.isLoggable(TRACE)) {
manyLog.log(Level.TRACE, " GET {0}({1}).{2} - cache miss", cacheName, parentId, propertyName); manyLog.log(TRACE, " GET {0}({1}).{2} - cache miss", cacheName, parentId, propertyName);
} }
} else if (manyLog.isLoggable(Level.DEBUG)) { } else if (manyLog.isLoggable(DEBUG)) {
manyLog.log(Level.DEBUG, " GET {0}({1}).{2} - hit", cacheName, parentId, propertyName); manyLog.log(DEBUG, " GET {0}({1}).{2} - hit", cacheName, parentId, propertyName);
} }
return entry; return entry;
} }
@@ -303,12 +304,12 @@ final class BeanDescriptorCacheHelp<T> {
changes.put(many.name(), asJson); changes.put(many.name(), asJson);
CachedBeanData newData = data.update(changes, data.getVersion()); CachedBeanData newData = data.update(changes, data.getVersion());
if (beanLog.isLoggable(Level.DEBUG)) { if (beanLog.isLoggable(DEBUG)) {
beanLog.log(Level.DEBUG, " UPDATE {0}({1}) changes:{2}", cacheName, parentId, changes); beanLog.log(DEBUG, " UPDATE {0}({1}) changes:{2}", cacheName, parentId, changes);
} }
beanCache.put(parentId, newData); beanCache.put(parentId, newData);
} catch (IOException e) { } catch (IOException e) {
log.log(Level.ERROR, "Error updating L2 cache", e); log.log(ERROR, "Error updating L2 cache", e);
} }
} }
} else { } else {
@@ -321,8 +322,8 @@ final class BeanDescriptorCacheHelp<T> {
void cachePutManyIds(Object parentId, String manyName, CachedManyIds entry) { void cachePutManyIds(Object parentId, String manyName, CachedManyIds entry) {
ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, manyName); ServerCache collectionIdsCache = cacheManager.getCollectionIdsCache(beanType, manyName);
if (manyLog.isLoggable(Level.DEBUG)) { if (manyLog.isLoggable(DEBUG)) {
manyLog.log(Level.DEBUG, " PUT {0}({1}).{2} - ids:{3}", cacheName, parentId, manyName, entry); manyLog.log(DEBUG, " PUT {0}({1}).{2} - ids:{3}", cacheName, parentId, manyName, entry);
} }
collectionIdsCache.put(parentId, entry); collectionIdsCache.put(parentId, entry);
} }
@@ -353,8 +354,8 @@ final class BeanDescriptorCacheHelp<T> {
return new BeanCacheResult<>(); return new BeanCacheResult<>();
} }
Map<Object, Object> beanDataMap = beanCache.getAll(keys); Map<Object, Object> beanDataMap = beanCache.getAll(keys);
if (beanLog.isLoggable(Level.TRACE)) { if (beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " MGET {0}({1}) - hits:{2}", cacheName, ids, beanDataMap.keySet()); beanLog.log(TRACE, " MGET {0}({1}) - hits:{2}", cacheName, ids, beanDataMap.keySet());
} }
BeanCacheResult<T> result = new BeanCacheResult<>(); BeanCacheResult<T> result = new BeanCacheResult<>();
for (Map.Entry<Object, Object> entry : beanDataMap.entrySet()) { for (Map.Entry<Object, Object> entry : beanDataMap.entrySet()) {
@@ -375,8 +376,8 @@ final class BeanDescriptorCacheHelp<T> {
// naturalKey -> Id map // naturalKey -> Id map
Map<Object, Object> naturalKeyMap = naturalKeyCache.getAll(keys); Map<Object, Object> naturalKeyMap = naturalKeyCache.getAll(keys);
if (natLog.isLoggable(Level.TRACE)) { if (natLog.isLoggable(TRACE)) {
natLog.log(Level.TRACE, " MLOOKUP {0}({1}) - hits:{2}", cacheName, keys, naturalKeyMap); natLog.log(TRACE, " MLOOKUP {0}({1}) - hits:{2}", cacheName, keys, naturalKeyMap);
} }
BeanCacheResult<T> result = new BeanCacheResult<>(); BeanCacheResult<T> result = new BeanCacheResult<>();
@@ -392,8 +393,8 @@ final class BeanDescriptorCacheHelp<T> {
Set<Object> ids = new HashSet<>(naturalKeyMap.values()); Set<Object> ids = new HashSet<>(naturalKeyMap.values());
Map<Object, Object> beanDataMap = beanCache.getAll(ids); Map<Object, Object> beanDataMap = beanCache.getAll(ids);
if (beanLog.isLoggable(Level.TRACE)) { if (beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " MGET {0}({1}) - hits:{2}", cacheName, ids, beanDataMap.keySet()); beanLog.log(TRACE, " MGET {0}({1}) - hits:{2}", cacheName, ids, beanDataMap.keySet());
} }
// process the hits into beans etc // process the hits into beans etc
for (Map.Entry<Object, Object> entry : beanDataMap.entrySet()) { for (Map.Entry<Object, Object> entry : beanDataMap.entrySet()) {
@@ -437,8 +438,8 @@ final class BeanDescriptorCacheHelp<T> {
*/ */
void beanCacheClear() { void beanCacheClear() {
if (beanCache != null) { if (beanCache != null) {
if (beanLog.isLoggable(Level.DEBUG)) { if (beanLog.isLoggable(DEBUG)) {
beanLog.log(Level.DEBUG, " CLEAR {0}", cacheName); beanLog.log(DEBUG, " CLEAR {0}", cacheName);
} }
beanCache.clear(); beanCache.clear();
} }
@@ -507,14 +508,14 @@ final class BeanDescriptorCacheHelp<T> {
} }
} }
} }
if (beanLog.isLoggable(Level.DEBUG)) { if (beanLog.isLoggable(DEBUG)) {
beanLog.log(Level.DEBUG, " MPUT {0}({1})", cacheName, map.keySet()); beanLog.log(DEBUG, " MPUT {0}({1})", cacheName, map.keySet());
} }
getBeanCache().putAll(map); getBeanCache().putAll(map);
if (natKeys != null && !natKeys.isEmpty()) { if (natKeys != null && !natKeys.isEmpty()) {
if (natLog.isLoggable(Level.DEBUG)) { if (natLog.isLoggable(DEBUG)) {
natLog.log(Level.DEBUG, " MPUT {0}({1}, {2})", cacheName, naturalKey, natKeys.keySet()); natLog.log(DEBUG, " MPUT {0}({1}, {2})", cacheName, naturalKey, natKeys.keySet());
} }
naturalKeyCache.putAll(natKeys); naturalKeyCache.putAll(natKeys);
} }
@@ -526,15 +527,15 @@ final class BeanDescriptorCacheHelp<T> {
void beanCachePutDirect(EntityBean bean) { void beanCachePutDirect(EntityBean bean) {
CachedBeanData beanData = beanExtractData(desc, bean); CachedBeanData beanData = beanExtractData(desc, bean);
String key = desc.cacheKeyForBean(bean); String key = desc.cacheKeyForBean(bean);
if (beanLog.isLoggable(Level.DEBUG)) { if (beanLog.isLoggable(DEBUG)) {
beanLog.log(Level.DEBUG, " PUT {0}({1}) data:{2}", cacheName, key, beanData); beanLog.log(DEBUG, " PUT {0}({1}) data:{2}", cacheName, key, beanData);
} }
getBeanCache().put(key, beanData); getBeanCache().put(key, beanData);
if (naturalKey != null) { if (naturalKey != null) {
String naturalKey = calculateNaturalKey(beanData); String naturalKey = calculateNaturalKey(beanData);
if (naturalKey != null) { if (naturalKey != null) {
if (natLog.isLoggable(Level.DEBUG)) { if (natLog.isLoggable(DEBUG)) {
natLog.log(Level.DEBUG, " PUT {0}({1}, {2})", cacheName, naturalKey, key); natLog.log(DEBUG, " PUT {0}({1}, {2})", cacheName, naturalKey, key);
} }
naturalKeyCache.put(naturalKey, key); naturalKeyCache.put(naturalKey, key);
} }
@@ -575,13 +576,13 @@ final class BeanDescriptorCacheHelp<T> {
private T beanCacheGetInternal(String key, Boolean readOnly, PersistenceContext context) { private T beanCacheGetInternal(String key, Boolean readOnly, PersistenceContext context) {
CachedBeanData data = (CachedBeanData) getBeanCache().get(key); CachedBeanData data = (CachedBeanData) getBeanCache().get(key);
if (data == null) { if (data == null) {
if (beanLog.isLoggable(Level.TRACE)) { if (beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " GET {0}({1}) - cache miss", cacheName, key); beanLog.log(TRACE, " GET {0}({1}) - cache miss", cacheName, key);
} }
return null; return null;
} }
if (beanLog.isLoggable(Level.TRACE)) { if (beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " GET {0}({1}) - hit", cacheName, key); beanLog.log(TRACE, " GET {0}({1}) - hit", cacheName, key);
} }
return convertToBean(key, readOnly, context, data); return convertToBean(key, readOnly, context, data);
} }
@@ -591,8 +592,8 @@ final class BeanDescriptorCacheHelp<T> {
if (cacheSharableBeans && !Boolean.FALSE.equals(readOnly)) { if (cacheSharableBeans && !Boolean.FALSE.equals(readOnly)) {
Object bean = data.getSharableBean(); Object bean = data.getSharableBean();
if (bean != null) { if (bean != null) {
if (beanLog.isLoggable(Level.TRACE)) { if (beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " GET {0}({1}) - hit shared bean", cacheName, id); beanLog.log(TRACE, " GET {0}({1}) - hit shared bean", cacheName, id);
} }
if (desc.isReadAuditing()) { if (desc.isReadAuditing()) {
desc.readAuditBean("l2", "", bean); desc.readAuditBean("l2", "", bean);
@@ -680,8 +681,8 @@ final class BeanDescriptorCacheHelp<T> {
*/ */
void beanCacheApplyInvalidate(Collection<String> keys) { void beanCacheApplyInvalidate(Collection<String> keys) {
if (beanCache != null) { if (beanCache != null) {
if (beanLog.isLoggable(Level.DEBUG)) { if (beanLog.isLoggable(DEBUG)) {
beanLog.log(Level.DEBUG, " MREMOVE {0}({1})", cacheName, keys); beanLog.log(DEBUG, " MREMOVE {0}({1})", cacheName, keys);
} }
beanCache.removeAll(new HashSet<>(keys)); beanCache.removeAll(new HashSet<>(keys));
} }
@@ -700,8 +701,8 @@ final class BeanDescriptorCacheHelp<T> {
} }
Map<Object, Object> hits = getBeanCache().getAll(ebis.keySet()); Map<Object, Object> hits = getBeanCache().getAll(ebis.keySet());
if (beanLog.isLoggable(Level.TRACE)) { if (beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " MLOAD {0}({1}) - got hits ({2})", cacheName, ebis.keySet(), hits.size()); beanLog.log(TRACE, " MLOAD {0}({1}) - got hits ({2})", cacheName, ebis.keySet(), hits.size());
} }
Set<EntityBeanIntercept> loaded = new HashSet<>(); Set<EntityBeanIntercept> loaded = new HashSet<>();
@@ -713,19 +714,19 @@ final class BeanDescriptorCacheHelp<T> {
CachedBeanData cacheData = (CachedBeanData) hit.getValue(); CachedBeanData cacheData = (CachedBeanData) hit.getValue();
if (lazyLoadProperty > -1 && !cacheData.isLoaded(propertyName)) { if (lazyLoadProperty > -1 && !cacheData.isLoaded(propertyName)) {
if (beanLog.isLoggable(Level.TRACE)) { if (beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " load {0}({1}) - cache miss on property({2})", cacheName, key, propertyName); beanLog.log(TRACE, " load {0}({1}) - cache miss on property({2})", cacheName, key, propertyName);
} }
} else { } else {
CachedBeanDataToBean.load(desc, ebi.getOwner(), cacheData, context); CachedBeanDataToBean.load(desc, ebi.getOwner(), cacheData, context);
loaded.add(ebi); loaded.add(ebi);
if (beanLog.isLoggable(Level.DEBUG)) { if (beanLog.isLoggable(DEBUG)) {
beanLog.log(Level.DEBUG, " load {0}({1}) - hit", cacheName, key); beanLog.log(DEBUG, " load {0}({1}) - hit", cacheName, key);
} }
} }
} }
if (!ebis.isEmpty() && beanLog.isLoggable(Level.TRACE)) { if (!ebis.isEmpty() && beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " load {0}({1}) - cache miss", cacheName, ebis.keySet()); beanLog.log(TRACE, " load {0}({1}) - cache miss", cacheName, ebis.keySet());
} }
return loaded; return loaded;
} }
@@ -736,21 +737,21 @@ final class BeanDescriptorCacheHelp<T> {
boolean beanCacheLoad(EntityBean bean, EntityBeanIntercept ebi, String key, PersistenceContext context) { boolean beanCacheLoad(EntityBean bean, EntityBeanIntercept ebi, String key, PersistenceContext context) {
CachedBeanData cacheData = (CachedBeanData) getBeanCache().get(key); CachedBeanData cacheData = (CachedBeanData) getBeanCache().get(key);
if (cacheData == null) { if (cacheData == null) {
if (beanLog.isLoggable(Level.TRACE)) { if (beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " LOAD {0}({1}) - cache miss", cacheName, key); beanLog.log(TRACE, " LOAD {0}({1}) - cache miss", cacheName, key);
} }
return false; return false;
} }
int lazyLoadProperty = ebi.getLazyLoadPropertyIndex(); int lazyLoadProperty = ebi.getLazyLoadPropertyIndex();
if (lazyLoadProperty > -1 && !cacheData.isLoaded(ebi.getLazyLoadProperty())) { if (lazyLoadProperty > -1 && !cacheData.isLoaded(ebi.getLazyLoadProperty())) {
if (beanLog.isLoggable(Level.TRACE)) { if (beanLog.isLoggable(TRACE)) {
beanLog.log(Level.TRACE, " LOAD {0}({1}) - cache miss on property({2})", cacheName, key, ebi.getLazyLoadProperty()); beanLog.log(TRACE, " LOAD {0}({1}) - cache miss on property({2})", cacheName, key, ebi.getLazyLoadProperty());
} }
return false; return false;
} }
CachedBeanDataToBean.load(desc, bean, cacheData, context); CachedBeanDataToBean.load(desc, bean, cacheData, context);
if (beanLog.isLoggable(Level.DEBUG)) { if (beanLog.isLoggable(DEBUG)) {
beanLog.log(Level.DEBUG, " LOAD {0}({1}) - hit", cacheName, key); beanLog.log(DEBUG, " LOAD {0}({1}) - hit", cacheName, key);
} }
return true; return true;
} }
@@ -874,8 +875,8 @@ final class BeanDescriptorCacheHelp<T> {
if (existingData != null) { if (existingData != null) {
long currentVersion = existingData.getVersion(); long currentVersion = existingData.getVersion();
if (version > 0 && version < currentVersion) { if (version > 0 && version < currentVersion) {
if (beanLog.isLoggable(Level.DEBUG)) { if (beanLog.isLoggable(DEBUG)) {
beanLog.log(Level.DEBUG, " REMOVE {0}({1}) - version conflict old:{2} new:{3}", cacheName, key, currentVersion, version); beanLog.log(DEBUG, " REMOVE {0}({1}) - version conflict old:{2} new:{3}", cacheName, key, currentVersion, version);
} }
cache.remove(key); cache.remove(key);
} else { } else {
@@ -883,16 +884,16 @@ final class BeanDescriptorCacheHelp<T> {
version = currentVersion; version = currentVersion;
} }
CachedBeanData newData = existingData.update(changes, version); CachedBeanData newData = existingData.update(changes, version);
if (beanLog.isLoggable(Level.DEBUG)) { if (beanLog.isLoggable(DEBUG)) {
beanLog.log(Level.DEBUG, " UPDATE {0}({1}) changes:{2}", cacheName, key, changes); beanLog.log(DEBUG, " UPDATE {0}({1}) changes:{2}", cacheName, key, changes);
} }
cache.put(key, newData); cache.put(key, newData);
} }
if (updateNaturalKey) { if (updateNaturalKey) {
Object oldKey = calculateNaturalKey(existingData); Object oldKey = calculateNaturalKey(existingData);
if (oldKey != null) { if (oldKey != null) {
if (natLog.isLoggable(Level.DEBUG)) { if (natLog.isLoggable(DEBUG)) {
natLog.log(Level.DEBUG, ".. update {0} REMOVE({1}) - old key for ({2})", cacheName, oldKey, key); natLog.log(DEBUG, ".. update {0} REMOVE({1}) - old key for ({2})", cacheName, oldKey, key);
} }
naturalKeyCache.remove(oldKey); naturalKeyCache.remove(oldKey);
} }
@@ -47,12 +47,13 @@ import javax.persistence.PersistenceException;
import javax.persistence.Transient; import javax.persistence.Transient;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.io.Serializable; import java.io.Serializable;
import java.lang.System.Logger.Level;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static java.lang.System.Logger.Level.*;
/** /**
* Creates BeanDescriptors. * Creates BeanDescriptors.
*/ */
@@ -309,7 +310,7 @@ public final class BeanDescriptorManager implements BeanDescriptorMap, SpiBeanTy
} catch (BeanNotEnhancedException e) { } catch (BeanNotEnhancedException e) {
throw e; throw e;
} catch (RuntimeException e) { } catch (RuntimeException e) {
log.log(Level.ERROR, "Error in deployment", e); log.log(ERROR, "Error in deployment", e);
throw e; throw e;
} }
} }
@@ -332,13 +333,13 @@ public final class BeanDescriptorManager implements BeanDescriptorMap, SpiBeanTy
try { try {
entityClass = Class.forName(entityClassName, false, classLoader); entityClass = Class.forName(entityClassName, false, classLoader);
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Could not load entity bean class " + entityClassName + " for ebean.xml entry"); log.log(ERROR, "Could not load entity bean class " + entityClassName + " for ebean.xml entry");
return; return;
} }
DeployBeanInfo<?> info = deployInfoMap.get(entityClass); DeployBeanInfo<?> info = deployInfoMap.get(entityClass);
if (info == null) { if (info == null) {
log.log(Level.ERROR, "No entity bean for ebean.xml entry " + entityClassName); log.log(ERROR, "No entity bean for ebean.xml entry " + entityClassName);
} else { } else {
for (XmapRawSql sql : entityDeploy.getRawSql()) { for (XmapRawSql sql : entityDeploy.getRawSql()) {
@@ -601,11 +602,11 @@ public final class BeanDescriptorManager implements BeanDescriptorMap, SpiBeanTy
int pc = postConstructManager.getRegisterCount(); int pc = postConstructManager.getRegisterCount();
int lc = persistListenerManager.getRegisterCount(); int lc = persistListenerManager.getRegisterCount();
int fc = beanFinderManager.getRegisterCount(); int fc = beanFinderManager.getRegisterCount();
log.log(Level.DEBUG, "BeanPersistControllers[{0}] BeanFinders[{1}] BeanPersistListeners[{2}] BeanQueryAdapters[{3}] BeanPostLoaders[{4}] BeanPostConstructors[{5}]", cc, fc, lc, qa, pl, pc); log.log(DEBUG, "BeanPersistControllers[{0}] BeanFinders[{1}] BeanPersistListeners[{2}] BeanQueryAdapters[{3}] BeanPostLoaders[{4}] BeanPostConstructors[{5}]", cc, fc, lc, qa, pl, pc);
} }
private void logStatus() { private void logStatus() {
log.log(Level.DEBUG, "Entities[{0}]", entityBeanCount); log.log(DEBUG, "Entities[{0}]", entityBeanCount);
} }
/** /**
@@ -867,10 +868,10 @@ public final class BeanDescriptorManager implements BeanDescriptorMap, SpiBeanTy
if (possibleLower.contains(searchName)) { if (possibleLower.contains(searchName)) {
// we have a match // we have a match
prop.setMappedBy(possibleMappedBy); prop.setMappedBy(possibleMappedBy);
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
String m = "Implicitly found mappedBy for " + targetDesc + "." + prop; String m = "Implicitly found mappedBy for " + targetDesc + "." + prop;
m += " by searching for [" + searchName + "] against " + matchSet; m += " by searching for [" + searchName + "] against " + matchSet;
log.log(Level.DEBUG, m); log.log(DEBUG, m);
} }
return true; return true;
} }
@@ -1207,12 +1208,12 @@ public final class BeanDescriptorManager implements BeanDescriptorMap, SpiBeanTy
final DeployIdentityMode identityMode = desc.getIdentityMode(); final DeployIdentityMode identityMode = desc.getIdentityMode();
if (identityMode.isSequence() && !dbIdentity.isSupportsSequence()) { if (identityMode.isSequence() && !dbIdentity.isSupportsSequence()) {
// explicit sequence but not supported by the DatabasePlatform // explicit sequence but not supported by the DatabasePlatform
log.log(Level.INFO, "Explicit sequence on {0} but not supported by DB Platform - ignored", desc.getFullName()); log.log(INFO, "Explicit sequence on {0} but not supported by DB Platform - ignored", desc.getFullName());
identityMode.setIdType(IdType.AUTO); identityMode.setIdType(IdType.AUTO);
} }
if (identityMode.isIdentity() && !dbIdentity.isSupportsIdentity()) { if (identityMode.isIdentity() && !dbIdentity.isSupportsIdentity()) {
// explicit identity but not supported by the DatabasePlatform // explicit identity but not supported by the DatabasePlatform
log.log(Level.INFO, "Explicit Identity on {0} but not supported by DB Platform - ignored", desc.getFullName()); log.log(INFO, "Explicit Identity on {0} but not supported by DB Platform - ignored", desc.getFullName());
identityMode.setIdType(IdType.AUTO); identityMode.setIdType(IdType.AUTO);
} }
@@ -44,7 +44,6 @@ import javax.persistence.PersistenceException;
import java.io.DataInput; import java.io.DataInput;
import java.io.DataOutput; import java.io.DataOutput;
import java.io.IOException; import java.io.IOException;
import java.lang.System.Logger.Level;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Types; import java.sql.Types;
@@ -52,6 +51,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Description of a property of a bean. Includes its deployment information such * Description of a property of a bean. Includes its deployment information such
* as database column mapping information. * as database column mapping information.
@@ -1434,7 +1435,7 @@ public class BeanProperty implements ElPropertyValue, Property, STreeProperty {
objValue = null; objValue = null;
String msg = "Error trying to use Jackson ObjectMapper to read transient property " String msg = "Error trying to use Jackson ObjectMapper to read transient property "
+ fullName() + " - consider marking this property with @JsonIgnore"; + fullName() + " - consider marking this property with @JsonIgnore";
CoreLog.log.log(Level.ERROR, msg, e); CoreLog.log.log(ERROR, msg, e);
} }
} }
if (jsonDeserialize) { if (jsonDeserialize) {
@@ -27,10 +27,11 @@ import io.ebeanservice.docstore.api.mapping.DocPropertyMapping;
import io.ebeanservice.docstore.api.support.DocStructure; import io.ebeanservice.docstore.api.support.DocStructure;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import java.lang.System.Logger.Level;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Abstract base for properties mapped to an associated bean, list, set or map. * Abstract base for properties mapped to an associated bean, list, set or map.
*/ */
@@ -433,7 +434,7 @@ public abstract class BeanPropertyAssoc<T> extends BeanProperty implements STree
if (!idProp.isEmbedded()) { if (!idProp.isEmbedded()) {
// simple single scalar id // simple single scalar id
if (cols.length != 1) { if (cols.length != 1) {
CoreLog.log.log(Level.ERROR, "No Imported Id column for [" + idProp + "] in table [" + join.getTable() + "]"); CoreLog.log.log(ERROR, "No Imported Id column for [" + idProp + "] in table [" + join.getTable() + "]");
return null; return null;
} else { } else {
BeanProperty[] idProps = {idProp}; BeanProperty[] idProps = {idProp};
@@ -24,9 +24,10 @@ import io.ebeaninternal.server.query.SqlBeanLoad;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.lang.System.Logger.Level;
import java.util.*; import java.util.*;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Property mapped to a List Set or Map. * Property mapped to a List Set or Map.
*/ */
@@ -668,7 +669,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> implements ST
} }
} catch (PersistenceException e) { } catch (PersistenceException e) {
// not found as individual scalar properties // not found as individual scalar properties
CoreLog.log.log(Level.ERROR, "Could not find a exported property?", e); CoreLog.log.log(ERROR, "Could not find a exported property?", e);
} }
} else { } else {
if (idProp != null) { if (idProp != null) {
@@ -963,7 +964,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> implements ST
setValue(bean, collection); setValue(bean, collection);
} }
} catch (Exception e) { } catch (Exception e) {
CoreLog.log.log(Level.ERROR, "Error setting value from L2 cache", e); CoreLog.log.log(ERROR, "Error setting value from L2 cache", e);
} }
} }
@@ -976,7 +977,7 @@ public class BeanPropertyAssocMany<T> extends BeanPropertyAssoc<T> implements ST
} }
return jsonWriteCollection(collection); return jsonWriteCollection(collection);
} catch (Exception e) { } catch (Exception e) {
CoreLog.log.log(Level.ERROR, "Error building value element collection json for L2 cache", e); CoreLog.log.log(ERROR, "Error building value element collection json for L2 cache", e);
return null; return null;
} }
} }
@@ -6,7 +6,7 @@ import io.ebeaninternal.server.deploy.meta.DeployBeanTable;
import io.ebeaninternal.server.deploy.meta.DeployTableJoin; import io.ebeaninternal.server.deploy.meta.DeployTableJoin;
import io.ebeaninternal.server.deploy.meta.DeployTableJoinColumn; import io.ebeaninternal.server.deploy.meta.DeployTableJoinColumn;
import java.lang.System.Logger.Level; import static java.lang.System.Logger.Level.DEBUG;
/** /**
@@ -107,7 +107,7 @@ public final class BeanTable {
if (complexKey) { if (complexKey) {
// just to copy the column name rather than prefix with the foreignKeyPrefix. // just to copy the column name rather than prefix with the foreignKeyPrefix.
// I think that with complex keys this is the more common approach. // I think that with complex keys this is the more common approach.
CoreLog.internal.log(Level.DEBUG, "On table[{0}] foreign key column [{1}]", baseTable, lc); CoreLog.internal.log(DEBUG, "On table[{0}] foreign key column [{1}]", baseTable, lc);
fk = lc; fk = lc;
} }
if (sqlFormulaSelect != null) { if (sqlFormulaSelect != null) {
@@ -15,7 +15,8 @@ import io.ebeaninternal.server.deploy.meta.DeployTableJoinColumn;
import io.ebeaninternal.server.query.SqlJoinType; import io.ebeaninternal.server.query.SqlJoinType;
import javax.persistence.*; import javax.persistence.*;
import java.lang.System.Logger.Level;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Read the deployment annotations for Associated One beans. * Read the deployment annotations for Associated One beans.
@@ -214,10 +215,10 @@ final class AnnotationAssocOnes extends AnnotationAssoc {
prop.setPrimaryKeyJoin(true); prop.setPrimaryKeyJoin(true);
if (!primaryKeyJoin.name().isEmpty()) { if (!primaryKeyJoin.name().isEmpty()) {
CoreLog.internal.log(Level.INFO, "Automatically determining join columns for @PrimaryKeyJoinColumn - ignoring PrimaryKeyJoinColumn.name attribute [{0}] on {1}", primaryKeyJoin.name(), prop.getFullBeanName()); CoreLog.internal.log(INFO, "Automatically determining join columns for @PrimaryKeyJoinColumn - ignoring PrimaryKeyJoinColumn.name attribute [{0}] on {1}", primaryKeyJoin.name(), prop.getFullBeanName());
} }
if (!primaryKeyJoin.referencedColumnName().isEmpty()) { if (!primaryKeyJoin.referencedColumnName().isEmpty()) {
CoreLog.internal.log(Level.INFO, "Automatically determining join columns for @PrimaryKeyJoinColumn - Ignoring PrimaryKeyJoinColumn.referencedColumnName attribute [{0}] on {1}", primaryKeyJoin.referencedColumnName(), prop.getFullBeanName()); CoreLog.internal.log(INFO, "Automatically determining join columns for @PrimaryKeyJoinColumn - Ignoring PrimaryKeyJoinColumn.referencedColumnName attribute [{0}] on {1}", primaryKeyJoin.referencedColumnName(), prop.getFullBeanName());
} }
BeanTable baseBeanTable = factory.beanTable(info.getDescriptor().getBeanType()); BeanTable baseBeanTable = factory.beanTable(info.getDescriptor().getBeanType());
String localPrimaryKey = baseBeanTable.getIdColumn(); String localPrimaryKey = baseBeanTable.getIdColumn();
@@ -1,19 +1,7 @@
package io.ebeaninternal.server.deploy.parse; package io.ebeaninternal.server.deploy.parse;
import io.ebean.annotation.Cache;
import io.ebean.annotation.DbComment;
import io.ebean.annotation.DbPartition;
import io.ebean.annotation.DocStore;
import io.ebean.annotation.Draftable;
import io.ebean.annotation.DraftableElement;
import io.ebean.annotation.History;
import io.ebean.annotation.Identity;
import io.ebean.annotation.Index; import io.ebean.annotation.Index;
import io.ebean.annotation.InvalidateQueryCache; import io.ebean.annotation.*;
import io.ebean.annotation.ReadAudit;
import io.ebean.annotation.StorageEngine;
import io.ebean.annotation.Tablespace;
import io.ebean.annotation.View;
import io.ebean.config.TableName; import io.ebean.config.TableName;
import io.ebeaninternal.api.CoreLog; import io.ebeaninternal.api.CoreLog;
import io.ebeaninternal.server.deploy.BeanDescriptor.EntityType; import io.ebeaninternal.server.deploy.BeanDescriptor.EntityType;
@@ -23,18 +11,10 @@ import io.ebeaninternal.server.deploy.PartitionMeta;
import io.ebeaninternal.server.deploy.TablespaceMeta; import io.ebeaninternal.server.deploy.TablespaceMeta;
import io.ebeaninternal.server.deploy.meta.DeployBeanProperty; import io.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import javax.persistence.AttributeOverride; import javax.persistence.*;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.IdClass;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import java.lang.System.Logger.Level;
import static io.ebean.util.AnnotationUtil.typeGet; import static io.ebean.util.AnnotationUtil.typeGet;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Read the class level deployment annotations. * Read the class level deployment annotations.
@@ -67,7 +47,7 @@ final class AnnotationClass extends AnnotationParser {
Column column = override.column(); Column column = override.column();
DeployBeanProperty beanProperty = descriptor.getBeanProperty(propertyName); DeployBeanProperty beanProperty = descriptor.getBeanProperty(propertyName);
if (beanProperty == null) { if (beanProperty == null) {
CoreLog.log.log(Level.ERROR, "AttributeOverride property [" + propertyName + "] not found on " + descriptor.getFullName()); CoreLog.log.log(ERROR, "AttributeOverride property [" + propertyName + "] not found on " + descriptor.getFullName());
} else { } else {
readColumn(column, beanProperty); readColumn(column, beanProperty);
} }
@@ -11,9 +11,10 @@ import io.ebeaninternal.server.type.TypeManager;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.persistence.Transient; import javax.persistence.Transient;
import java.lang.System.Logger.Level;
import java.lang.reflect.*; import java.lang.reflect.*;
import static java.lang.System.Logger.Level.*;
/** /**
* Create the properties for a bean. * Create the properties for a bean.
* <p> * <p>
@@ -85,7 +86,7 @@ public final class DeployCreateProperties {
if (replaced != null && !replaced.isTransient()) { if (replaced != null && !replaced.isTransient()) {
String msg = "Huh??? property " + prop.getFullBeanName() + " being defined twice"; String msg = "Huh??? property " + prop.getFullBeanName() + " being defined twice";
msg += " but replaced property was not transient? This is not expected?"; msg += " but replaced property was not transient? This is not expected?";
CoreLog.log.log(Level.WARNING, msg); CoreLog.log.log(WARNING, msg);
} }
} }
} }
@@ -112,7 +113,7 @@ public final class DeployCreateProperties {
return new DeployBeanPropertySimpleCollection(desc, targetType, manyType); return new DeployBeanPropertySimpleCollection(desc, targetType, manyType);
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
CoreLog.internal.log(Level.DEBUG, "expected non-scalar type {0}", e.getMessage()); CoreLog.internal.log(DEBUG, "expected non-scalar type {0}", e.getMessage());
} }
return new DeployBeanPropertyAssocMany(desc, targetType, manyType); return new DeployBeanPropertyAssocMany(desc, targetType, manyType);
} }
@@ -133,7 +134,7 @@ public final class DeployCreateProperties {
// not supporting this field (generic type used) // not supporting this field (generic type used)
return null; return null;
} }
CoreLog.internal.log(Level.WARNING, "Could not find parameter type (via reflection) on " + desc.getFullName() + " " + field.getName()); CoreLog.internal.log(WARNING, "Could not find parameter type (via reflection) on " + desc.getFullName() + " " + field.getName());
} }
return createManyType(desc, targetType, manyType); return createManyType(desc, targetType, manyType);
} }
@@ -152,7 +153,7 @@ public final class DeployCreateProperties {
return new DeployBeanPropertyAssocOne(desc, propertyType); return new DeployBeanPropertyAssocOne(desc, propertyType);
} catch (Exception e) { } catch (Exception e) {
CoreLog.log.log(Level.ERROR, "Error with " + desc + " field:" + field.getName(), e); CoreLog.log.log(ERROR, "Error with " + desc + " field:" + field.getName(), e);
return null; return null;
} }
} }
@@ -3,13 +3,14 @@ package io.ebeaninternal.server.dto;
import io.ebeaninternal.api.CoreLog; import io.ebeaninternal.api.CoreLog;
import io.ebeaninternal.server.type.TypeManager; import io.ebeaninternal.server.type.TypeManager;
import java.lang.System.Logger.Level;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static java.lang.System.Logger.Level.DEBUG;
/** /**
* Build the DtoMeta for a bean. * Build the DtoMeta for a bean.
* <p> * <p>
@@ -40,7 +41,7 @@ final class DtoMetaBuilder {
final String name = propertyName(method.getName()); final String name = propertyName(method.getName());
properties.add(new DtoMetaProperty(typeManager, dtoType, method, name)); properties.add(new DtoMetaProperty(typeManager, dtoType, method, name));
} catch (Exception e) { } catch (Exception e) {
CoreLog.log.log(Level.DEBUG, "exclude on " + dtoType + " method " + method, e); CoreLog.log.log(DEBUG, "exclude on " + dtoType + " method " + method, e);
} }
} }
} }
@@ -78,7 +79,7 @@ final class DtoMetaBuilder {
constructorList.add(new DtoMetaConstructor(typeManager, constructor, dtoType)); constructorList.add(new DtoMetaConstructor(typeManager, constructor, dtoType));
} catch (Exception e) { } catch (Exception e) {
// we don't want that constructor // we don't want that constructor
CoreLog.log.log(Level.DEBUG, "exclude on " + dtoType + " constructor " + constructor, e); CoreLog.log.log(DEBUG, "exclude on " + dtoType + " constructor " + constructor, e);
} }
} }
} }
@@ -2,10 +2,11 @@ package io.ebeaninternal.server.executor;
import io.avaje.applog.AppLog; import io.avaje.applog.AppLog;
import java.lang.System.Logger.Level;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.*;
/** /**
* A "CachedThreadPool" based on Daemon threads. * A "CachedThreadPool" based on Daemon threads.
* <p> * <p>
@@ -43,19 +44,19 @@ final class DaemonExecutorService {
lock.lock(); lock.lock();
try { try {
if (service.isShutdown()) { if (service.isShutdown()) {
logger.log(Level.DEBUG, "DaemonExecutorService[{0}] already shut down", namePrefix); logger.log(DEBUG, "DaemonExecutorService[{0}] already shut down", namePrefix);
return; return;
} }
try { try {
logger.log(Level.DEBUG, "DaemonExecutorService[{0}] shutting down...", namePrefix); logger.log(DEBUG, "DaemonExecutorService[{0}] shutting down...", namePrefix);
service.shutdown(); service.shutdown();
if (!service.awaitTermination(shutdownWaitSeconds, TimeUnit.SECONDS)) { if (!service.awaitTermination(shutdownWaitSeconds, TimeUnit.SECONDS)) {
logger.log(Level.INFO, "DaemonExecutorService[{0}] shut down timeout exceeded. Terminating running threads.", namePrefix); logger.log(INFO, "DaemonExecutorService[{0}] shut down timeout exceeded. Terminating running threads.", namePrefix);
service.shutdownNow(); service.shutdownNow();
} }
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.ERROR, "Error during shutdown of DaemonThreadPool[" + namePrefix + "]", e); logger.log(ERROR, "Error during shutdown of DaemonThreadPool[" + namePrefix + "]", e);
e.printStackTrace(); e.printStackTrace();
} }
} finally { } finally {
@@ -2,11 +2,12 @@ package io.ebeaninternal.server.executor;
import io.ebeaninternal.api.CoreLog; import io.ebeaninternal.api.CoreLog;
import java.lang.System.Logger.Level;
import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.*;
/** /**
* Daemon based ScheduleThreadPool. * Daemon based ScheduleThreadPool.
*/ */
@@ -38,19 +39,19 @@ public final class DaemonScheduleThreadPool extends ScheduledThreadPoolExecutor
lock.lock(); lock.lock();
try { try {
if (super.isShutdown()) { if (super.isShutdown()) {
log.log(Level.DEBUG, "Already shutdown threadPool {0}", namePrefix); log.log(DEBUG, "Already shutdown threadPool {0}", namePrefix);
return; return;
} }
try { try {
log.log(Level.TRACE, "shutting down threadPool {0}", namePrefix); log.log(TRACE, "shutting down threadPool {0}", namePrefix);
super.shutdown(); super.shutdown();
if (!super.awaitTermination(shutdownWaitSeconds, TimeUnit.SECONDS)) { if (!super.awaitTermination(shutdownWaitSeconds, TimeUnit.SECONDS)) {
log.log(Level.INFO, "Shutdown wait timeout exceeded. Terminating running threads for {0}", namePrefix); log.log(INFO, "Shutdown wait timeout exceeded. Terminating running threads for {0}", namePrefix);
super.shutdownNow(); super.shutdownNow();
} }
log.log(Level.TRACE, "shutdown complete for threadPool {0}", namePrefix); log.log(TRACE, "shutdown complete for threadPool {0}", namePrefix);
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Error during shutdown of threadPool " + namePrefix, e); log.log(ERROR, "Error during shutdown of threadPool " + namePrefix, e);
e.printStackTrace(); e.printStackTrace();
} }
} finally { } finally {
@@ -5,9 +5,10 @@ import io.avaje.lang.NonNullApi;
import io.ebean.config.BackgroundExecutorWrapper; import io.ebean.config.BackgroundExecutorWrapper;
import io.ebeaninternal.api.SpiBackgroundExecutor; import io.ebeaninternal.api.SpiBackgroundExecutor;
import java.lang.System.Logger.Level;
import java.util.concurrent.*; import java.util.concurrent.*;
import static java.lang.System.Logger.Level.*;
/** /**
* The default implementation of the BackgroundExecutor. * The default implementation of the BackgroundExecutor.
*/ */
@@ -27,7 +28,7 @@ public final class DefaultBackgroundExecutor implements SpiBackgroundExecutor {
this.schedulePool = new DaemonScheduleThreadPool(schedulePoolSize, shutdownWaitSeconds, namePrefix + "-periodic-"); this.schedulePool = new DaemonScheduleThreadPool(schedulePoolSize, shutdownWaitSeconds, namePrefix + "-periodic-");
this.pool = new DaemonExecutorService(shutdownWaitSeconds, namePrefix); this.pool = new DaemonExecutorService(shutdownWaitSeconds, namePrefix);
this.wrapper = wrapper; this.wrapper = wrapper;
log.log(Level.DEBUG, "Created backgroundExecutor {0} (schedulePoolSize={1}, shutdownWaitSeconds={2})", namePrefix, schedulePoolSize, shutdownWaitSeconds); log.log(DEBUG, "Created backgroundExecutor {0} (schedulePoolSize={1}, shutdownWaitSeconds={2})", namePrefix, schedulePoolSize, shutdownWaitSeconds);
} }
/** /**
@@ -64,14 +65,14 @@ public final class DefaultBackgroundExecutor implements SpiBackgroundExecutor {
*/ */
private Runnable logExceptions(Runnable task) { private Runnable logExceptions(Runnable task) {
long queued = System.nanoTime(); long queued = System.nanoTime();
log.log(Level.TRACE, "Queued {0}", task); log.log(TRACE, "Queued {0}", task);
return () -> { return () -> {
try { try {
if (log.isLoggable(Level.TRACE)) { if (log.isLoggable(TRACE)) {
long start = System.nanoTime(); long start = System.nanoTime();
log.log(Level.TRACE, "Start {0} (delay time {1} us)", task, (start - queued) / 1000L); log.log(TRACE, "Start {0} (delay time {1} us)", task, (start - queued) / 1000L);
task.run(); task.run();
log.log(Level.TRACE, "Stop {0} (exec time {1} us)", task, (System.nanoTime() - start) / 1000L); log.log(TRACE, "Stop {0} (exec time {1} us)", task, (System.nanoTime() - start) / 1000L);
} else { } else {
task.run(); task.run();
} }
@@ -79,7 +80,7 @@ public final class DefaultBackgroundExecutor implements SpiBackgroundExecutor {
// log any exception here. Note they will not bubble up to the calling user // log any exception here. Note they will not bubble up to the calling user
// unless Future.get() is checked. (Which is almost never done on scheduled // unless Future.get() is checked. (Which is almost never done on scheduled
// background executions) // background executions)
log.log(Level.ERROR, "Error while executing the task " + task, t); log.log(ERROR, "Error while executing the task " + task, t);
throw t; throw t;
} }
}; };
@@ -127,10 +128,10 @@ public final class DefaultBackgroundExecutor implements SpiBackgroundExecutor {
@Override @Override
public void shutdown() { public void shutdown() {
log.log(Level.TRACE, "BackgroundExecutor shutting down"); log.log(TRACE, "BackgroundExecutor shutting down");
schedulePool.shutdown(); schedulePool.shutdown();
pool.shutdown(); pool.shutdown();
log.log(Level.DEBUG, "BackgroundExecutor stopped"); log.log(DEBUG, "BackgroundExecutor stopped");
} }
} }
@@ -1,12 +1,13 @@
package io.ebeaninternal.server.idgen; package io.ebeaninternal.server.idgen;
import java.io.*; import java.io.*;
import java.lang.System.Logger.Level;
import java.net.NetworkInterface; import java.net.NetworkInterface;
import java.net.SocketException; import java.net.SocketException;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import static java.lang.System.Logger.Level.*;
/** /**
* IdGenerator for java util UUID. * IdGenerator for java util UUID.
* <p> * <p>
@@ -82,7 +83,7 @@ public class UuidV1IdGenerator extends UuidV1RndIdGenerator {
} }
} }
} catch (SocketException ex) { } catch (SocketException ex) {
log.log(Level.DEBUG, "Skipping " + network, ex); log.log(DEBUG, "Skipping " + network, ex);
} }
} }
return fallbackAddr; return fallbackAddr;
@@ -119,7 +120,7 @@ public class UuidV1IdGenerator extends UuidV1RndIdGenerator {
// See, if there is an alternative MAC address set. // See, if there is an alternative MAC address set.
nodeId = parseAlternativeNodeId(altNodeId); nodeId = parseAlternativeNodeId(altNodeId);
restoreState(); restoreState();
log.log(Level.INFO, "Explicitly using ID {0} to generate Type 1 UUIDs", getNodeIdentifier()); log.log(INFO, "Explicitly using ID {0} to generate Type 1 UUIDs", getNodeIdentifier());
} }
UUID uuid = nextId(null); UUID uuid = nextId(null);
long ts = timeStamp.get(); long ts = timeStamp.get();
@@ -127,9 +128,9 @@ public class UuidV1IdGenerator extends UuidV1RndIdGenerator {
ts /= MILLIS_TO_UUID; ts /= MILLIS_TO_UUID;
saveState(); saveState();
log.log(Level.DEBUG, "Saved state: clockSeq {0}, timestamp {1}, uuid {2}, stateFile: {3})", clockSeq.get(), new Date(ts), uuid, stateFile); log.log(DEBUG, "Saved state: clockSeq {0}, timestamp {1}, uuid {2}, stateFile: {3})", clockSeq.get(), new Date(ts), uuid, stateFile);
} catch (IOException e) { } catch (IOException e) {
log.log(Level.ERROR, "There was a problem while detecting the nodeId. Falling back to random mode. Try using to specify 'ebean.uuidNodeId' property", e); log.log(ERROR, "There was a problem while detecting the nodeId. Falling back to random mode. Try using to specify 'ebean.uuidNodeId' property", e);
useRandomMode(); useRandomMode();
} }
} }
@@ -146,16 +147,16 @@ public class UuidV1IdGenerator extends UuidV1RndIdGenerator {
try { try {
nodeId = getHardwareId(); nodeId = getHardwareId();
} catch (IOException e) { } catch (IOException e) {
log.log(Level.ERROR, "Error while reading MAC address. Fall back to 'generate' mode", e); log.log(ERROR, "Error while reading MAC address. Fall back to 'generate' mode", e);
tryGenerateMode(); tryGenerateMode();
} }
if (nodeId != null) { if (nodeId != null) {
restoreState(); restoreState();
log.log(Level.INFO, "Using MAC {0} to generate Type 1 UUIDs", getNodeIdentifier()); log.log(INFO, "Using MAC {0} to generate Type 1 UUIDs", getNodeIdentifier());
return; return;
} }
log.log(Level.WARNING, "No suitable network interface found. Fall back to 'generate' mode"); log.log(WARNING, "No suitable network interface found. Fall back to 'generate' mode");
tryGenerateMode(); tryGenerateMode();
} }
@@ -165,11 +166,11 @@ public class UuidV1IdGenerator extends UuidV1RndIdGenerator {
*/ */
private void tryGenerateMode() throws IOException { private void tryGenerateMode() throws IOException {
if (restoreState()) { if (restoreState()) {
log.log(Level.INFO, "Using recently generated nodeId {0} to generate Type 1 UUIDs", getNodeIdentifier()); log.log(INFO, "Using recently generated nodeId {0} to generate Type 1 UUIDs", getNodeIdentifier());
} else { } else {
// RFC 4.5 use random portion for node // RFC 4.5 use random portion for node
nodeId = super.getNodeIdBytes(); nodeId = super.getNodeIdBytes();
log.log(Level.INFO, "Using a newly generated nodeId {0} to generate Type 1 UUIDs", getNodeIdentifier()); log.log(INFO, "Using a newly generated nodeId {0} to generate Type 1 UUIDs", getNodeIdentifier());
} }
} }
@@ -180,7 +181,7 @@ public class UuidV1IdGenerator extends UuidV1RndIdGenerator {
private void useRandomMode() { private void useRandomMode() {
canSaveState = false; canSaveState = false;
nodeId = super.getNodeIdBytes(); nodeId = super.getNodeIdBytes();
log.log(Level.INFO, "Explicitly using a new random ID {0} to generate Type 1 UUIDs", getNodeIdentifier()); log.log(INFO, "Explicitly using a new random ID {0} to generate Type 1 UUIDs", getNodeIdentifier());
} }
/** /**
@@ -211,14 +212,14 @@ public class UuidV1IdGenerator extends UuidV1RndIdGenerator {
String propNodeId = prop.getProperty("nodeId"); String propNodeId = prop.getProperty("nodeId");
if (propNodeId == null || propNodeId.isEmpty()) { if (propNodeId == null || propNodeId.isEmpty()) {
log.log(Level.WARNING, "State file '{0}' is incomplete", stateFile); log.log(WARNING, "State file '{0}' is incomplete", stateFile);
return false; // we cannot restore return false; // we cannot restore
} }
try { try {
if (nodeId == null) { if (nodeId == null) {
nodeId = parseAlternativeNodeId(propNodeId); nodeId = parseAlternativeNodeId(propNodeId);
} else if (!getNodeIdentifier().equals(propNodeId)) { } else if (!getNodeIdentifier().equals(propNodeId)) {
log.log(Level.WARNING, log.log(WARNING,
"The nodeId in the state file '{0}' has changed from {1} to {2}. " "The nodeId in the state file '{0}' has changed from {1} to {2}. "
+ "This can happen when MAC address changes or when two containers share the same state file", + "This can happen when MAC address changes or when two containers share the same state file",
stateFile, propNodeId, getNodeIdentifier()); stateFile, propNodeId, getNodeIdentifier());
@@ -231,7 +232,7 @@ public class UuidV1IdGenerator extends UuidV1RndIdGenerator {
return true; return true;
} catch (IllegalArgumentException nfe) { } catch (IllegalArgumentException nfe) {
log.log(Level.ERROR, "State file corrupt: " + stateFile, nfe); log.log(ERROR, "State file corrupt: " + stateFile, nfe);
} }
return false; return false;
} }
@@ -255,7 +256,7 @@ public class UuidV1IdGenerator extends UuidV1RndIdGenerator {
try (OutputStream os = new FileOutputStream(stateFile)) { try (OutputStream os = new FileOutputStream(stateFile)) {
prop.store(os, "ebean uuid state file"); prop.store(os, "ebean uuid state file");
} catch (IOException e) { } catch (IOException e) {
log.log(Level.ERROR, "Could not persist uuid state to: " + stateFile, e); log.log(ERROR, "Could not persist uuid state to: " + stateFile, e);
} }
} }
@@ -4,13 +4,14 @@ import io.avaje.applog.AppLog;
import io.ebean.Transaction; import io.ebean.Transaction;
import io.ebean.config.dbplatform.PlatformIdGenerator; import io.ebean.config.dbplatform.PlatformIdGenerator;
import java.lang.System.Logger.Level;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.INFO;
/** /**
* IdGenerator for (pseudo) type 1 UUIDs. * IdGenerator for (pseudo) type 1 UUIDs.
* *
@@ -105,7 +106,7 @@ public class UuidV1RndIdGenerator implements PlatformIdGenerator {
delta = current - last; delta = current - last;
if (delta < -10000 * 20000) { if (delta < -10000 * 20000) {
log.log(Level.INFO, "Clock skew of {} ms detected", delta / -10000); log.log(INFO, "Clock skew of {} ms detected", delta / -10000);
// The clock was adjusted back about 2 seconds, or we were generating a lot of ids too fast // The clock was adjusted back about 2 seconds, or we were generating a lot of ids too fast
// if so, we try to set the current as last and also increment the clockSeq. // if so, we try to set the current as last and also increment the clockSeq.
lock.lock(); lock.lock();
@@ -2,7 +2,8 @@ package io.ebeaninternal.server.logger;
import io.ebeaninternal.api.SpiLogger; import io.ebeaninternal.api.SpiLogger;
import java.lang.System.Logger.Level; import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.TRACE;
final class DSpiLogger implements SpiLogger { final class DSpiLogger implements SpiLogger {
@@ -14,21 +15,21 @@ final class DSpiLogger implements SpiLogger {
@Override @Override
public boolean isDebug() { public boolean isDebug() {
return logger.isLoggable(Level.DEBUG); return logger.isLoggable(DEBUG);
} }
@Override @Override
public boolean isTrace() { public boolean isTrace() {
return logger.isLoggable(Level.TRACE); return logger.isLoggable(TRACE);
} }
@Override @Override
public void debug(String msg) { public void debug(String msg) {
logger.log(Level.DEBUG, msg); logger.log(DEBUG, msg);
} }
@Override @Override
public void trace(String msg) { public void trace(String msg) {
logger.log(Level.TRACE, msg); logger.log(TRACE, msg);
} }
} }
@@ -6,13 +6,14 @@ import io.ebeaninternal.api.SpiTransaction;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.System.Logger.Level;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static java.lang.System.Logger.Level.WARNING;
/** /**
* A batched statement that is held in BatchedPstmtHolder. It has a list of * A batched statement that is held in BatchedPstmtHolder. It has a list of
* BatchPostExecute which it will process after the statement is executed. * BatchPostExecute which it will process after the statement is executed.
@@ -136,7 +137,7 @@ public final class BatchedPstmt implements SpiProfileTransactionEvent {
try { try {
pstmt.close(); pstmt.close();
} catch (SQLException e) { } catch (SQLException e) {
CoreLog.log.log(Level.WARNING, "BatchedPstmt Error closing statement", e); CoreLog.log.log(WARNING, "BatchedPstmt Error closing statement", e);
} finally { } finally {
pstmt = null; pstmt = null;
} }
@@ -202,7 +203,7 @@ public final class BatchedPstmt implements SpiProfileTransactionEvent {
try { try {
inputStream.close(); inputStream.close();
} catch (IOException e) { } catch (IOException e) {
CoreLog.log.log(Level.WARNING, "BatchedPstmt Error closing inputStream ", e); CoreLog.log.log(WARNING, "BatchedPstmt Error closing inputStream ", e);
} }
} }
inputStreams = null; inputStreams = null;
@@ -12,12 +12,13 @@ import io.ebeaninternal.server.persist.platform.MultiValueBind;
import io.ebeaninternal.server.type.*; import io.ebeaninternal.server.type.*;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import java.lang.System.Logger.Level;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.sql.*; import java.sql.*;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static java.lang.System.Logger.Level.WARNING;
/** /**
* Binds bean values to a PreparedStatement. * Binds bean values to a PreparedStatement.
*/ */
@@ -133,7 +134,7 @@ public final class Binder {
} }
} catch (SQLException ex) { } catch (SQLException ex) {
CoreLog.log.log(Level.WARNING, "error binding parameter [{0}][{1}]", (dataBind.currentPos() - 1), value); CoreLog.log.log(WARNING, "error binding parameter [{0}][{1}]", (dataBind.currentPos() - 1), value);
throw ex; throw ex;
} }
} }
@@ -13,10 +13,12 @@ import io.ebeaninternal.server.core.*;
import io.ebeaninternal.server.core.PersistRequest.Type; import io.ebeaninternal.server.core.PersistRequest.Type;
import io.ebeaninternal.server.deploy.*; import io.ebeaninternal.server.deploy.*;
import java.lang.System.Logger.Level;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.*;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.TRACE;
/** /**
* Persister implementation using DML. * Persister implementation using DML.
* <p> * <p>
@@ -143,7 +145,7 @@ public final class DefaultPersister implements Persister {
DraftHandler<T> draftHandler = new DraftHandler<>(desc, transaction); DraftHandler<T> draftHandler = new DraftHandler<>(desc, transaction);
List<T> liveBeans = draftHandler.fetchSourceBeans(query, false); List<T> liveBeans = draftHandler.fetchSourceBeans(query, false);
PUB.log(Level.DEBUG, "draftRestore [{0}] count[{1}]", desc.name(), liveBeans.size()); PUB.log(DEBUG, "draftRestore [{0}] count[{1}]", desc.name(), liveBeans.size());
if (liveBeans.isEmpty()) { if (liveBeans.isEmpty()) {
return Collections.emptyList(); return Collections.emptyList();
} }
@@ -156,11 +158,11 @@ public final class DefaultPersister implements Persister {
// reset @DraftDirty and @DraftReset properties // reset @DraftDirty and @DraftReset properties
draftHandler.resetDraft(draftBean); draftHandler.resetDraft(draftBean);
PUB.log(Level.TRACE, "draftRestore bean [{0}] id[{1}]", desc.name(), draftHandler.getId()); PUB.log(TRACE, "draftRestore bean [{0}] id[{1}]", desc.name(), draftHandler.getId());
update(createRequest(draftBean, transaction, null, mgr, Type.UPDATE, Flags.RECURSE)); update(createRequest(draftBean, transaction, null, mgr, Type.UPDATE, Flags.RECURSE));
} }
PUB.log(Level.DEBUG, "draftRestore - complete for [{0}]", desc.name()); PUB.log(DEBUG, "draftRestore - complete for [{0}]", desc.name());
return draftHandler.getDrafts(); return draftHandler.getDrafts();
} }
@@ -185,7 +187,7 @@ public final class DefaultPersister implements Persister {
DraftHandler<T> draftHandler = new DraftHandler<>(desc, transaction); DraftHandler<T> draftHandler = new DraftHandler<>(desc, transaction);
List<T> draftBeans = draftHandler.fetchSourceBeans(query, true); List<T> draftBeans = draftHandler.fetchSourceBeans(query, true);
PUB.log(Level.DEBUG, "publish [{0}] count[{1}]", desc.name(), draftBeans.size()); PUB.log(DEBUG, "publish [{0}] count[{1}]", desc.name(), draftBeans.size());
if (draftBeans.isEmpty()) { if (draftBeans.isEmpty()) {
return Collections.emptyList(); return Collections.emptyList();
} }
@@ -202,7 +204,7 @@ public final class DefaultPersister implements Persister {
draftHandler.resetDraft(draftBean); draftHandler.resetDraft(draftBean);
Type persistType = draftHandler.isInsert() ? Type.INSERT : Type.UPDATE; Type persistType = draftHandler.isInsert() ? Type.INSERT : Type.UPDATE;
PUB.log(Level.TRACE, "publish bean [{0}] id[{1}] type[{2}]", desc.name(), draftHandler.getId(), persistType); PUB.log(TRACE, "publish bean [{0}] id[{1}] type[{2}]", desc.name(), draftHandler.getId(), persistType);
PersistRequestBean<T> request = createRequest(liveBean, transaction, null, mgr, persistType, Flags.PUBLISH_RECURSE); PersistRequestBean<T> request = createRequest(liveBean, transaction, null, mgr, persistType, Flags.PUBLISH_RECURSE);
if (persistType == Type.INSERT) { if (persistType == Type.INSERT) {
@@ -214,7 +216,7 @@ public final class DefaultPersister implements Persister {
} }
draftHandler.updateDrafts(transaction, mgr); draftHandler.updateDrafts(transaction, mgr);
PUB.log(Level.DEBUG, "publish - complete for [{0}]", desc.name()); PUB.log(DEBUG, "publish - complete for [{0}]", desc.name());
return livePublish; return livePublish;
} }
@@ -270,7 +272,7 @@ public final class DefaultPersister implements Persister {
void updateDrafts(Transaction transaction, BeanManager<T> mgr) { void updateDrafts(Transaction transaction, BeanManager<T> mgr) {
if (!draftUpdates.isEmpty()) { if (!draftUpdates.isEmpty()) {
// update the dirty status on the drafts that have been published // update the dirty status on the drafts that have been published
PUB.log(Level.DEBUG, "publish - update dirty status on [{0}] drafts", draftUpdates.size()); PUB.log(DEBUG, "publish - update dirty status on [{0}] drafts", draftUpdates.size());
for (T draftUpdate : draftUpdates) { for (T draftUpdate : draftUpdates) {
update(createRequest(draftUpdate, transaction, null, mgr, Type.UPDATE, Flags.ZERO)); update(createRequest(draftUpdate, transaction, null, mgr, Type.UPDATE, Flags.ZERO));
} }
@@ -491,8 +493,8 @@ public final class DefaultPersister implements Persister {
} }
if (request.isDirty()) { if (request.isDirty()) {
request.executeOrQueue(); request.executeOrQueue();
} else if (log.isLoggable(Level.DEBUG)) { } else if (log.isLoggable(DEBUG)) {
log.log(Level.DEBUG, "Update skipped as bean is unchanged: {0}", request.bean()); log.log(DEBUG, "Update skipped as bean is unchanged: {0}", request.bean());
} }
if (request.isPersistCascade()) { if (request.isPersistCascade()) {
// save all the beans in assocMany's after // save all the beans in assocMany's after
@@ -538,8 +540,8 @@ public final class DefaultPersister implements Persister {
if (req.isRegisteredForDeleteBean()) { if (req.isRegisteredForDeleteBean()) {
// skip deleting bean. Used where cascade is on // skip deleting bean. Used where cascade is on
// both sides of a relationship // both sides of a relationship
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
log.log(Level.DEBUG, "skipping delete on alreadyRegistered {0}", req.bean()); log.log(DEBUG, "skipping delete on alreadyRegistered {0}", req.bean());
} }
return 0; return 0;
} }
@@ -9,7 +9,8 @@ import io.ebeaninternal.server.core.PersistRequestBean;
import io.ebeaninternal.server.deploy.BeanPropertyAssocMany; import io.ebeaninternal.server.deploy.BeanPropertyAssocMany;
import java.io.IOException; import java.io.IOException;
import java.lang.System.Logger.Level;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Base for saving entity bean collections and element collections. * Base for saving entity bean collections and element collections.
@@ -72,7 +73,7 @@ abstract class SaveManyBase implements SaveMany {
String asJson = many.jsonWriteCollection(value); String asJson = many.jsonWriteCollection(value);
request.addCollectionChange(many.name(), asJson); request.addCollectionChange(many.name(), asJson);
} catch (IOException e) { } catch (IOException e) {
CoreLog.log.log(Level.ERROR, "Error build element collection entry for L2 cache", e); CoreLog.log.log(ERROR, "Error build element collection entry for L2 cache", e);
} }
} }
} }
@@ -7,12 +7,12 @@ import io.ebeaninternal.api.*;
import io.ebeaninternal.server.transaction.TransactionManager; import io.ebeaninternal.server.transaction.TransactionManager;
import io.ebeaninternal.server.type.bindcapture.BindCapture; import io.ebeaninternal.server.type.bindcapture.BindCapture;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import static java.lang.System.Logger.Level.ERROR;
import static java.util.Collections.emptyList; import static java.util.Collections.emptyList;
public final class CQueryPlanManager implements QueryPlanManager { public final class CQueryPlanManager implements QueryPlanManager {
@@ -65,7 +65,7 @@ public final class CQueryPlanManager implements QueryPlanManager {
} }
return req.plans(); return req.plans();
} catch (SQLException e) { } catch (SQLException e) {
CoreLog.log.log(Level.ERROR, "Error during query plan collection", e); CoreLog.log.log(ERROR, "Error during query plan collection", e);
return emptyList(); return emptyList();
} }
} }
@@ -12,9 +12,10 @@ import io.ebeaninternal.server.deploy.TableJoin;
import io.ebeaninternal.server.querydefn.OrmQueryDetail; import io.ebeaninternal.server.querydefn.OrmQueryDetail;
import io.ebeaninternal.server.querydefn.OrmQueryProperties; import io.ebeaninternal.server.querydefn.OrmQueryProperties;
import java.lang.System.Logger.Level;
import java.util.*; import java.util.*;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Factory for SqlTree. * Factory for SqlTree.
*/ */
@@ -385,7 +386,7 @@ public final class SqlTreeBuilder {
private void addPropertyToSubQuery(SqlTreeProperties selectProps, STreeType desc, String propName, String path) { private void addPropertyToSubQuery(SqlTreeProperties selectProps, STreeType desc, String propName, String path) {
STreeProperty p = desc.findPropertyWithDynamic(propName, path); STreeProperty p = desc.findPropertyWithDynamic(propName, path);
if (p == null) { if (p == null) {
log.log(Level.ERROR, "property [{0}] not found on {1} for query - excluding it.", propName, desc); log.log(ERROR, "property [{0}] not found on {1} for query - excluding it.", propName, desc);
return; return;
} else if (p instanceof STreePropertyAssoc && p.isEmbedded()) { } else if (p instanceof STreePropertyAssoc && p.isEmbedded()) {
// if the property is embedded we need to lookup the real column name // if the property is embedded we need to lookup the real column name
@@ -420,13 +421,13 @@ public final class SqlTreeBuilder {
if (p != null) { if (p != null) {
selectProps.add(p); selectProps.add(p);
} else { } else {
log.log(Level.ERROR, "property [{0}] not found on {1} for query - excluding it.", propName, desc); log.log(ERROR, "property [{0}] not found on {1} for query - excluding it.", propName, desc);
} }
} else if (p.isEmbedded() || (p instanceof STreePropertyAssoc && !queryProps.isIncludedBeanJoin(p.name()))) { } else if (p.isEmbedded() || (p instanceof STreePropertyAssoc && !queryProps.isIncludedBeanJoin(p.name()))) {
// add the embedded bean or the *ToOne assoc bean. We skip the check that the *ToOne propName maps to Id property ... // add the embedded bean or the *ToOne assoc bean. We skip the check that the *ToOne propName maps to Id property ...
selectProps.add(p); selectProps.add(p);
} else { } else {
log.log(Level.ERROR, "property [{0}] expected to be an embedded or *ToOne bean for query - excluding it.", p.fullName()); log.log(ERROR, "property [{0}] expected to be an embedded or *ToOne bean for query - excluding it.", p.fullName());
} }
} }
@@ -435,7 +436,7 @@ public final class SqlTreeBuilder {
// sub class hierarchy if required // sub class hierarchy if required
STreeProperty p = desc.findPropertyWithDynamic(propName, queryProps.getPath()); STreeProperty p = desc.findPropertyWithDynamic(propName, queryProps.getPath());
if (p == null) { if (p == null) {
log.log(Level.ERROR, "property [{0}] not found on {1} for query - excluding it.", propName, desc); log.log(ERROR, "property [{0}] not found on {1} for query - excluding it.", propName, desc);
p = desc.findProperty("id"); p = desc.findProperty("id");
selectProps.add(p); selectProps.add(p);
@@ -11,9 +11,11 @@ import io.ebeaninternal.api.CoreLog;
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.lang.System.Logger.Level;
import java.util.Map; import java.util.Map;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Default implementation of ReadAuditLogger that writes the event in JSON format to standard loggers. * Default implementation of ReadAuditLogger that writes the event in JSON format to standard loggers.
*/ */
@@ -48,9 +50,9 @@ public class DefaultReadAuditLogger implements ReadAuditLogger {
} }
gen.writeEndObject(); gen.writeEndObject();
gen.flush(); gen.flush();
queryLogger.log(Level.INFO, writer.toString()); queryLogger.log(INFO, writer.toString());
} catch (IOException e) { } catch (IOException e) {
CoreLog.log.log(Level.ERROR, "Error writing Read audit event", e); CoreLog.log.log(ERROR, "Error writing Read audit event", e);
} }
} }
@@ -75,9 +77,9 @@ public class DefaultReadAuditLogger implements ReadAuditLogger {
StringWriter writer = new StringWriter(defaultReadBuffer); StringWriter writer = new StringWriter(defaultReadBuffer);
JsonGenerator gen = jsonFactory.createGenerator(writer); JsonGenerator gen = jsonFactory.createGenerator(writer);
writeDetails(gen, event); writeDetails(gen, event);
auditLogger.log(Level.INFO, writer.toString()); auditLogger.log(INFO, writer.toString());
} catch (IOException e) { } catch (IOException e) {
CoreLog.log.log(Level.ERROR, "Error writing Read audit event", e); CoreLog.log.log(ERROR, "Error writing Read audit event", e);
} }
} }
@@ -11,7 +11,6 @@ import io.ebeaninternal.api.SpiProfileHandler;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.lang.System.Logger.Level;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeFormatterBuilder;
@@ -22,6 +21,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.*;
import static java.time.temporal.ChronoField.*; import static java.time.temporal.ChronoField.*;
/** /**
@@ -79,7 +79,7 @@ public final class DefaultProfileHandler implements SpiProfileHandler, Plugin {
this.executor = Executors.newSingleThreadExecutor(); this.executor = Executors.newSingleThreadExecutor();
this.dir = new File(config.getDirectory()); this.dir = new File(config.getDirectory());
if (!dir.exists() && !dir.mkdirs()) { if (!dir.exists() && !dir.mkdirs()) {
log.log(Level.ERROR, "failed to mkdirs " + dir.getAbsolutePath()); log.log(ERROR, "failed to mkdirs " + dir.getAbsolutePath());
} }
incrementFile(); incrementFile();
} }
@@ -109,7 +109,7 @@ public final class DefaultProfileHandler implements SpiProfileHandler, Plugin {
out.close(); out.close();
out = null; out = null;
} catch (IOException e) { } catch (IOException e) {
log.log(Level.ERROR, "Failed to flush and close transaction profiling file ", e); log.log(ERROR, "Failed to flush and close transaction profiling file ", e);
} }
} }
} finally { } finally {
@@ -129,7 +129,7 @@ public final class DefaultProfileHandler implements SpiProfileHandler, Plugin {
File file = new File(dir, "txprofile-" + now + ".tprofile"); File file = new File(dir, "txprofile-" + now + ".tprofile");
out = IOUtils.newWriter(file); out = IOUtils.newWriter(file);
} catch (IOException e) { } catch (IOException e) {
log.log(Level.ERROR, "Not expected", e); log.log(ERROR, "Not expected", e);
} }
} finally { } finally {
lock.unlock(); lock.unlock();
@@ -152,7 +152,7 @@ public final class DefaultProfileHandler implements SpiProfileHandler, Plugin {
} }
flushCurrentFile(); flushCurrentFile();
} catch (Exception e) { } catch (Exception e) {
log.log(Level.WARNING, "Error on collect", e); log.log(WARNING, "Error on collect", e);
} }
} }
@@ -183,10 +183,10 @@ public final class DefaultProfileHandler implements SpiProfileHandler, Plugin {
if (profileCounter % profilesPerFile == 0) { if (profileCounter % profilesPerFile == 0) {
incrementFile(); incrementFile();
log.log(Level.DEBUG, "profiled {0} transactions", profileCounter); log.log(DEBUG, "profiled {0} transactions", profileCounter);
} }
} catch (IOException e) { } catch (IOException e) {
log.log(Level.WARNING, "Error writing transaction profiling", e); log.log(WARNING, "Error writing transaction profiling", e);
} }
} }
@@ -250,16 +250,16 @@ public final class DefaultProfileHandler implements SpiProfileHandler, Plugin {
@Override @Override
public void shutdown() { public void shutdown() {
shutdown = true; shutdown = true;
log.log(Level.TRACE, "shutting down"); log.log(TRACE, "shutting down");
try { try {
executor.shutdown(); executor.shutdown();
if (!executor.awaitTermination(4, TimeUnit.SECONDS)) { if (!executor.awaitTermination(4, TimeUnit.SECONDS)) {
log.log(Level.INFO, "Shut down timeout exceeded. Terminating profiling consumer thread."); log.log(INFO, "Shut down timeout exceeded. Terminating profiling consumer thread.");
executor.shutdownNow(); executor.shutdownNow();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
log.log(Level.WARNING, "Interrupt on shutdown", e); log.log(WARNING, "Interrupt on shutdown", e);
} }
flushCurrentFile(); flushCurrentFile();
} }
@@ -12,12 +12,13 @@ import io.ebeaninternal.server.persist.BatchControl;
import io.ebeanservice.docstore.api.DocStoreTransaction; import io.ebeanservice.docstore.api.DocStoreTransaction;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Read only transaction expected to use autoCommit connection and for implicit use only. * Read only transaction expected to use autoCommit connection and for implicit use only.
* <p> * <p>
@@ -484,7 +485,7 @@ final class ImplicitReadOnlyTransaction implements SpiTransaction, TxnProfileEve
} catch (Exception ex) { } catch (Exception ex) {
// the connection pool will automatically remove the // the connection pool will automatically remove the
// connection if it does not pass the test // connection if it does not pass the test
CoreLog.log.log(Level.ERROR, "Error closing connection", ex); CoreLog.log.log(ERROR, "Error closing connection", ex);
} }
connection = null; connection = null;
active = false; active = false;
@@ -17,12 +17,13 @@ import io.ebeanservice.docstore.api.DocStoreTransaction;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.persistence.RollbackException; import javax.persistence.RollbackException;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* JDBC Connection based transaction. * JDBC Connection based transaction.
*/ */
@@ -356,7 +357,7 @@ class JdbcTransaction implements SpiTransaction, TxnProfileEventCodes {
try { try {
consumer.accept(callbackList.get(i)); consumer.accept(callbackList.get(i));
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Error executing transaction callback", e); log.log(ERROR, "Error executing transaction callback", e);
} }
} }
} }
@@ -884,7 +885,7 @@ class JdbcTransaction implements SpiTransaction, TxnProfileEventCodes {
connection.setReadOnly(false); connection.setReadOnly(false);
} }
} catch (SQLException e) { } catch (SQLException e) {
log.log(Level.ERROR, "Error setting to readOnly?", e); log.log(ERROR, "Error setting to readOnly?", e);
} }
try { try {
if (autoCommit) { if (autoCommit) {
@@ -892,14 +893,14 @@ class JdbcTransaction implements SpiTransaction, TxnProfileEventCodes {
connection.setAutoCommit(true); connection.setAutoCommit(true);
} }
} catch (SQLException e) { } catch (SQLException e) {
log.log(Level.ERROR, "Error setting to readOnly?", e); log.log(ERROR, "Error setting to readOnly?", e);
} }
try { try {
connection.close(); connection.close();
} catch (Exception ex) { } catch (Exception ex) {
// the connection pool will automatically remove the // the connection pool will automatically remove the
// connection if it does not pass the test // connection if it does not pass the test
log.log(Level.ERROR, "Error closing connection", ex); log.log(ERROR, "Error closing connection", ex);
} }
connection = null; connection = null;
active = false; active = false;
@@ -932,7 +933,7 @@ class JdbcTransaction implements SpiTransaction, TxnProfileEventCodes {
} }
withEachCallback(TransactionCallback::postCommit); withEachCallback(TransactionCallback::postCommit);
} catch (SQLException e) { } catch (SQLException e) {
log.log(Level.ERROR, "Error when ending a query only transaction via " + onQueryOnly, e); log.log(ERROR, "Error when ending a query only transaction via " + onQueryOnly, e);
} }
} }
@@ -13,7 +13,9 @@ import javax.transaction.Status;
import javax.transaction.Synchronization; import javax.transaction.Synchronization;
import javax.transaction.TransactionSynchronizationRegistry; import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction; import javax.transaction.UserTransaction;
import java.lang.System.Logger.Level;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.WARNING;
/** /**
* Hook into external JTA transaction manager. * Hook into external JTA transaction manager.
@@ -87,15 +89,15 @@ public final class JtaTransactionManager implements ExternalTransactionManager {
SpiTransaction currentEbeanTransaction = scope.inScope(); SpiTransaction currentEbeanTransaction = scope.inScope();
if (currentEbeanTransaction != null) { if (currentEbeanTransaction != null) {
// NOT expecting this so log WARNING // NOT expecting this so log WARNING
log.log(Level.WARNING, "JTA Transaction - no current txn BUT using current Ebean one {0}", currentEbeanTransaction.getId()); log.log(WARNING, "JTA Transaction - no current txn BUT using current Ebean one {0}", currentEbeanTransaction.getId());
return currentEbeanTransaction; return currentEbeanTransaction;
} }
UserTransaction ut = getUserTransaction(); UserTransaction ut = getUserTransaction();
if (ut == null) { if (ut == null) {
// no current JTA transaction // no current JTA transaction
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
log.log(Level.DEBUG, "JTA Transaction - no current txn"); log.log(DEBUG, "JTA Transaction - no current txn");
} }
return null; return null;
} }
@@ -181,21 +183,21 @@ public final class JtaTransactionManager implements ExternalTransactionManager {
public void afterCompletion(int status) { public void afterCompletion(int status) {
switch (status) { switch (status) {
case Status.STATUS_COMMITTED: case Status.STATUS_COMMITTED:
log.log(Level.DEBUG, "Jta Txn [{0}] committed", transaction.getId()); log.log(DEBUG, "Jta Txn [{0}] committed", transaction.getId());
transaction.postCommit(); transaction.postCommit();
// Remove this transaction object as it is completed // Remove this transaction object as it is completed
transactionManager.scope().clearExternal(); transactionManager.scope().clearExternal();
break; break;
case Status.STATUS_ROLLEDBACK: case Status.STATUS_ROLLEDBACK:
log.log(Level.DEBUG, "Jta Txn [{0}] rollback", transaction.getId()); log.log(DEBUG, "Jta Txn [{0}] rollback", transaction.getId());
transaction.postRollback(null); transaction.postRollback(null);
// Remove this transaction object as it is completed // Remove this transaction object as it is completed
transactionManager.scope().clearExternal(); transactionManager.scope().clearExternal();
break; break;
default: default:
log.log(Level.DEBUG, "Jta Txn [{0}] status:{1}", transaction.getId(), status); log.log(DEBUG, "Jta Txn [{0}] status:{1}", transaction.getId(), status);
} }
// No matter the completion status of the transaction, we release the connection we got from the pool. // No matter the completion status of the transaction, we release the connection we got from the pool.
@@ -11,10 +11,11 @@ import io.ebeaninternal.server.cluster.ClusterManager;
import io.ebeaninternal.server.core.PersistRequestBean; import io.ebeaninternal.server.core.PersistRequestBean;
import io.ebeanservice.docstore.api.DocStoreUpdates; import io.ebeanservice.docstore.api.DocStoreUpdates;
import java.lang.System.Logger.Level;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static java.lang.System.Logger.Level.DEBUG;
/** /**
* Performs post commit processing using a background thread. * Performs post commit processing using a background thread.
* <p> * <p>
@@ -104,8 +105,8 @@ final class PostCommitProcessing {
private void notifyCluster() { private void notifyCluster() {
if (remoteTransactionEvent != null && !remoteTransactionEvent.isEmpty()) { if (remoteTransactionEvent != null && !remoteTransactionEvent.isEmpty()) {
// send the interesting events to the cluster // send the interesting events to the cluster
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
log.log(Level.DEBUG, "Cluster Send: {0}", remoteTransactionEvent); log.log(DEBUG, "Cluster Send: {0}", remoteTransactionEvent);
} }
clusterManager.broadcast(remoteTransactionEvent); clusterManager.broadcast(remoteTransactionEvent);
} }
@@ -6,11 +6,13 @@ import io.ebean.cache.QueryCacheEntryValidate;
import io.ebean.cache.ServerCacheNotification; import io.ebean.cache.ServerCacheNotification;
import io.ebean.cache.ServerCacheNotify; import io.ebean.cache.ServerCacheNotify;
import java.lang.System.Logger.Level;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.TRACE;
/** /**
* Holds timestamp of last modification per table. * Holds timestamp of last modification per table.
* <p> * <p>
@@ -34,8 +36,8 @@ public final class TableModState implements QueryCacheEntryValidate, ServerCache
for (String tableName : touchedTables) { for (String tableName : touchedTables) {
tableModStamp.put(tableName, modNanoTime); tableModStamp.put(tableName, modNanoTime);
} }
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
log.log(Level.DEBUG, "TableModState updated - touched:{0} modNanoTime:{1}", touchedTables, modNanoTime); log.log(DEBUG, "TableModState updated - touched:{0} modNanoTime:{1}", touchedTables, modNanoTime);
} }
} }
@@ -46,8 +48,8 @@ public final class TableModState implements QueryCacheEntryValidate, ServerCache
for (String tableName : tables) { for (String tableName : tables) {
Long modTime = tableModStamp.get(tableName); Long modTime = tableModStamp.get(tableName);
if (modTime != null && modTime >= sinceNanoTime) { if (modTime != null && modTime >= sinceNanoTime) {
if (log.isLoggable(Level.TRACE)) { if (log.isLoggable(TRACE)) {
log.log(Level.TRACE, "Invalidate on table:{0}", tableName); log.log(TRACE, "Invalidate on table:{0}", tableName);
} }
return false; return false;
} }
@@ -73,8 +75,8 @@ public final class TableModState implements QueryCacheEntryValidate, ServerCache
public void notify(ServerCacheNotification notification) { public void notify(ServerCacheNotification notification) {
// use local clock - for slightly more aggressive invalidation (as later) // use local clock - for slightly more aggressive invalidation (as later)
// that removes any concern regarding clock syncing across cluster // that removes any concern regarding clock syncing across cluster
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
log.log(Level.DEBUG, "ServerCacheNotification:{0}", notification); log.log(DEBUG, "ServerCacheNotification:{0}", notification);
} }
touch(notification.getDependentTables()); touch(notification.getDependentTables());
} }
@@ -87,8 +89,8 @@ public final class TableModState implements QueryCacheEntryValidate, ServerCache
public void notify(RemoteTableMod tableMod) { public void notify(RemoteTableMod tableMod) {
// use local clock - for slightly more aggressive invalidation (as later) // use local clock - for slightly more aggressive invalidation (as later)
// that removes any concern regarding clock syncing across cluster // that removes any concern regarding clock syncing across cluster
if (log.isLoggable(Level.DEBUG)) { if (log.isLoggable(DEBUG)) {
log.log(Level.DEBUG, "RemoteTableMod:{0}", tableMod); log.log(DEBUG, "RemoteTableMod:{0}", tableMod);
} }
touch(tableMod.getTables()); touch(tableMod.getTables());
} }
@@ -32,7 +32,6 @@ import io.ebeanservice.docstore.api.DocStoreUpdates;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
@@ -40,6 +39,9 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Manages transactions. * Manages transactions.
* <p> * <p>
@@ -365,7 +367,7 @@ public class TransactionManager implements SpiTransactionManager {
txnLogger.debug(msg); txnLogger.debug(msg);
} }
} catch (Exception ex) { } catch (Exception ex) {
log.log(Level.ERROR, "Error while notifying TransactionEventListener of rollback event", ex); log.log(ERROR, "Error while notifying TransactionEventListener of rollback event", ex);
} }
} }
@@ -416,7 +418,7 @@ public class TransactionManager implements SpiTransactionManager {
postCommit.notifyLocalCache(); postCommit.notifyLocalCache();
backgroundExecutor.execute(postCommit.backgroundNotify()); backgroundExecutor.execute(postCommit.backgroundNotify());
} catch (Exception ex) { } catch (Exception ex) {
log.log(Level.ERROR, "NotifyOfCommit failed. L2 Cache potentially not notified.", ex); log.log(ERROR, "NotifyOfCommit failed. L2 Cache potentially not notified.", ex);
} }
} }
@@ -442,8 +444,8 @@ public class TransactionManager implements SpiTransactionManager {
* Notify local BeanPersistListeners etc of events from another server in the cluster. * Notify local BeanPersistListeners etc of events from another server in the cluster.
*/ */
public final void remoteTransactionEvent(RemoteTransactionEvent remoteEvent) { public final void remoteTransactionEvent(RemoteTransactionEvent remoteEvent) {
if (clusterLogger.isLoggable(Level.DEBUG)) { if (clusterLogger.isLoggable(DEBUG)) {
clusterLogger.log(Level.DEBUG, "processing {0}", remoteEvent); clusterLogger.log(DEBUG, "processing {0}", remoteEvent);
} }
CacheChangeSet changeSet = new CacheChangeSet(); CacheChangeSet changeSet = new CacheChangeSet();
@@ -5,13 +5,14 @@ import io.ebeaninternal.api.CoreLog;
import io.ebeaninternal.server.core.timezone.DataTimeZone; import io.ebeaninternal.server.core.timezone.DataTimeZone;
import java.io.*; import java.io.*;
import java.lang.System.Logger.Level;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
import static java.lang.System.Logger.Level.WARNING;
public class DataBind implements DataBinder { public class DataBind implements DataBinder {
private final DataTimeZone dataTimeZone; private final DataTimeZone dataTimeZone;
@@ -101,7 +102,7 @@ public class DataBind implements DataBinder {
try { try {
inputStream.close(); inputStream.close();
} catch (IOException e) { } catch (IOException e) {
CoreLog.log.log(Level.WARNING, "Error closing InputStream that was bound to PreparedStatement", e); CoreLog.log.log(WARNING, "Error closing InputStream that was bound to PreparedStatement", e);
} }
} }
inputStreams = null; inputStreams = null;
@@ -29,7 +29,6 @@ import org.joda.time.LocalTime;
import javax.persistence.AttributeConverter; import javax.persistence.AttributeConverter;
import javax.persistence.EnumType; import javax.persistence.EnumType;
import java.io.File; import java.io.File;
import java.lang.System.Logger.Level;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
@@ -45,6 +44,8 @@ import java.time.*;
import java.util.*; import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import static java.lang.System.Logger.Level.*;
/** /**
* Default implementation of TypeManager. * Default implementation of TypeManager.
* <p> * <p>
@@ -219,10 +220,10 @@ public final class DefaultTypeManager implements TypeManager {
} }
private void logAdd(ScalarType<?> scalarType) { private void logAdd(ScalarType<?> scalarType) {
if (log.isLoggable(Level.TRACE)) { if (log.isLoggable(TRACE)) {
String msg = "ScalarType register [" + scalarType.getClass().getName() + "]"; String msg = "ScalarType register [" + scalarType.getClass().getName() + "]";
msg += " for [" + scalarType.getType().getName() + "]"; msg += " for [" + scalarType.getType().getName() + "]";
log.log(Level.TRACE, msg); log.log(TRACE, msg);
} }
} }
@@ -675,7 +676,7 @@ public final class DefaultTypeManager implements TypeManager {
} }
add(scalarType); add(scalarType);
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Error loading ScalarType [" + cls.getName() + "]", e); log.log(ERROR, "Error loading ScalarType [" + cls.getName() + "]", e);
} }
} }
} }
@@ -706,10 +707,10 @@ public final class DefaultTypeManager implements TypeManager {
} }
ScalarTypeConverter converter = foundType.getDeclaredConstructor().newInstance(); ScalarTypeConverter converter = foundType.getDeclaredConstructor().newInstance();
ScalarTypeWrapper stw = new ScalarTypeWrapper(logicalType, wrappedType, converter); ScalarTypeWrapper stw = new ScalarTypeWrapper(logicalType, wrappedType, converter);
log.log(Level.DEBUG, "Register ScalarTypeWrapper from {0} -> {1} using:{2}", logicalType, persistType, foundType); log.log(DEBUG, "Register ScalarTypeWrapper from {0} -> {1} using:{2}", logicalType, persistType, foundType);
add(stw); add(stw);
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Error registering ScalarTypeConverter [" + foundType.getName() + "]", e); log.log(ERROR, "Error registering ScalarTypeConverter [" + foundType.getName() + "]", e);
} }
} }
} }
@@ -730,10 +731,10 @@ public final class DefaultTypeManager implements TypeManager {
} }
AttributeConverter converter = foundType.getDeclaredConstructor().newInstance(); AttributeConverter converter = foundType.getDeclaredConstructor().newInstance();
ScalarTypeWrapper stw = new ScalarTypeWrapper(logicalType, wrappedType, new AttributeConverterAdapter(converter)); ScalarTypeWrapper stw = new ScalarTypeWrapper(logicalType, wrappedType, new AttributeConverterAdapter(converter));
log.log(Level.DEBUG, "Register ScalarTypeWrapper from {0} -> {1} using:{2}", logicalType, persistType, foundType); log.log(DEBUG, "Register ScalarTypeWrapper from {0} -> {1} using:{2}", logicalType, persistType, foundType);
add(stw); add(stw);
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Error registering AttributeConverter [" + foundType.getName() + "]", e); log.log(ERROR, "Error registering AttributeConverter [" + foundType.getName() + "]", e);
} }
} }
} }
@@ -805,7 +806,7 @@ public final class DefaultTypeManager implements TypeManager {
// detect if Joda classes are in the classpath // detect if Joda classes are in the classpath
if (config.getClassLoadConfig().isJodaTimePresent()) { if (config.getClassLoadConfig().isJodaTimePresent()) {
// Joda classes are in the classpath so register the types // Joda classes are in the classpath so register the types
log.log(Level.DEBUG, "Registering Joda data types"); log.log(DEBUG, "Registering Joda data types");
addType(LocalDateTime.class, new ScalarTypeJodaLocalDateTime(jsonDateTime)); addType(LocalDateTime.class, new ScalarTypeJodaLocalDateTime(jsonDateTime));
addType(DateTime.class, new ScalarTypeJodaDateTime(jsonDateTime)); addType(DateTime.class, new ScalarTypeJodaDateTime(jsonDateTime));
if (config.getDatabasePlatform().supportsNativeJavaTime()) { if (config.getDatabasePlatform().supportsNativeJavaTime()) {
@@ -9,10 +9,11 @@ import io.ebean.text.TextException;
import io.ebeaninternal.api.CoreLog; import io.ebeaninternal.api.CoreLog;
import java.io.*; import java.io.*;
import java.lang.System.Logger.Level;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Types; import java.sql.Types;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* ScalarType for streaming between a File and the database. * ScalarType for streaming between a File and the database.
*/ */
@@ -170,14 +171,14 @@ final class ScalarTypeFile extends ScalarTypeBase<File> {
try { try {
output.close(); output.close();
} catch (IOException e) { } catch (IOException e) {
CoreLog.log.log(Level.ERROR, "Error when closing outputStream", e); CoreLog.log.log(ERROR, "Error when closing outputStream", e);
} }
} }
if (input != null) { if (input != null) {
try { try {
input.close(); input.close();
} catch (IOException e) { } catch (IOException e) {
CoreLog.log.log(Level.ERROR, "Error when closing inputStream ", e); CoreLog.log.log(ERROR, "Error when closing inputStream ", e);
} }
} }
} }
@@ -15,10 +15,11 @@ import io.ebeaninternal.extraddl.model.ExtraDdlXmlReader;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import java.io.*; import java.io.*;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import static java.lang.System.Logger.Level.WARNING;
/** /**
* Controls the generation and execution of "Create All" and "Drop All" DDL scripts. * Controls the generation and execution of "Create All" and "Drop All" DDL scripts.
* <p> * <p>
@@ -60,7 +61,7 @@ public class DdlGenerator implements SpiDdlGenerator {
this.platform = databasePlatform.getPlatform(); this.platform = databasePlatform.getPlatform();
this.platformName = platform.base().name(); this.platformName = platform.base().name();
if (!config.getTenantMode().isDdlEnabled() && config.isDdlRun()) { if (!config.getTenantMode().isDdlEnabled() && config.isDdlRun()) {
log.log(Level.WARNING, "DDL can't be run on startup with TenantMode " + config.getTenantMode()); log.log(WARNING, "DDL can't be run on startup with TenantMode " + config.getTenantMode());
this.runDdl = false; this.runDdl = false;
this.useMigrationStoredProcedures = false; this.useMigrationStoredProcedures = false;
} else { } else {
@@ -224,7 +225,7 @@ public class DdlGenerator implements SpiDdlGenerator {
if (sqlScript != null) { if (sqlScript != null) {
try (InputStream is = getClassLoader().getResourceAsStream(sqlScript)) { try (InputStream is = getClassLoader().getResourceAsStream(sqlScript)) {
if (is == null) { if (is == null) {
log.log(Level.WARNING, "sql script {0} was not found as a resource", sqlScript); log.log(WARNING, "sql script {0} was not found as a resource", sqlScript);
} else { } else {
String content = readContent(IOUtils.newReader(is)); // 'is' is closed String content = readContent(IOUtils.newReader(is)); // 'is' is closed
runScript(connection, false, content, sqlScript); runScript(connection, false, content, sqlScript);
@@ -26,13 +26,13 @@ import io.ebeaninternal.extraddl.model.ExtraDdlXmlReader;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.lang.System.Logger.Level;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Properties; import java.util.Properties;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import static io.ebeaninternal.api.PlatformMatch.matchPlatform; import static io.ebeaninternal.api.PlatformMatch.matchPlatform;
import static java.lang.System.Logger.Level.*;
/** /**
* Generates DB Migration xml and sql scripts. * Generates DB Migration xml and sql scripts.
@@ -402,7 +402,7 @@ public class DefaultDbMigration implements DbMigration {
*/ */
private void writeExtraDdl(File migrationDir, DdlScript script) throws IOException { private void writeExtraDdl(File migrationDir, DdlScript script) throws IOException {
String fullName = repeatableMigrationName(script.isInit(), script.getName()); String fullName = repeatableMigrationName(script.isInit(), script.getName());
logger.log(Level.DEBUG, "writing repeatable script {0}", fullName); logger.log(DEBUG, "writing repeatable script {0}", fullName);
File file = new File(migrationDir, fullName); File file = new File(migrationDir, fullName);
try (Writer writer = IOUtils.newWriter(file)) { try (Writer writer = IOUtils.newWriter(file)) {
writer.write(script.getValue()); writer.write(script.getValue());
@@ -419,7 +419,7 @@ public class DefaultDbMigration implements DbMigration {
if (logToSystemOut) { if (logToSystemOut) {
System.out.println("DbMigration> " + message); System.out.println("DbMigration> " + message);
} else { } else {
logger.log(Level.ERROR, message); logger.log(ERROR, message);
} }
} }
@@ -430,7 +430,7 @@ public class DefaultDbMigration implements DbMigration {
if (logToSystemOut) { if (logToSystemOut) {
System.out.println("DbMigration> " + message); System.out.println("DbMigration> " + message);
} else { } else {
logger.log(Level.INFO, message); logger.log(INFO, message);
} }
} }
@@ -792,7 +792,7 @@ public class DefaultDbMigration implements DbMigration {
case SQLSERVER: case SQLSERVER:
throw new IllegalArgumentException("Please choose the more specific SQLSERVER16 or SQLSERVER17 platform. Refer to issue #1340 for details"); throw new IllegalArgumentException("Please choose the more specific SQLSERVER16 or SQLSERVER17 platform. Refer to issue #1340 for details");
case DB2: case DB2:
logger.log(Level.WARNING, "Using DB2LegacyPlatform. It is recommended to migrate to db2luw/db2zos/db2fori. Refer to issue #2514 for details"); logger.log(WARNING, "Using DB2LegacyPlatform. It is recommended to migrate to db2luw/db2zos/db2fori. Refer to issue #2514 for details");
case GENERIC: case GENERIC:
return new DatabasePlatform(); return new DatabasePlatform();
default: default:
@@ -4,11 +4,12 @@ import io.avaje.applog.AppLog;
import io.ebean.migration.MigrationVersion; import io.ebean.migration.MigrationVersion;
import java.io.File; import java.io.File;
import java.lang.System.Logger.Level;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import static java.lang.System.Logger.Level.DEBUG;
/** /**
* Build the model from the series of migrations. * Build the model from the series of migrations.
*/ */
@@ -52,7 +53,7 @@ public class MigrationModel {
if (!initMigration) { if (!initMigration) {
for (MigrationResource migrationResource : resources) { for (MigrationResource migrationResource : resources) {
logger.log(Level.DEBUG, "read {0}", migrationResource); logger.log(DEBUG, "read {0}", migrationResource);
model.apply(migrationResource.read(), migrationResource.version()); model.apply(migrationResource.read(), migrationResource.version());
} }
} }
@@ -15,9 +15,10 @@ import io.ebeaninternal.dbmigration.migration.Migration;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import java.lang.System.Logger.Level;
import java.util.List; import java.util.List;
import static java.lang.System.Logger.Level.ERROR;
/** /**
* Writes migration changes as platform specific DDL. * Writes migration changes as platform specific DDL.
*/ */
@@ -107,7 +108,7 @@ public class PlatformDdlWriter {
File subPath = new File(path, suffix); File subPath = new File(path, suffix);
if (!subPath.exists()) { if (!subPath.exists()) {
if (!subPath.mkdirs()) { if (!subPath.mkdirs()) {
logger.log(Level.ERROR, "failed to create directories for " + subPath.getAbsolutePath()); logger.log(ERROR, "failed to create directories for " + subPath.getAbsolutePath());
} }
} }
return subPath; return subPath;
@@ -8,9 +8,9 @@ import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.lang.System.Logger.Level;
import static io.ebeaninternal.api.PlatformMatch.matchPlatform; import static io.ebeaninternal.api.PlatformMatch.matchPlatform;
import static java.lang.System.Logger.Level.DEBUG;
/** /**
* Read ExtraDdl from an XML document. * Read ExtraDdl from an XML document.
@@ -42,7 +42,7 @@ public class ExtraDdlXmlReader {
StringBuilder sb = new StringBuilder(300); StringBuilder sb = new StringBuilder(300);
for (DdlScript script : read.getDdlScript()) { for (DdlScript script : read.getDdlScript()) {
if (script.isDrop() == drops && matchPlatform(platform, script.getPlatforms())) { if (script.isDrop() == drops && matchPlatform(platform, script.getPlatforms())) {
logger.log(Level.DEBUG, "include script {}", script.getName()); logger.log(DEBUG, "include script {}", script.getName());
String value = script.getValue(); String value = script.getValue();
sb.append(value); sb.append(value);
if (value.lastIndexOf(';') == -1) { if (value.lastIndexOf(';') == -1) {
@@ -7,9 +7,10 @@ import io.ebean.annotation.PersistBatch;
import io.ebean.annotation.Platform; import io.ebean.annotation.Platform;
import io.ebeaninternal.api.SpiEbeanServer; import io.ebeaninternal.api.SpiEbeanServer;
import java.lang.System.Logger.Level;
import java.sql.Types; import java.sql.Types;
import static java.lang.System.Logger.Level.ERROR;
public abstract class BaseTestCase { public abstract class BaseTestCase {
protected static System.Logger logger = AppLog.getLogger(BaseTestCase.class); protected static System.Logger logger = AppLog.getLogger(BaseTestCase.class);
@@ -35,7 +36,7 @@ public abstract class BaseTestCase {
// First try, if we get the default server. If this fails, all tests will fail. // First try, if we get the default server. If this fails, all tests will fail.
DB.getDefault(); DB.getDefault();
} catch (Throwable e) { } catch (Throwable e) {
logger.log(Level.ERROR, "Fatal error while getting ebean-server. Exiting...", e); logger.log(ERROR, "Fatal error while getting ebean-server. Exiting...", e);
System.exit(1); System.exit(1);
} }
} }
@@ -20,9 +20,11 @@ import redis.clients.jedis.params.SetParams;
import redis.clients.jedis.resps.ScanResult; import redis.clients.jedis.resps.ScanResult;
import redis.clients.jedis.util.SafeEncoder; import redis.clients.jedis.util.SafeEncoder;
import java.lang.System.Logger.Level;
import java.util.*; import java.util.*;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.WARNING;
final class RedisCache implements ServerCache { final class RedisCache implements ServerCache {
private static final System.Logger log = AppLog.getLogger(RedisCache.class); private static final System.Logger log = AppLog.getLogger(RedisCache.class);
@@ -106,17 +108,17 @@ final class RedisCache implements ServerCache {
} }
return valueEncode.decode(data); return valueEncode.decode(data);
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Error decoding data, treated as cache miss", e); log.log(ERROR, "Error decoding data, treated as cache miss", e);
return null; return null;
} }
} }
private void errorOnRead(Exception e) { private void errorOnRead(Exception e) {
log.log(Level.WARNING, "Error when reading redis cache", e); log.log(WARNING, "Error when reading redis cache", e);
} }
private void errorOnWrite(Exception e) { private void errorOnWrite(Exception e) {
log.log(Level.WARNING, "Error when writing redis cache", e); log.log(WARNING, "Error when writing redis cache", e);
} }
@Override @Override
@@ -21,7 +21,6 @@ import redis.clients.jedis.JedisPool;
import redis.clients.jedis.util.SafeEncoder; import redis.clients.jedis.util.SafeEncoder;
import java.io.*; import java.io.*;
import java.lang.System.Logger.Level;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Map; import java.util.Map;
@@ -29,6 +28,7 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import static java.lang.System.Logger.Level.*;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
final class RedisCacheFactory implements ServerCacheFactory { final class RedisCacheFactory implements ServerCacheFactory {
@@ -105,7 +105,7 @@ final class RedisCacheFactory implements ServerCacheFactory {
redisConfig = new RedisConfig(); redisConfig = new RedisConfig();
} }
redisConfig.loadProperties(config.getProperties()); redisConfig.loadProperties(config.getProperties());
log.log(Level.INFO, "using l2cache redis host {0}:{1}", redisConfig.getServer(), redisConfig.getPort()); log.log(INFO, "using l2cache redis host {0}:{1}", redisConfig.getServer(), redisConfig.getPort());
return redisConfig.createPool(); return redisConfig.createPool();
} }
@@ -160,7 +160,7 @@ final class RedisCacheFactory implements ServerCacheFactory {
try { try {
RQueryCache cache = queryCaches.get(config.getCacheKey()); RQueryCache cache = queryCaches.get(config.getCacheKey());
if (cache == null) { if (cache == null) {
logger.log(Level.DEBUG, "create query cache [{0}]", config.getCacheKey()); logger.log(DEBUG, "create query cache [{0}]", config.getCacheKey());
cache = new RQueryCache(new DefaultServerCacheConfig(config)); cache = new RQueryCache(new DefaultServerCacheConfig(config));
cache.periodicTrim(executor); cache.periodicTrim(executor);
queryCaches.put(config.getCacheKey(), cache); queryCaches.put(config.getCacheKey(), cache);
@@ -214,7 +214,7 @@ final class RedisCacheFactory implements ServerCacheFactory {
* Process the invalidation message coming from the cluster. * Process the invalidation message coming from the cluster.
*/ */
private void invalidate() { private void invalidate() {
queryLogger.log(Level.DEBUG, " CLEAR {0}(*) - cluster invalidate", name); queryLogger.log(DEBUG, " CLEAR {0}(*) - cluster invalidate", name);
super.clear(); super.clear();
} }
} }
@@ -233,8 +233,8 @@ final class RedisCacheFactory implements ServerCacheFactory {
msg.append(table).append(","); msg.append(table).append(",");
} }
String formattedMsg = msg.toString(); String formattedMsg = msg.toString();
if (tableModLogger.isLoggable(Level.DEBUG)) { if (tableModLogger.isLoggable(DEBUG)) {
tableModLogger.log(Level.DEBUG, "Publish TableMods - {0}", formattedMsg); tableModLogger.log(DEBUG, "Publish TableMods - {0}", formattedMsg);
} }
sendTableMod(formattedMsg); sendTableMod(formattedMsg);
} }
@@ -262,8 +262,8 @@ final class RedisCacheFactory implements ServerCacheFactory {
private void processTableNotify(String rawMessage) { private void processTableNotify(String rawMessage) {
long nanos = System.nanoTime(); long nanos = System.nanoTime();
try { try {
if (logger.isLoggable(Level.DEBUG)) { if (logger.isLoggable(DEBUG)) {
logger.log(Level.DEBUG, "processTableNotify {0}", rawMessage); logger.log(DEBUG, "processTableNotify {0}", rawMessage);
} }
Set<String> tables = new HashSet<>(asList(rawMessage.split(","))); Set<String> tables = new HashSet<>(asList(rawMessage.split(",")));
listener.notify(new ServerCacheNotification(tables)); listener.notify(new ServerCacheNotification(tables));
@@ -282,7 +282,7 @@ final class RedisCacheFactory implements ServerCacheFactory {
try { try {
sendMessage(messageInvalidateKeys(cacheKey, keySet)); sendMessage(messageInvalidateKeys(cacheKey, keySet));
} catch (IOException e) { } catch (IOException e) {
logger.log(Level.ERROR, "failed to transmit invalidateKeys() message", e); logger.log(ERROR, "failed to transmit invalidateKeys() message", e);
} }
} }
@@ -291,7 +291,7 @@ final class RedisCacheFactory implements ServerCacheFactory {
try { try {
sendMessage(messageInvalidateKey(cacheKey, id)); sendMessage(messageInvalidateKey(cacheKey, id));
} catch (IOException e) { } catch (IOException e) {
logger.log(Level.ERROR, "failed to transmit invalidateKeys() message", e); logger.log(ERROR, "failed to transmit invalidateKeys() message", e);
} }
} }
@@ -300,7 +300,7 @@ final class RedisCacheFactory implements ServerCacheFactory {
try { try {
sendMessage(messageInvalidateClear(cacheKey)); sendMessage(messageInvalidateClear(cacheKey));
} catch (IOException e) { } catch (IOException e) {
logger.log(Level.ERROR, "failed to transmit invalidateKeys() message", e); logger.log(ERROR, "failed to transmit invalidateKeys() message", e);
} }
} }
@@ -364,7 +364,7 @@ final class RedisCacheFactory implements ServerCacheFactory {
@Override @Override
public void notifyConnected() { public void notifyConnected() {
logger.log(Level.INFO, "Established connection to Redis"); logger.log(INFO, "Established connection to Redis");
} }
/** /**
@@ -395,8 +395,8 @@ final class RedisCacheFactory implements ServerCacheFactory {
} }
msgType = oi.readInt(); msgType = oi.readInt();
cacheKey = oi.readUTF(); cacheKey = oi.readUTF();
if (logger.isLoggable(Level.DEBUG)) { if (logger.isLoggable(DEBUG)) {
logger.log(Level.DEBUG, "processNearCacheMessage serverId:{0} type:{1} cacheKey:{2}", sourceServerId, msgType, cacheKey); logger.log(DEBUG, "processNearCacheMessage serverId:{0} type:{1} cacheKey:{2}", sourceServerId, msgType, cacheKey);
} }
switch (msgType) { switch (msgType) {
@@ -423,7 +423,7 @@ final class RedisCacheFactory implements ServerCacheFactory {
} }
} catch (IOException | ClassNotFoundException e) { } catch (IOException | ClassNotFoundException e) {
logger.log(Level.ERROR, "failed to decode near cache message [" + SafeEncoder.encode(message) + "] for cache:" + cacheKey, e); logger.log(ERROR, "failed to decode near cache message [" + SafeEncoder.encode(message) + "] for cache:" + cacheKey, e);
if (cacheKey != null) { if (cacheKey != null) {
nearCacheInvalidateClear(cacheKey); nearCacheInvalidateClear(cacheKey);
} }
@@ -449,10 +449,10 @@ final class RedisCacheFactory implements ServerCacheFactory {
queryCacheInvalidate(split[2]); queryCacheInvalidate(split[2]);
break; break;
default: default:
logger.log(Level.ERROR, "Unknown L2 message type[{0}] on redis channel - message[{1}] ", split[0], message); logger.log(ERROR, "Unknown L2 message type[{0}] on redis channel - message[{1}] ", split[0], message);
} }
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.ERROR, "Error handling L2 message[" + message + "]", e); logger.log(ERROR, "Error handling L2 message[" + message + "]", e);
} }
} }
} }
@@ -495,7 +495,7 @@ final class RedisCacheFactory implements ServerCacheFactory {
} }
private void warnNearCacheNotFound(String cacheKey) { private void warnNearCacheNotFound(String cacheKey) {
logger.log(Level.WARNING, "No near cache found for cacheKey [" + cacheKey + "] yet - probably on startup"); logger.log(WARNING, "No near cache found for cacheKey [" + cacheKey + "] yet - probably on startup");
} }
} }
@@ -5,10 +5,11 @@ import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.exceptions.JedisException;
import java.lang.System.Logger.Level;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import static java.lang.System.Logger.Level.*;
/** /**
* Subscribe to redis topic listening for changes. * Subscribe to redis topic listening for changes.
* <p> * <p>
@@ -49,13 +50,13 @@ public final class DaemonTopicRunner {
try { try {
subscribe(); subscribe();
} catch (JedisException e) { } catch (JedisException e) {
log.log(Level.DEBUG, "... redis subscribe connection attempt:{0} failed:{1}", attempts, e.getMessage()); log.log(DEBUG, "... redis subscribe connection attempt:{0} failed:{1}", attempts, e.getMessage());
try { try {
// wait a little before retrying // wait a little before retrying
Thread.sleep(reconnectWaitMillis); Thread.sleep(reconnectWaitMillis);
} catch (InterruptedException e1) { } catch (InterruptedException e1) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
log.log(Level.WARNING, "Interrupted redis re-connection wait", e1); log.log(WARNING, "Interrupted redis re-connection wait", e1);
} }
} }
} }
@@ -70,13 +71,13 @@ public final class DaemonTopicRunner {
try { try {
daemonTopic.subscribe(jedis); daemonTopic.subscribe(jedis);
} catch (Exception e) { } catch (Exception e) {
log.log(Level.ERROR, "Lost connection to topic, starting re-connection loop", e); log.log(ERROR, "Lost connection to topic, starting re-connection loop", e);
attemptConnections(); attemptConnections();
} finally { } finally {
try { try {
jedis.close(); jedis.close();
} catch (Exception e) { } catch (Exception e) {
log.log(Level.WARNING, "Error closing probably broken Redis connection", e); log.log(WARNING, "Error closing probably broken Redis connection", e);
} }
} }
} }
@@ -4,7 +4,8 @@ import io.avaje.applog.AppLog;
import io.ebeaninternal.api.SpiLogger; import io.ebeaninternal.api.SpiLogger;
import io.ebeaninternal.api.SpiLoggerFactory; import io.ebeaninternal.api.SpiLoggerFactory;
import java.lang.System.Logger.Level; import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.TRACE;
/** /**
* Create a logger that captures the SQL and register it for later access in tests. * Create a logger that captures the SQL and register it for later access in tests.
@@ -33,22 +34,22 @@ public class CapturingLoggerFactory implements SpiLoggerFactory {
@Override @Override
public boolean isDebug() { public boolean isDebug() {
return logger.isLoggable(Level.DEBUG); return logger.isLoggable(DEBUG);
} }
@Override @Override
public boolean isTrace() { public boolean isTrace() {
return logger.isLoggable(Level.TRACE); return logger.isLoggable(TRACE);
} }
@Override @Override
public void debug(String msg) { public void debug(String msg) {
logger.log(Level.DEBUG, msg); logger.log(DEBUG, msg);
} }
@Override @Override
public void trace(String msg) { public void trace(String msg) {
logger.log(Level.TRACE, msg); logger.log(TRACE, msg);
} }
} }
} }
@@ -8,9 +8,11 @@ import io.ebean.test.config.platform.PlatformAutoConfig;
import io.ebean.test.config.provider.ProviderAutoConfig; import io.ebean.test.config.provider.ProviderAutoConfig;
import io.ebean.test.containers.DockerHost; import io.ebean.test.containers.DockerHost;
import java.lang.System.Logger.Level;
import java.util.Properties; import java.util.Properties;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Automatically configure ServerConfig for testing purposes. * Automatically configure ServerConfig for testing purposes.
* <p> * <p>
@@ -38,7 +40,7 @@ public class AutoConfigureForTesting implements AutoConfigure {
io.avaje.config.Config.asConfiguration().evalModify(properties); io.avaje.config.Config.asConfiguration().evalModify(properties);
} }
if (!config.isDefaultServer()) { if (!config.isDefaultServer()) {
log.log(Level.INFO, "skip automatic testing config on non-default server name:{0} register:{1}", config.getName(), config.isRegister()); log.log(INFO, "skip automatic testing config on non-default server name:{0} register:{1}", config.getName(), config.isRegister());
return; return;
} }
if (isExtraServer(config, properties)) { if (isExtraServer(config, properties)) {
@@ -46,7 +48,7 @@ public class AutoConfigureForTesting implements AutoConfigure {
return; return;
} }
String testPlatform = properties.getProperty("ebean.test.platform"); String testPlatform = properties.getProperty("ebean.test.platform");
log.log(Level.DEBUG, "automatic testing config - with ebean.test.platform:{0} name:{1} environmentDb:{2}", testPlatform, config.getName(), environmentDb); log.log(DEBUG, "automatic testing config - with ebean.test.platform:{0} name:{1} environmentDb:{2}", testPlatform, config.getName(), environmentDb);
if (RunOnceMarker.isRun()) { if (RunOnceMarker.isRun()) {
setupPlatform(environmentDb, config); setupPlatform(environmentDb, config);
} }
@@ -5,9 +5,10 @@ import io.ebean.config.DatabaseConfig;
import io.ebean.datasource.DataSourceConfig; import io.ebean.datasource.DataSourceConfig;
import io.ebean.test.containers.DockerHost; import io.ebean.test.containers.DockerHost;
import java.lang.System.Logger.Level;
import java.util.Properties; import java.util.Properties;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Config for a database / datasource with associated DDL mode and Docker configuration. * Config for a database / datasource with associated DDL mode and Docker configuration.
*/ */
@@ -193,8 +194,7 @@ class Config {
ds.setDriver(driverClass); ds.setDriver(driverClass);
config.setDataSourceConfig(ds); config.setDataSourceConfig(ds);
log.log(Level.INFO, "Using jdbc settings - username:{0} url:{1} driver:{2}", ds.getUsername(), ds.getUrl(), ds.getDriver()); log.log(INFO, "Using jdbc settings - username:{0} url:{1} driver:{2}", ds.getUsername(), ds.getUrl(), ds.getDriver());
if (driverClass != null) { if (driverClass != null) {
try { try {
Class.forName(driverClass); Class.forName(driverClass);
@@ -4,11 +4,11 @@ import io.avaje.applog.AppLog;
import io.ebean.config.DatabaseConfig; import io.ebean.config.DatabaseConfig;
import io.ebean.test.containers.ContainerFactory; import io.ebean.test.containers.ContainerFactory;
import java.lang.System.Logger.Level;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import static java.lang.System.Logger.Level.*;
import static java.util.concurrent.CompletableFuture.allOf; import static java.util.concurrent.CompletableFuture.allOf;
import static java.util.concurrent.CompletableFuture.runAsync; import static java.util.concurrent.CompletableFuture.runAsync;
@@ -62,7 +62,7 @@ public class PlatformAutoConfig {
Config config = new Config(db, platform, databaseName, this.config); Config config = new Config(db, platform, databaseName, this.config);
platformSetup.setupExtraDbDataSource(config); platformSetup.setupExtraDbDataSource(config);
log.log(Level.DEBUG, "configured dataSource for extraDb name:{0} url:{1}", db, this.config.getDataSourceConfig().getUrl()); log.log(DEBUG, "configured dataSource for extraDb name:{0} url:{1}", db, this.config.getDataSourceConfig().getUrl());
} }
} }
@@ -92,9 +92,9 @@ public class PlatformAutoConfig {
Properties dockerProperties = platformSetup.setup(config); Properties dockerProperties = platformSetup.setup(config);
if (!dockerProperties.isEmpty()) { if (!dockerProperties.isEmpty()) {
if (isDebug()) { if (isDebug()) {
log.log(Level.INFO, "Docker properties: {0}", dockerProperties); log.log(INFO, "Docker properties: {0}", dockerProperties);
} else { } else {
log.log(Level.DEBUG, "Docker properties: {0}", dockerProperties); log.log(DEBUG, "Docker properties: {0}", dockerProperties);
} }
// start the docker container with appropriate configuration // start the docker container with appropriate configuration
new ContainerFactory(dockerProperties, config.getDockerPlatform()).startContainers(); new ContainerFactory(dockerProperties, config.getDockerPlatform()).startContainers();
@@ -130,7 +130,7 @@ public class PlatformAutoConfig {
} }
this.platformSetup = KNOWN_PLATFORMS.get(platform); this.platformSetup = KNOWN_PLATFORMS.get(platform);
if (platformSetup == null) { if (platformSetup == null) {
log.log(Level.WARNING, "unknown platform {0} - skipping platform setup", platform); log.log(WARNING, "unknown platform {0} - skipping platform setup", platform);
} }
return platformSetup != null; return platformSetup != null;
} }
@@ -6,9 +6,11 @@ import io.ebean.config.CurrentUserProvider;
import io.ebean.config.DatabaseConfig; import io.ebean.config.DatabaseConfig;
import io.ebean.config.EncryptKeyManager; import io.ebean.config.EncryptKeyManager;
import java.lang.System.Logger.Level;
import java.util.Properties; import java.util.Properties;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.INFO;
/** /**
* Auto configuration of User and Tenant providers and Encrypt key manager for testing purposes. * Auto configuration of User and Tenant providers and Encrypt key manager for testing purposes.
*/ */
@@ -44,12 +46,12 @@ public class ProviderAutoConfig {
if (keyManager == null) { if (keyManager == null) {
// Must be 16 Chars for Oracle function // Must be 16 Chars for Oracle function
String keyVal = properties.getProperty("ebean.test.encryptKey", "simple0123456789"); String keyVal = properties.getProperty("ebean.test.encryptKey", "simple0123456789");
log.log(Level.DEBUG, "for testing - using FixedEncryptKeyManager() keyVal:{0}", keyVal); log.log(DEBUG, "for testing - using FixedEncryptKeyManager() keyVal:{0}", keyVal);
config.setEncryptKeyManager(new FixedEncryptKeyManager(keyVal)); config.setEncryptKeyManager(new FixedEncryptKeyManager(keyVal));
} }
if (providerSetFlag > 0) { if (providerSetFlag > 0) {
log.log(Level.INFO, msg(providerSetFlag)); log.log(INFO, msg(providerSetFlag));
} }
} }
@@ -3,13 +3,14 @@ package io.ebean.platform.h2;
import io.avaje.applog.AppLog; import io.avaje.applog.AppLog;
import org.h2.api.Trigger; import org.h2.api.Trigger;
import java.lang.System.Logger.Level;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import static java.lang.System.Logger.Level.DEBUG;
/** /**
* H2 database trigger used to populate history tables to support the @History feature. * H2 database trigger used to populate history tables to support the @History feature.
*/ */
@@ -72,7 +73,7 @@ public class H2HistoryTrigger implements Trigger {
insertSql.append(");"); insertSql.append(");");
this.insertHistorySql = insertSql.toString(); this.insertHistorySql = insertSql.toString();
log.log(Level.DEBUG, "History table insert sql: {0}", insertHistorySql); log.log(DEBUG, "History table insert sql: {0}", insertHistorySql);
} }
@Override @Override