From 65644bf797329c43c7b1733109d84d357fa4211b Mon Sep 17 00:00:00 2001 From: rma-rripken <89810919+rma-rripken@users.noreply.github.com> Date: Tue, 18 Nov 2025 14:34:20 -0800 Subject: [PATCH 1/4] Replacing java.util.logging.Logger with FluentLogger. --- .../java/cwms/cda/api/BasinController.java | 7 ++-- .../cda/api/BinaryTimeSeriesController.java | 7 ++-- .../java/cwms/cda/api/CatalogController.java | 6 ++-- .../cda/api/ForecastTimeseriesController.java | 2 -- .../cda/api/LocationCategoryController.java | 17 +++------- .../java/cwms/cda/api/LocationController.java | 13 ++++---- .../cwms/cda/api/LocationGroupController.java | 11 +++---- .../cwms/cda/api/ParametersController.java | 7 ++-- .../java/cwms/cda/api/PoolController.java | 9 ++---- .../java/cwms/cda/api/ProjectController.java | 9 ++---- .../cda/api/SpecifiedLevelController.java | 7 ++-- .../cda/api/TextTimeSeriesController.java | 7 ++-- .../cda/api/TimeSeriesCategoryController.java | 7 ++-- .../cwms/cda/api/TimeSeriesController.java | 13 ++++---- .../cda/api/TimeSeriesFilteredController.java | 9 +++--- .../cda/api/TimeSeriesGroupController.java | 8 ++--- ...eSeriesIdentifierDescriptorController.java | 11 +++---- .../cda/api/TimeSeriesRecentController.java | 9 +++--- .../java/cwms/cda/api/TimeZoneController.java | 7 ++-- .../java/cwms/cda/api/UnitsController.java | 7 ++-- .../cwms/cda/api/rating/RatingController.java | 20 ++++++------ .../api/rating/RatingMetadataController.java | 7 ++-- .../cda/api/rating/RatingSpecController.java | 9 +++--- .../api/rating/RatingTemplateController.java | 9 +++--- .../AccountingCatalogController.java | 9 +++--- .../java/cwms/cda/data/dao/CdaVersionDao.java | 7 ++-- .../main/java/cwms/cda/data/dao/ClobDao.java | 3 +- .../cda/data/dao/LocationLevelsDaoImpl.java | 15 +++++---- .../cwms/cda/data/dao/LocationsDaoImpl.java | 17 +++++----- .../main/java/cwms/cda/data/dao/PoolDao.java | 9 +++--- .../cwms/cda/data/dao/RatingMetadataDao.java | 7 ++-- .../java/cwms/cda/data/dao/RatingSpecDao.java | 15 +++++---- .../cwms/cda/data/dao/RatingTemplateDao.java | 19 +++++------ .../cwms/cda/data/dao/TimeSeriesDaoImpl.java | 32 +++++++++---------- .../cwms/cda/data/dao/TimeSeriesGroupDao.java | 10 +++--- .../main/java/cwms/cda/data/dao/UserDao.java | 7 ++-- .../TimeSeriesProfileInstanceDao.java | 14 ++++---- .../dao/watersupply/WaterSupplyUtils.java | 9 +++--- .../cwms/cda/data/dto/CwmsDTOPaginated.java | 6 ++-- .../DelegatingConnectionPreparer.java | 8 ++--- .../java/cwms/cda/formatters/Formats.java | 19 ++++++----- .../java/cwms/cda/formatters/xml/XMLv1.java | 9 +++--- .../java/cwms/cda/formatters/xml/XMLv2.java | 9 +++--- .../cwms/cda/formatters/xml/XMLv2Office.java | 9 +++--- .../java/cwms/cda/helpers/ResourceHelper.java | 7 ++-- .../cda/security/CwmsAaaIdentityProvider.java | 11 +++---- 46 files changed, 215 insertions(+), 254 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/api/BasinController.java b/cwms-data-api/src/main/java/cwms/cda/api/BasinController.java index 38297aa42..bf24ef92b 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/BasinController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/BasinController.java @@ -60,15 +60,14 @@ import java.sql.SQLException; import java.util.Collections; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; public class BasinController implements CrudHandler { - private static final Logger LOGGER = Logger.getLogger(BasinController.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); public static final String TAG = "Basins"; private final MetricRegistry metrics; @@ -143,7 +142,7 @@ public void getAll(@NotNull Context ctx) { ctx.status(HttpServletResponse.SC_OK); } catch (SQLException ex) { CdaError error = new CdaError("Error retrieving all basins"); - LOGGER.log(Level.SEVERE, "Error retrieving all basins", ex); + LOGGER.atSevere().withCause(ex).log("Error retrieving all basins"); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(error); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/BinaryTimeSeriesController.java b/cwms-data-api/src/main/java/cwms/cda/api/BinaryTimeSeriesController.java index 12dc6b62b..767f1ed36 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/BinaryTimeSeriesController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/BinaryTimeSeriesController.java @@ -63,8 +63,7 @@ import java.net.URISyntaxException; import java.net.URLEncoder; import java.time.Instant; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.apache.http.client.utils.URIBuilder; import org.jetbrains.annotations.NotNull; @@ -72,7 +71,7 @@ public class BinaryTimeSeriesController implements CrudHandler { - private static final Logger logger = Logger.getLogger(BinaryTimeSeriesController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); static final String TAG = "Binary-TimeSeries"; public static final String REPLACE_ALL = "replace-all"; @@ -172,7 +171,7 @@ public void getAll(@NotNull Context ctx) { } catch (URISyntaxException | UnsupportedEncodingException ex) { CdaError re = new CdaError("Failed to process request: " + ex.getLocalizedMessage()); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/CatalogController.java b/cwms-data-api/src/main/java/cwms/cda/api/CatalogController.java index af9cc6093..59a1be385 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/CatalogController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/CatalogController.java @@ -30,14 +30,14 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; import org.owasp.html.PolicyFactory; public class CatalogController implements CrudHandler { - private static final Logger logger = Logger.getLogger(CatalogController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String TAG = "Catalog"; public static final boolean INCLUDE_EXTENTS_DEFAULT = true; public static final boolean EXCLUDE_EMPTY_DEFAULT = true; @@ -285,7 +285,7 @@ public void getOne(@NotNull Context ctx, @NotNull String dataSet) { final CdaError re = new CdaError("Cannot create catalog of requested " + "information"); - logger.info(() -> re + " with url:" + ctx.fullUrl()); + logger.atInfo().log("%s with url:%s", re, ctx.fullUrl()); ctx.json(re).status(HttpCode.NOT_FOUND); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/ForecastTimeseriesController.java b/cwms-data-api/src/main/java/cwms/cda/api/ForecastTimeseriesController.java index ef24510f5..ce604c26c 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/ForecastTimeseriesController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/ForecastTimeseriesController.java @@ -15,7 +15,6 @@ import io.javalin.plugin.openapi.annotations.OpenApiRequestBody; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; -import java.util.logging.Logger; import static com.codahale.metrics.MetricRegistry.name; import static cwms.cda.api.Controllers.FORECAST_DATE; @@ -30,7 +29,6 @@ import static cwms.cda.api.Controllers.TIMESERIES_ID; public class ForecastTimeseriesController implements CrudHandler { - private static final Logger logger = Logger.getLogger(ForecastSpecController.class.getName()); public static final String TAG = "Forecast"; private final MetricRegistry metrics; diff --git a/cwms-data-api/src/main/java/cwms/cda/api/LocationCategoryController.java b/cwms-data-api/src/main/java/cwms/cda/api/LocationCategoryController.java index bd1e269ac..35c4cf6cd 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/LocationCategoryController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/LocationCategoryController.java @@ -47,14 +47,13 @@ import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.util.List; import java.util.Optional; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; public class LocationCategoryController implements CrudHandler { - public static final Logger logger = - Logger.getLogger(LocationCategoryController.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String TAG = "Location Categories"; private final MetricRegistry metrics; @@ -111,11 +110,7 @@ public void getAll(Context ctx) { CdaError re = new CdaError("Cannot find requested location category for " + "office provided: " + office); - logger.info(() -> { - StringBuilder builder = new StringBuilder(re.toString()) - .append("with url:").append(ctx.fullUrl()); - return builder.toString(); - }); + logger.atInfo().log("%s with url:%s", re, ctx.fullUrl()); ctx.json(re).status(HttpServletResponse.SC_NOT_FOUND); } @@ -167,11 +162,7 @@ public void getOne(Context ctx, @NotNull String categoryId) { CdaError re = new CdaError("Cannot find requested location category id: " + categoryId + " with office: " + office); - logger.info(() -> { - StringBuilder builder = new StringBuilder(re.toString()) - .append("with url:").append(ctx.fullUrl()); - return builder.toString(); - }); + logger.atInfo().log("%s with url:%s", re, ctx.fullUrl()); ctx.json(re).status(HttpServletResponse.SC_NOT_FOUND); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/LocationController.java b/cwms-data-api/src/main/java/cwms/cda/api/LocationController.java index d0cd39f6b..f94bfd5b3 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/LocationController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/LocationController.java @@ -63,8 +63,7 @@ import java.io.IOException; import java.sql.SQLException; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.geojson.FeatureCollection; import org.jetbrains.annotations.NotNull; @@ -73,7 +72,7 @@ public class LocationController implements CrudHandler { - public static final Logger logger = Logger.getLogger(LocationController.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final MetricRegistry metrics; private final Histogram requestResultSize; @@ -199,7 +198,7 @@ public void getAll(@NotNull Context ctx) { } catch (Exception ex) { CdaError re = new CdaError("failed to process request"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re.toString()); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } @@ -254,7 +253,7 @@ public void getOne(@NotNull Context ctx, @NotNull String name) { String errorMsg = "Error retrieving " + name; CdaError re = new CdaError(errorMsg); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); - logger.log(Level.SEVERE, errorMsg, ex); + logger.atSevere().withCause(ex).log("%s", errorMsg); } } @@ -295,7 +294,7 @@ public void create(@NotNull Context ctx) { ctx.status(HttpServletResponse.SC_CREATED).json(re); } catch (IOException ex) { CdaError re = new CdaError("failed to process request"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re.toString()); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } @@ -347,7 +346,7 @@ public void update(@NotNull Context ctx, @NotNull String locationId) { } catch (IOException ex) { CdaError re = new CdaError("Failed to process request: " + ex.getLocalizedMessage()); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re.toString()); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/LocationGroupController.java b/cwms-data-api/src/main/java/cwms/cda/api/LocationGroupController.java index d6083bf62..235827eac 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/LocationGroupController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/LocationGroupController.java @@ -50,15 +50,14 @@ import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.util.List; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.geojson.FeatureCollection; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; public class LocationGroupController implements CrudHandler { - public static final Logger logger = Logger.getLogger(LocationGroupController.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String LOCATION_OFFICE_ID = "location-office-id"; public static final String TAG = "Location Groups"; @@ -136,7 +135,7 @@ Boolean.class, false, metrics, name(LocationGroupController.class.getName(), ctx.status(HttpServletResponse.SC_OK); } else { CdaError re = new CdaError("No location groups for office provided"); - logger.info(() -> re + System.lineSeparator() + "for request " + ctx.fullUrl()); + logger.atInfo().log("%s%nfor request %s", re, ctx.fullUrl()); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re); } @@ -200,7 +199,7 @@ public void getOne(@NotNull Context ctx, @NotNull String groupId) { result = Formats.format(contentType, grp.get()); } else { CdaError re = new CdaError("Unable to find location group based on parameters given"); - logger.info(() -> re + System.lineSeparator() + "for request " + ctx.fullUrl()); + logger.atInfo().log("%s%nfor request %s", re, ctx.fullUrl()); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re); return; } @@ -214,7 +213,7 @@ public void getOne(@NotNull Context ctx, @NotNull String groupId) { ctx.status(HttpServletResponse.SC_OK); } catch (JsonProcessingException e) { CdaError re = new CdaError("Failed to process request"); - logger.log(Level.SEVERE, re.toString(), e); + logger.atSevere().withCause(e).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/ParametersController.java b/cwms-data-api/src/main/java/cwms/cda/api/ParametersController.java index c7566f989..076320792 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/ParametersController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/ParametersController.java @@ -29,13 +29,12 @@ import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jooq.DSLContext; public class ParametersController implements CrudHandler { - private static final Logger logger = Logger.getLogger(ParametersController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final MetricRegistry metrics; private final Histogram requestResultSize; @@ -131,7 +130,7 @@ public void getAll(Context ctx) { requestResultSize.update(results.length()); } catch (Exception ex) { CdaError re = new CdaError("Failed to process request"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/PoolController.java b/cwms-data-api/src/main/java/cwms/cda/api/PoolController.java index 657206a9b..7a2dd82b5 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/PoolController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/PoolController.java @@ -41,13 +41,13 @@ import io.javalin.plugin.openapi.annotations.OpenApiContent; import io.javalin.plugin.openapi.annotations.OpenApiParam; import io.javalin.plugin.openapi.annotations.OpenApiResponse; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; public class PoolController implements CrudHandler { - public static final Logger logger = Logger.getLogger(PoolController.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int defaultPageSize = 100; private final MetricRegistry metrics; @@ -206,10 +206,7 @@ public void getOne(@NotNull Context ctx, @NotNull String poolId) { if (pool == null) { CdaError re = new CdaError("Unable to find pool based on parameters given"); - logger.info(() -> { - String fullUrl = ctx.fullUrl(); - return re + System.lineSeparator() + "for request " + fullUrl; - }); + logger.atInfo().log("%s%nfor request %s", re, ctx.fullUrl()); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re); } else { String formatHeader = ctx.header(Header.ACCEPT); diff --git a/cwms-data-api/src/main/java/cwms/cda/api/ProjectController.java b/cwms-data-api/src/main/java/cwms/cda/api/ProjectController.java index 7b42139c9..4261d016b 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/ProjectController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/ProjectController.java @@ -65,13 +65,13 @@ import io.javalin.plugin.openapi.annotations.OpenApiParam; import io.javalin.plugin.openapi.annotations.OpenApiRequestBody; import io.javalin.plugin.openapi.annotations.OpenApiResponse; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; public class ProjectController implements CrudHandler { - public static final Logger logger = Logger.getLogger(ProjectController.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int DEFAULT_PAGE_SIZE = 100; public static final String TAG = "Projects"; @@ -177,10 +177,7 @@ public void getOne(@NotNull Context ctx, @NotNull String name) { if (project == null) { CdaError re = new CdaError("Unable to find Project based on parameters given"); - logger.info(() -> { - String fullUrl = ctx.fullUrl(); - return re + System.lineSeparator() + "for request " + fullUrl; - }); + logger.atInfo().log("%s%nfor request %s", re, ctx.fullUrl()); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re); } else { String formatHeader = ctx.header(Header.ACCEPT); diff --git a/cwms-data-api/src/main/java/cwms/cda/api/SpecifiedLevelController.java b/cwms-data-api/src/main/java/cwms/cda/api/SpecifiedLevelController.java index 309502d26..1686f6e63 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/SpecifiedLevelController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/SpecifiedLevelController.java @@ -41,8 +41,7 @@ import javax.servlet.http.HttpServletResponse; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import static com.codahale.metrics.MetricRegistry.name; import static cwms.cda.api.Controllers.*; @@ -50,7 +49,7 @@ public class SpecifiedLevelController implements CrudHandler { - private static final Logger logger = Logger.getLogger(SpecifiedLevelController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String TAG = "Levels"; private final MetricRegistry metrics; @@ -114,7 +113,7 @@ public void getAll(Context ctx) { } catch (Exception ex) { CdaError re = new CdaError("Failed to process request: " + ex.getLocalizedMessage()); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TextTimeSeriesController.java b/cwms-data-api/src/main/java/cwms/cda/api/TextTimeSeriesController.java index 6638d2650..4e557631e 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TextTimeSeriesController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TextTimeSeriesController.java @@ -48,8 +48,7 @@ import java.net.URISyntaxException; import java.net.URLEncoder; import java.time.Instant; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.apache.http.client.utils.URIBuilder; import org.jetbrains.annotations.NotNull; @@ -58,7 +57,7 @@ public class TextTimeSeriesController implements CrudHandler { - private static final Logger logger = Logger.getLogger(TextTimeSeriesController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); static final String TAG = "Text-TimeSeries"; public static final String REPLACE_ALL = "replace-all"; @@ -153,7 +152,7 @@ public void getAll(@NotNull Context ctx) { } catch (URISyntaxException | UnsupportedEncodingException ex) { CdaError re = new CdaError("Failed to process request: " + ex.getLocalizedMessage()); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesCategoryController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesCategoryController.java index 4de269573..0993bee92 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesCategoryController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesCategoryController.java @@ -47,14 +47,13 @@ import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.util.List; import java.util.Optional; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; public class TimeSeriesCategoryController implements CrudHandler { - public static final Logger logger = - Logger.getLogger(TimeSeriesCategoryController.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String TAG = "TimeSeries Categories"; private final MetricRegistry metrics; @@ -152,7 +151,7 @@ public void getOne(Context ctx, @NotNull String categoryId) { ctx.status(HttpServletResponse.SC_OK); } else { CdaError re = new CdaError("Unable to find category based on parameters given"); - logger.info(() -> re + System.lineSeparator() + "for request " + ctx.fullUrl()); + logger.atInfo().log("%s%nfor request %s", re, ctx.fullUrl()); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesController.java index 6789cdf67..1ae141920 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesController.java @@ -36,8 +36,7 @@ import java.sql.Timestamp; import java.time.ZoneId; import java.time.ZonedDateTime; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.http.client.utils.URIBuilder; @@ -47,7 +46,7 @@ import org.jooq.exception.DataAccessException; public class TimeSeriesController implements CrudHandler { - private static final Logger logger = Logger.getLogger(TimeSeriesController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String TAG = "TimeSeries"; public static final String STORE_RULE_DESC = "The business rule to use " + "when merging the incoming with existing data\n" @@ -171,7 +170,7 @@ public void create(@NotNull Context ctx) { ctx.status(HttpServletResponse.SC_OK); } catch (DataAccessException | IOException ex) { CdaError re = new CdaError("Internal Error"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re.toString()); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } @@ -482,7 +481,7 @@ public void getAll(@NotNull Context ctx) { requestResultSize.update(results.length()); } catch (IllegalArgumentException ex) { CdaError re = new CdaError("Invalid arguments supplied"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re.toString()); ctx.status(HttpServletResponse.SC_BAD_REQUEST); ctx.json(re); } @@ -506,7 +505,7 @@ private void addLinkHeader(@NotNull Context ctx, TimeSeries ts, ContentType cont ctx.header("Link", linkValue.toString()); } catch (URISyntaxException ex) { - logger.log(Level.WARNING, null, ex); + logger.atWarning().withCause(ex).log("Failed to build Link header"); } } @@ -566,7 +565,7 @@ public void update(@NotNull Context ctx, @NotNull String id) { ctx.status(HttpServletResponse.SC_OK); } catch (DataAccessException | IOException ex) { CdaError re = new CdaError("Internal Error"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re.toString()); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesFilteredController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesFilteredController.java index 04b770d8d..48d339ca8 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesFilteredController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesFilteredController.java @@ -33,8 +33,7 @@ import java.nio.charset.StandardCharsets; import java.time.ZoneId; import java.time.ZonedDateTime; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; @@ -44,7 +43,7 @@ import org.jooq.DSLContext; public class TimeSeriesFilteredController implements Handler { - private static final Logger logger = Logger.getLogger(TimeSeriesFilteredController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String TAG = "TimeSeries"; private static final int DEFAULT_PAGE_SIZE = 500; @@ -241,7 +240,7 @@ public void handle(@NotNull Context ctx) { requestResultSize.update(results.length()); } catch (IllegalArgumentException ex) { CdaError re = new CdaError("Invalid arguments supplied"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_BAD_REQUEST); ctx.json(re); } @@ -266,7 +265,7 @@ private void addLinkHeader(@NotNull Context ctx, FilteredTimeSeries fts, Content ctx.header("Link", linkValue.toString()); } catch (URISyntaxException ex) { - logger.log(Level.WARNING, null, ex); + logger.atWarning().withCause(ex).log("Error building Link header"); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesGroupController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesGroupController.java index 3630ca94a..34ece4b81 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesGroupController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesGroupController.java @@ -68,14 +68,14 @@ import io.javalin.plugin.openapi.annotations.OpenApiRequestBody; import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.util.List; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.checkerframework.checker.nullness.qual.NonNull; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; public class TimeSeriesGroupController implements CrudHandler { - public static final Logger logger = Logger.getLogger(TimeSeriesGroupController.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String TAG = "Timeseries Groups"; private final MetricRegistry metrics; @@ -139,7 +139,7 @@ Boolean.class, true, metrics, name(TimeSeriesGroupController.class.getName(), includeAssigned, tsCategoryLike, tsGroupLike); if (grps.isEmpty()) { CdaError re = new CdaError("No data found for The provided office"); - logger.info(() -> re + " for request " + ctx.fullUrl()); + logger.atInfo().log("%s for request %s", re, ctx.fullUrl()); ctx.status(HttpCode.NOT_FOUND).json(re); } else { String formatHeader = ctx.header(Header.ACCEPT); @@ -223,7 +223,7 @@ public void getOne(@NotNull Context ctx, @NotNull String groupId) { ctx.status(HttpServletResponse.SC_OK); } else { CdaError re = new CdaError("Unable to find group based on parameters given"); - logger.info(() -> re + System.lineSeparator() + "for request " + ctx.fullUrl()); + logger.atInfo().log("%s%sfor request %s", re, System.lineSeparator(), ctx.fullUrl()); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesIdentifierDescriptorController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesIdentifierDescriptorController.java index 7cc942063..1ee916c83 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesIdentifierDescriptorController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesIdentifierDescriptorController.java @@ -50,8 +50,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import org.jetbrains.annotations.NotNull; @@ -59,7 +58,7 @@ import org.jooq.exception.DataAccessException; public class TimeSeriesIdentifierDescriptorController implements CrudHandler { - public static final Logger logger = Logger.getLogger(TimeSeriesIdentifierDescriptorController.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String TAG = "TimeSeries Identifier"; private static final int DEFAULT_PAGE_SIZE = 500; @@ -195,7 +194,7 @@ public void getOne(@NotNull Context ctx, @NotNull String timeseriesId) { } else { CdaError re = new CdaError("Unable to find identifier based on parameters " + "given"); - logger.info(() -> re + System.lineSeparator() + "for request " + ctx.fullUrl()); + logger.atInfo().log("%s%s for request %s", re, System.lineSeparator(), ctx.fullUrl()); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re); } } @@ -320,7 +319,7 @@ public void delete(@NotNull Context ctx, @NotNull String timeseriesId) { try (final Timer.Context ignored = markAndTime(DELETE)){ DSLContext dsl = getDslContext(ctx); - logger.log(Level.FINE, "Deleting timeseries:{0} from office:{1}", new Object[]{timeseriesId, office}); + logger.atFine().log("Deleting timeseries:%s from office:%s", timeseriesId, office); TimeSeriesIdentifierDescriptorDao dao = new TimeSeriesIdentifierDescriptorDao(dsl); dao.delete(office, timeseriesId, method); @@ -328,7 +327,7 @@ public void delete(@NotNull Context ctx, @NotNull String timeseriesId) { } catch (DataAccessException ex) { CdaError re = new CdaError("Internal Error"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re.toString()); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesRecentController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesRecentController.java index 1aa56839d..d5e4da755 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesRecentController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesRecentController.java @@ -65,8 +65,7 @@ import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.regex.MatchResult; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -77,7 +76,7 @@ import org.jooq.DSLContext; public class TimeSeriesRecentController implements Handler { - private static final Logger logger = Logger.getLogger(TimeSeriesRecentController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final MetricRegistry metrics; private final Histogram requestResultSize; @@ -163,7 +162,7 @@ public void handle(@NotNull Context ctx) { // has both = this is an error CdaError re = new CdaError("Invalid arguments supplied, group has both " + "Timeseries Group info and Timeseries IDs."); - logger.log(Level.SEVERE, "{0} for request {1}", new Object[]{ re, ctx.fullUrl()}); + logger.atSevere().log("%s for request %s", re, ctx.fullUrl()); ctx.status(HttpServletResponse.SC_BAD_REQUEST); ctx.json(re); return; @@ -171,7 +170,7 @@ public void handle(@NotNull Context ctx) { // doesn't have either? Just return empty results? CdaError re = new CdaError("Invalid arguments supplied, group has neither " + "Timeseries Group info nor Timeseries IDs"); - logger.log(Level.SEVERE, "{0} for request {1}", new Object[]{ re, ctx.fullUrl()}); + logger.atSevere().log("%s for request %s", re, ctx.fullUrl()); ctx.status(HttpServletResponse.SC_BAD_REQUEST); ctx.json(re); return; diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeZoneController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeZoneController.java index ea8c40bbb..72cbd7e70 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeZoneController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeZoneController.java @@ -29,13 +29,12 @@ import io.javalin.plugin.openapi.annotations.OpenApiParam; import io.javalin.plugin.openapi.annotations.OpenApiResponse; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jooq.DSLContext; public class TimeZoneController implements CrudHandler { - private static final Logger logger = Logger.getLogger(TimeZoneController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final MetricRegistry metrics; @@ -127,7 +126,7 @@ public void getAll(Context ctx) { ctx.status(HttpServletResponse.SC_OK); ctx.result(results); } catch (Exception ex) { - logger.log(Level.SEVERE, null, ex); + logger.atSevere().withCause(ex).log("Failed to process request"); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ctx.result("Failed to process request"); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/UnitsController.java b/cwms-data-api/src/main/java/cwms/cda/api/UnitsController.java index 95051ed37..d2a74848d 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/UnitsController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/UnitsController.java @@ -28,13 +28,12 @@ import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jooq.DSLContext; public class UnitsController implements CrudHandler { - private static final Logger logger = Logger.getLogger(UnitsController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final MetricRegistry metrics; private final Histogram requestResultSize; @@ -123,7 +122,7 @@ public void getAll(Context ctx) { addDeprecatedContentTypeWarning(ctx, contentType); requestResultSize.update(results.length()); } catch (Exception ex) { - logger.log(Level.SEVERE, null, ex); + logger.atSevere().withCause(ex).log("Failed to process request"); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ctx.result("Failed to process request"); } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingController.java b/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingController.java index ab718255e..7797c0e12 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingController.java @@ -85,8 +85,7 @@ import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.io.IOException; import java.time.Instant; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.TransformerException; import mil.army.usace.hec.cwms.rating.io.xml.RatingXmlFactory; @@ -97,7 +96,7 @@ public class RatingController implements CrudHandler { - private static final Logger logger = Logger.getLogger(RatingController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); static final String TAG = "Ratings"; private final MetricRegistry metrics; @@ -155,11 +154,11 @@ public void create(@NotNull Context ctx) { ctx.status(HttpServletResponse.SC_CREATED).json(re); } catch (IOException ex) { CdaError re = new CdaError("Failed to process request to update RatingSet"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } catch (RatingException ex) { CdaError re = new CdaError("Failed to process request to update RatingSet: " + ex.getLocalizedMessage()); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } @@ -433,21 +432,20 @@ private String getRatingSetString(Context ctx, RatingSet.DatabaseLoadMethod meth } catch (RatingException e) { CdaError re = new CdaError("Failed to process request to retrieve RatingSet"); - logger.log(Level.SEVERE, re.toString(), e); + logger.atSevere().withCause(e).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ctx.json(re); } catch (IOException e) { CdaError re = new CdaError("Failed to process request to retrieve RatingSet"); - logger.log(Level.SEVERE, re.toString(), e); + logger.atSevere().withCause(e).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } else { CdaError re = new CdaError("Currently supporting only: " + Formats.JSONV2 + " and " + Formats.XMLV2); - logger.log(Level.WARNING, "Provided accept header not recognized:" - + acceptHeader, re); + logger.atWarning().log("Provided accept header not recognized: %s; %s", acceptHeader, re); ctx.status(HttpServletResponse.SC_NOT_IMPLEMENTED); ctx.json(CdaError.notImplemented()); } @@ -505,11 +503,11 @@ public void update(@NotNull Context ctx, @NotNull String ratingId) { ctx.status(HttpServletResponse.SC_OK).json(re); } catch (IOException ex) { CdaError re = new CdaError("Failed to process request to update RatingSet"); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } catch (RatingException ex) { CdaError re = new CdaError("Failed to process request to update RatingSet: " + ex.getLocalizedMessage()); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingMetadataController.java b/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingMetadataController.java index 1e96a4563..eba0d857a 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingMetadataController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingMetadataController.java @@ -58,14 +58,13 @@ import io.javalin.plugin.openapi.annotations.OpenApiParam; import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.time.ZonedDateTime; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; public class RatingMetadataController implements CrudHandler { - private static final Logger logger = Logger.getLogger(RatingMetadataController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final MetricRegistry metrics; @@ -171,7 +170,7 @@ public void getAll(Context ctx) { } catch (Exception ex) { CdaError re = new CdaError("Failed to process request: " + ex.getLocalizedMessage()); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingSpecController.java b/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingSpecController.java index 18efbb347..4b5477a6f 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingSpecController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingSpecController.java @@ -50,8 +50,7 @@ import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.io.IOException; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.TransformerException; import org.jetbrains.annotations.NotNull; @@ -59,7 +58,7 @@ public class RatingSpecController implements CrudHandler { - private static final Logger logger = Logger.getLogger(RatingSpecController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String TAG = "Ratings"; private final MetricRegistry metrics; @@ -139,7 +138,7 @@ public void getAll(Context ctx) { } catch (Exception ex) { CdaError re = new CdaError("Failed to process request: " + ex.getLocalizedMessage()); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } @@ -189,7 +188,7 @@ public void getOne(Context ctx, String ratingId) { } else { CdaError re = new CdaError("Unable to find Rating Spec based on parameters " + "given"); - logger.info(() -> re + System.lineSeparator() + "for request " + ctx.fullUrl()); + logger.atInfo().log("%s%sfor request %s", re, System.lineSeparator(), ctx.fullUrl()); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingTemplateController.java b/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingTemplateController.java index c86c7199d..d0cf75b7e 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingTemplateController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/rating/RatingTemplateController.java @@ -51,8 +51,7 @@ import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.io.IOException; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.TransformerException; import org.jetbrains.annotations.NotNull; @@ -60,7 +59,7 @@ public class RatingTemplateController implements CrudHandler { - private static final Logger logger = Logger.getLogger(RatingTemplateController.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String TAG = "Ratings"; private final MetricRegistry metrics; @@ -138,7 +137,7 @@ public void getAll(Context ctx) { } catch (Exception ex) { CdaError re = new CdaError("Failed to process request: " + ex.getLocalizedMessage()); - logger.log(Level.SEVERE, re.toString(), ex); + logger.atSevere().withCause(ex).log("%s", re); ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).json(re); } @@ -194,7 +193,7 @@ public void getOne(Context ctx, String templateId) { } else { CdaError re = new CdaError("Unable to find Rating Template based on " + "parameters given"); - logger.info(() -> re + System.lineSeparator() + "for request " + ctx.fullUrl()); + logger.atInfo().log("%s%sfor request %s", re, System.lineSeparator(), ctx.fullUrl()); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/AccountingCatalogController.java b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/AccountingCatalogController.java index 53a7b69d1..1e10310c5 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/watersupply/AccountingCatalogController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/watersupply/AccountingCatalogController.java @@ -67,15 +67,14 @@ import io.javalin.plugin.openapi.annotations.OpenApiResponse; import java.time.Instant; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; public class AccountingCatalogController implements Handler { - private static final Logger LOGGER = Logger.getLogger(AccountingCatalogController.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private static final String TAG = "Pump Accounting"; private static final String ROW_LIMIT = "row-limit"; private static final String ASCENDING = "ascending"; @@ -175,7 +174,7 @@ public void handle(Context ctx) { if (waterUser.getEntityName() == null) { CdaError error = new CdaError("Unable to retrieve accounting - no water user found for the" + " provided parameters."); - LOGGER.log(Level.SEVERE, "Error retrieving water pump accounting - no water user found."); + LOGGER.atSevere().log("Error retrieving water pump accounting - no water user found."); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); return; } @@ -191,7 +190,7 @@ public void handle(Context ctx) { if (!contractExists) { CdaError error = new CdaError("Unable to retrieve accounting - no matching contract found for the" + " provided parameters."); - LOGGER.log(Level.SEVERE, "Error retrieving water pump accounting - no contract found."); + LOGGER.atSevere().log("Error retrieving water pump accounting - no contract found."); ctx.status(HttpServletResponse.SC_NOT_FOUND).json(error); return; } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/CdaVersionDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/CdaVersionDao.java index 074b27c7a..e4c900a02 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/CdaVersionDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/CdaVersionDao.java @@ -30,13 +30,12 @@ import cwms.cda.data.dto.CdaVersion; import java.util.HashMap; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.jooq.DSLContext; import org.jooq.exception.DataAccessException; public final class CdaVersionDao extends JooqDao { - private static final Logger logger = Logger.getLogger(CdaVersionDao.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public CdaVersionDao(DSLContext dsl) { super(dsl); @@ -69,7 +68,7 @@ private String hasTsDataEntryDateSupport() { tsDao.validateEntryDateSupport(true); supported = true; } catch (DataAccessException e) { - logger.log(Level.FINEST, e.getMessage(), e); + logger.atFinest().withCause(e).log("%s", e.getMessage()); } return String.valueOf(supported); } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/ClobDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/ClobDao.java index 9ee4fbc00..c27b35348 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/ClobDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/ClobDao.java @@ -29,6 +29,7 @@ import java.util.List; import java.util.Optional; +import static com.google.common.flogger.LazyArgs.lazy; import static org.jooq.impl.DSL.*; public class ClobDao extends JooqDao { @@ -123,7 +124,7 @@ public Clobs getClobs(String cursor, int pageSize, String officeLike, Clobs.Builder builder = new Clobs.Builder(cursor, pageSize, total); - logger.atFine().log(query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(()->query.getSQL(ParamType.INLINED))); query.fetch().forEach(row -> { usace.cwms.db.jooq.codegen.tables.records.AV_CLOB clob = row.into(vClob); diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/LocationLevelsDaoImpl.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/LocationLevelsDaoImpl.java index fbb3150a9..a43fa47c2 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/LocationLevelsDaoImpl.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/LocationLevelsDaoImpl.java @@ -24,6 +24,8 @@ package cwms.cda.data.dao; +import static com.google.common.flogger.LazyArgs.lazy; + import static java.util.stream.Collectors.toList; import static mil.army.usace.hec.metadata.IntervalFactory.equalsName; import static mil.army.usace.hec.metadata.IntervalFactory.isRegular; @@ -70,8 +72,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.regex.Pattern; import cwms.cda.data.dto.locationlevel.TimeSeriesLocationLevel; import cwms.cda.data.dto.locationlevel.VirtualLocationLevel; @@ -105,7 +106,7 @@ import usace.cwms.db.jooq.codegen.udt.records.ZTSV_TYPE; public class LocationLevelsDaoImpl extends JooqDao implements LocationLevelsDao { - private static final Logger logger = Logger.getLogger(LocationLevelsDaoImpl.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String ATTRIBUTE_ID_PARSING_REGEXP = "(.*)\\.(.*)\\.(.*)"; public static final Pattern attributeIdParsingPattern = @@ -160,7 +161,7 @@ public LocationLevels getLocationLevels(String cursor, int pageSize, total = Integer.valueOf(parts[1]); totalSet = true; } catch (NumberFormatException e) { - logger.log(Level.INFO, "Could not parse {0}", parts[1]); + logger.atInfo().log("Could not parse %s", parts[1]); } } pageSize = Integer.parseInt(parts[2]); @@ -266,7 +267,7 @@ public LocationLevels getLocationLevels(String cursor, int pageSize, final SelectLimitPercentAfterOffsetStep queryFinal = query; - logger.fine(() -> "getLocationLevels query: " + queryFinal.getSQL(ParamType.INLINED)); + logger.atFine().log("getLocationLevels query: %s", lazy(() -> queryFinal.getSQL(ParamType.INLINED))); if (includeAliases) { Result result = query.fetch(); @@ -534,10 +535,10 @@ public LocationLevel retrieveLocationLevel(String locationLevelName, String pUni units = CWMS_UTIL_PACKAGE.call_GET_DEFAULT_UNITS(configuration, parameter, units); } else if (units == null) { - logger.info("Getting default units for " + parameter); + logger.atInfo().log("Getting default units for %s", parameter); String defaultUnits = CWMS_UTIL_PACKAGE.call_GET_DEFAULT_UNITS( configuration, parameter, UnitSystem.SI.getValue()); - logger.info("Default units are " + defaultUnits); + logger.atInfo().log("Default units are %s", defaultUnits); units = defaultUnits; } LOCATION_LEVEL_T level = CWMS_LEVEL_PACKAGE.call_RETRIEVE_LOCATION_LEVEL__2( diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/LocationsDaoImpl.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/LocationsDaoImpl.java index 759f80193..f039e9ed5 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/LocationsDaoImpl.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/LocationsDaoImpl.java @@ -24,6 +24,8 @@ package cwms.cda.data.dao; +import static com.google.common.flogger.LazyArgs.lazy; + import static cwms.cda.api.Controllers.BOUNDING_OFFICE_LIKE; import static cwms.cda.api.Controllers.LIKE; import static cwms.cda.api.Controllers.LOCATION_CATEGORY_LIKE; @@ -67,8 +69,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.stream.Stream; import org.geojson.Feature; import org.geojson.FeatureCollection; @@ -94,7 +95,7 @@ public class LocationsDaoImpl extends JooqDao implements LocationsDao { - private static final Logger logger = Logger.getLogger(LocationsDaoImpl.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final long DELETED_TS_MARKER = 0L; @@ -505,7 +506,7 @@ private Catalog getLocationCatalog(Catalog.CatalogPage catPage, int pageSize, Ca SelectConditionStep> count = dsl.select(count(asterisk())) .from(table) .where(condition); - logger.log(Level.FINER, () -> count.getSQL(ParamType.INLINED)); + logger.atFiner().log("%s", lazy(() -> count.getSQL(ParamType.INLINED))); total = count.fetchOne().value1(); } else { cursorLocation = catPage.getCursorId(); @@ -554,7 +555,7 @@ private Catalog getLocationCatalog(Catalog.CatalogPage catPage, int pageSize, Ca .from(limiter) .leftOuterJoin(table).on(fieldMapping.getLocationCode().eq(limitCode)) .orderBy(orderFields); - logger.log(Level.FINER, () -> query.getSQL(ParamType.INLINED)); + logger.atFiner().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); try (Stream recordStream = (Stream) query .fetchSize(DEFAULT_FETCH_SIZE) @@ -654,9 +655,9 @@ private static Condition addCursorConditions(Condition condition, String cursorO static String warnIfMismatch(String paramName, String pageParam, String queryParam) { if (queryParam != null && (!queryParam.equals(pageParam))) { - logger.log(Level.WARNING, "The {0} query parameter:{1} and page cursor parameter:{2} do not match." - + " The value provided in the page parameter will be used.", - new Object[]{paramName, queryParam, pageParam}); + logger.atWarning().log( + "The %s query parameter:%s and page cursor parameter:%s do not match. The value provided in the page parameter will be used.", + paramName, queryParam, pageParam); } return pageParam; } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/PoolDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/PoolDao.java index 010530886..5e189f233 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/PoolDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/PoolDao.java @@ -8,8 +8,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import org.jooq.Condition; @@ -23,7 +22,7 @@ import usace.cwms.db.jooq.codegen.tables.AV_POOL; public class PoolDao extends JooqDao { - private static Logger logger = Logger.getLogger(PoolDao.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public PoolDao(DSLContext dsl) { super(dsl); @@ -180,7 +179,7 @@ public Pools retrievePools(String cursor, int pageSize, if (cursor != null && !cursor.isEmpty()) { String[] parts = Pools.decodeCursor(cursor); - logger.fine( () -> "decoded cursor: " + Arrays.toString(parts)); + logger.atFine().log("decoded cursor: %s", Arrays.toString(parts)); if (parts.length > 2) { offset = Integer.parseInt(parts[0]); @@ -188,7 +187,7 @@ public Pools retrievePools(String cursor, int pageSize, try { total = Integer.valueOf(parts[1]); } catch(NumberFormatException e){ - logger.log(Level.INFO, "Could not parse " + parts[1]); + logger.atInfo().log("Could not parse %s", parts[1]); } } pageSize = Integer.parseInt(parts[2]); // Why are we taking pageSize as an arg and also pulling it from cursor? diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/RatingMetadataDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/RatingMetadataDao.java index 75c72ad70..25c9cb435 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/RatingMetadataDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/RatingMetadataDao.java @@ -62,8 +62,7 @@ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -71,7 +70,7 @@ import static org.jooq.impl.DSL.field; public class RatingMetadataDao extends JooqDao { - private static final Logger logger = Logger.getLogger(RatingMetadataDao.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String EMPTY = "\n" + " { public static final Calendar GMT_CALENDAR = getGmtCalendar(); - private static final Logger logger = Logger.getLogger(RatingSpecDao.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String OFFICE_ID = "OFFICE_ID"; public static final String SPECIFICATION_ID = "SPECIFICATION_ID"; public static final String LOCATION_ID = "LOCATION_ID"; @@ -142,7 +143,7 @@ public Collection retrieveRatingSpecs(String office, String specIdMa .where(condition) .fetchSize(DEFAULT_FETCH_SIZE); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); Map> map = new LinkedHashMap<>(); try (Stream stream = query.fetchStream()) { @@ -182,7 +183,7 @@ public RatingSpecs retrieveRatingSpecs(String cursor, int pageSize, String offic try { total = Integer.valueOf(parts[1]); } catch (NumberFormatException e) { - logger.log(Level.INFO, "Could not parse " + parts[1]); + logger.atInfo().log("Could not parse %s", parts[1]); } } pageSize = Integer.parseInt(parts[2]); @@ -236,7 +237,7 @@ public Set getRatingSpecs(String office, String specIdMask, int firs .limit(pageSize) .offset(firstRow); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); Map> map = new LinkedHashMap<>(); try (Stream stream = query.fetchStream()) { @@ -296,7 +297,7 @@ public Optional retrieveRatingSpec(String office, String specId) { .orderBy(specView.OFFICE_ID, specView.RATING_ID, ratView.EFFECTIVE_DATE) .fetchSize(DEFAULT_FETCH_SIZE); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); Map> map = new LinkedHashMap<>(); try (Stream stream = query.fetchStream()) { diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/RatingTemplateDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/RatingTemplateDao.java index ee0f1968b..cc8bec9c1 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/RatingTemplateDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/RatingTemplateDao.java @@ -24,6 +24,8 @@ package cwms.cda.data.dao; +import static com.google.common.flogger.LazyArgs.lazy; + import cwms.cda.data.dto.CwmsDTOPaginated; import cwms.cda.data.dto.rating.ParameterSpec; import cwms.cda.data.dto.rating.RatingTemplate; @@ -36,8 +38,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jetbrains.annotations.NotNull; @@ -54,7 +55,7 @@ import usace.cwms.db.jooq.codegen.tables.AV_RATING_TEMPLATE; public class RatingTemplateDao extends JooqDao { - private static final Logger logger = Logger.getLogger(RatingTemplateDao.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public RatingTemplateDao(DSLContext dsl) { super(dsl); @@ -89,7 +90,7 @@ public Set retrieveRatingTemplates(String office, String templat .where(condition) .fetchSize(DEFAULT_FETCH_SIZE); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); return buildRatingTemplateSet(query); } @@ -132,7 +133,7 @@ public Optional retrieveRatingTemplate(String office, String tem .where(condition) .fetchSize(DEFAULT_FETCH_SIZE); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); Map> map = new LinkedHashMap<>(); @@ -164,8 +165,8 @@ static void addTemplate(Record rec, Map> map) { ratingSpecs.add(specID); } } catch(RuntimeException ex) { - logger.log(Level.WARNING, ex, () -> - "Error transforming rating template table record into RatingTemplate DTO:\n" + rec); + logger.atWarning().withCause(ex).log( + "Error transforming rating template table record into RatingTemplate DTO:%n%s", rec); } } @@ -229,7 +230,7 @@ public RatingTemplates retrieveRatingTemplates(String cursor, int pageSize, Stri try { total = Integer.valueOf(parts[1]); } catch (NumberFormatException e) { - logger.log(Level.INFO, "Could not parse " + parts[1]); + logger.atInfo().log("Could not parse %s", parts[1]); } } pageSize = Integer.parseInt(parts[2]); @@ -273,7 +274,7 @@ private Set getRatingTemplates(String office, String templateIdM .limit(pageSize) .offset(firstRow); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); return buildRatingTemplateSet(query); } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/TimeSeriesDaoImpl.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/TimeSeriesDaoImpl.java index 097c1a83a..f0b72b833 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/TimeSeriesDaoImpl.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/TimeSeriesDaoImpl.java @@ -1,6 +1,7 @@ package cwms.cda.data.dao; +import static com.google.common.flogger.LazyArgs.lazy; import static org.jooq.impl.DSL.asterisk; import static org.jooq.impl.DSL.countDistinct; import static org.jooq.impl.DSL.field; @@ -62,8 +63,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -106,7 +106,7 @@ import usace.cwms.db.jooq.codegen.udt.records.ZTSV_TYPE; public class TimeSeriesDaoImpl extends JooqDao implements TimeSeriesDao { - private static final Logger logger = Logger.getLogger(TimeSeriesDaoImpl.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * String constants for accessing alias tables and columns in TimeSeriesRecent querying @@ -261,14 +261,14 @@ protected TimeSeries getRequestedTimeSeries(String page, int pageSize, @NotNull if (page != null && !page.isEmpty()) { final String[] parts = CwmsDTOPaginated.decodeCursor(page); - logger.fine("Decoded cursor"); - logger.finest(() -> { + logger.atFine().log("Decoded cursor"); + logger.atFinest().log("%s", lazy(() -> { StringBuilder sb = new StringBuilder(); for (String p : parts) { sb.append(p).append("\n"); } return sb.toString(); - }); + })); if (parts.length > 1) { cursor = parts[0]; @@ -433,7 +433,7 @@ protected TimeSeries getRequestedTimeSeries(String page, int pageSize, @NotNull .and(AV_CWMS_TS_ID2.ALIASED_ITEM.isNull()) ); - logger.fine(() -> metadataQuery.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> metadataQuery.getSQL(ParamType.INLINED))); TimeSeries timeseries = metadataQuery.fetchOne(tsMetadata -> { @@ -513,7 +513,7 @@ protected TimeSeries getRequestedTimeSeries(String page, int pageSize, @NotNull } if (requestParameters.isIncludeEntryDate()) { - logger.fine(() -> query2.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query2.getSQL(ParamType.INLINED))); try (Cursor> recCursor = query2.fetchLazy()) { for (Record tsRecord: recCursor) { timeseries.addValue( @@ -524,7 +524,7 @@ protected TimeSeries getRequestedTimeSeries(String page, int pageSize, @NotNull } } } else { - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); try (Cursor> recCursor = query.fetchLazy()) { for (Record tsRecord: recCursor) { timeseries.addValue( @@ -615,7 +615,7 @@ public static VerticalDatumInfo parseVerticalDatumInfo(String body) { try { retVal = new XMLv1().parseContent(body, VerticalDatumInfo.class); } catch (FormattingException e) { - logger.log(Level.WARNING, e, () -> "Failed to parse:" + body); + logger.atWarning().withCause(e).log("Failed to parse:%s", body); } } return retVal; @@ -635,10 +635,10 @@ public Catalog getTimeSeriesCatalog(String page, int pageSize, CatalogRequestPar SelectJoinStep> totalQuery = dsl.with(limiter) .select(countDistinct(limiter.field(cwmsTsIdFields.getTsCode()))) .from(limiter); - logger.fine(() -> totalQuery.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> totalQuery.getSQL(ParamType.INLINED))); total = totalQuery.fetchOne(0, int.class); } else { - logger.fine("getting non-default page"); + logger.atFine().log("getting non-default page"); // Information provided by the page value overrides anything provided catPage = new Catalog.CatalogPage(page); total = catPage.getTotal(); @@ -683,7 +683,7 @@ public Catalog getTimeSeriesCatalog(String page, int pageSize, CatalogRequestPar final SelectSeekStep2 overallQuery = tmpQuery .orderBy(cwmsTsIdFields.getDbOfficeId(), cwmsTsIdFields.getCwmsTsId()); - logger.fine(() -> overallQuery.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> overallQuery.getSQL(ParamType.INLINED))); Result result = overallQuery.fetch(); Map tsIdExtentMap = new LinkedHashMap<>(); @@ -1223,7 +1223,7 @@ public List findMostRecentsInRange(String office, List tsId .where(field(name(maxValues.getName(), DATE_TIME), java.sql.Date.class) .eq(field(name(maxValues.getName(), MAX_DATE_TIME), java.sql.Date.class))); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); // fetch and build records retval = query.fetch(r -> { @@ -1375,7 +1375,7 @@ public List findRecentsInRange(String office, String categoryId, St .where(field(name(maxValues.getName(), DATE_TIME), java.sql.Date.class) .eq(field(name(maxValues.getName(), MAX_DATE_TIME), java.sql.Date.class))); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); // fetch and build records retval = query.fetch(r -> { @@ -1493,7 +1493,7 @@ private void store(Connection connection, String officeId, String tsId, String u throw e; } // Ignore tsId not found exceptions. tsDao.store() will create tsId if it is not found - logger.log(Level.FINER, e, () -> "TS ID: " + tsId + " not found at office: " + officeId); + logger.atFiner().withCause(e).log("TS ID: %s not found at office: %s", tsId, officeId); } else { throw e; } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/TimeSeriesGroupDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/TimeSeriesGroupDao.java index 3157ec5f4..724d2883e 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/TimeSeriesGroupDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/TimeSeriesGroupDao.java @@ -24,6 +24,8 @@ package cwms.cda.data.dao; +import static com.google.common.flogger.LazyArgs.lazy; + import static java.util.stream.Collectors.toList; import cwms.cda.data.dto.AssignedTimeSeries; @@ -31,7 +33,7 @@ import cwms.cda.data.dto.TimeSeriesGroup; import java.math.BigDecimal; import java.util.List; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.jetbrains.annotations.NotNull; import org.jooq.*; import org.jooq.conf.ParamType; @@ -44,7 +46,7 @@ public class TimeSeriesGroupDao extends JooqDao { - private static final Logger logger = Logger.getLogger(TimeSeriesGroupDao.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String CWMS = "CWMS"; public TimeSeriesGroupDao(DSLContext dsl) { @@ -149,7 +151,7 @@ private List getTimeSeriesGroupsWhere(Condition whereCond, Stri catGrp.GRP_DB_OFFICE_ID, catGrp.TS_GROUP_ID); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); RecordMapper>, TimeSeriesGroup> mapperToTimeSeriesGroup = @@ -178,7 +180,7 @@ private List getTimeSeriesGroupsWithoutAssigned(Condition where .from(AV_TS_CAT_GRP.AV_TS_CAT_GRP) .where(whereCond); - logger.fine(() -> query.getSQL(ParamType.INLINED)); + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); return query.fetch((RecordMapper) this::buildTimeSeriesGroup); } diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java index c05ad19c7..c2e12d63f 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java @@ -1,5 +1,6 @@ package cwms.cda.data.dao; +import static com.google.common.flogger.LazyArgs.lazy; import static org.jooq.impl.DSL.*; import java.sql.CallableStatement; @@ -233,10 +234,8 @@ public Users getAll(String cursor, int pageSize, String office, boolean includeR // association and always fully included per use in the response. .orderBy(limitUserId, vUserGroups.DB_OFFICE_ID) ; - - - logger.atInfo().log(query.getSQL(ParamType.INLINED)); - + + logger.atFine().log("%s", lazy(() -> query.getSQL(ParamType.INLINED))); final Users.Builder builder = new Users.Builder(cursor, pageSizeTmp, total, limitOffice); diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/timeseriesprofile/TimeSeriesProfileInstanceDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/timeseriesprofile/TimeSeriesProfileInstanceDao.java index 8d01f30a2..da9789a79 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/timeseriesprofile/TimeSeriesProfileInstanceDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/timeseriesprofile/TimeSeriesProfileInstanceDao.java @@ -1,5 +1,6 @@ package cwms.cda.data.dao.timeseriesprofile; +import static com.google.common.flogger.LazyArgs.lazy; import static cwms.cda.data.dto.CwmsDTOPaginated.delimiter; import static cwms.cda.data.dto.CwmsDTOPaginated.encodeCursor; import static org.jooq.impl.DSL.asterisk; @@ -27,7 +28,7 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.jetbrains.annotations.NotNull; import org.jooq.Condition; import org.jooq.DSLContext; @@ -56,7 +57,7 @@ public class TimeSeriesProfileInstanceDao extends JooqDao { - private static final Logger LOGGER = Logger.getLogger(TimeSeriesProfileInstanceDao.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final AV_TS_PROFILE_INST_TSV2 VIEW_TSV2 = AV_TS_PROFILE_INST_TSV2.AV_TS_PROFILE_INST_TSV2; private static final AV_TS_PROFILE_INST VIEW = AV_TS_PROFILE_INST.AV_TS_PROFILE_INST; @@ -238,14 +239,15 @@ public TimeSeriesProfileInstance retrieveTimeSeriesProfileInstance(CwmsId locati if (page != null && !page.isEmpty()) { final String[] parts = CwmsDTOPaginated.decodeCursor(page); - LOGGER.fine("Decoded cursor"); - LOGGER.finest(() -> { + logger.atFine().log("Decoded cursor"); + logger.atFinest().log("%s", lazy(()-> + { StringBuilder sb = new StringBuilder(); for (String part : parts) { sb.append(part).append("\n"); } return sb.toString(); - }); + })); if (parts.length > 1) { tsCursor = Timestamp.from(Instant.ofEpochMilli(Long.parseLong(parts[0]))); @@ -463,7 +465,7 @@ public TimeSeriesProfileInstance retrieveTimeSeriesProfileInstance(CwmsId locati } } Result lastRecord = result; - LOGGER.fine(lastRecord::toString); + logger.atFine().log(lastRecord.toString()); } // Throw 404 if no results diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyUtils.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyUtils.java index 43c95dd8c..9803ae99e 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyUtils.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/watersupply/WaterSupplyUtils.java @@ -46,8 +46,7 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.jetbrains.annotations.NotNull; import org.jooq.impl.DSL; import usace.cwms.db.jooq.codegen.udt.records.LOCATION_REF_T; @@ -64,7 +63,7 @@ final class WaterSupplyUtils { - private static final Logger LOGGER = Logger.getLogger(WaterSupplyUtils.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private WaterSupplyUtils() { throw new IllegalStateException("Utility class"); @@ -201,7 +200,7 @@ static WAT_USR_CONTRACT_ACCT_TAB_T toWaterUserContractAcctTs(WaterSupplyAccounti watUsrContractAcctObjT.setPUMP_LOCATION_REF(pumpBelow); break; default: - LOGGER.log(Level.WARNING, "Invalid pump type"); + LOGGER.atWarning().log("Invalid pump type"); throw new IllegalArgumentException( String.format("Invalid pump type for mapping to DB object: %s", transfer.getPumpType())); } @@ -232,7 +231,7 @@ static LOC_REF_TIME_WINDOW_TAB_T toTimeWindowTabT(WaterSupplyAccounting accounti timeWindow.setLOCATION_REF(pumpBelow); break; default: - LOGGER.log(Level.WARNING, "Invalid pump type"); + LOGGER.atWarning().log("Invalid pump type"); break; } timeWindow.setSTART_DATE(Timestamp.from(entry.getKey())); diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dto/CwmsDTOPaginated.java b/cwms-data-api/src/main/java/cwms/cda/data/dto/CwmsDTOPaginated.java index f51723563..d27229872 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dto/CwmsDTOPaginated.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dto/CwmsDTOPaginated.java @@ -5,7 +5,7 @@ import java.util.Base64; import java.util.Base64.Decoder; import java.util.Base64.Encoder; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -29,7 +29,7 @@ @JsonNaming(PropertyNamingStrategies.KebabCaseStrategy.class) @JsonPropertyOrder(alphabetic = true) public abstract class CwmsDTOPaginated extends CwmsDTOBase { - private static final Logger logger = Logger.getLogger(CwmsDTOPaginated.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Schema( description = "The cursor to the current page of data", @@ -154,7 +154,7 @@ public static class CursorCheck implements Function1 { private static Pattern base64 = Pattern.compile("^[-A-Za-z0-9+/]*={0,3}$"); @Override public Boolean invoke(String cursor) { - logger.finest("checking"); + logger.atFinest().log("checking"); return base64.matcher(cursor).matches() ? Boolean.TRUE : Boolean.FALSE; } diff --git a/cwms-data-api/src/main/java/cwms/cda/datasource/DelegatingConnectionPreparer.java b/cwms-data-api/src/main/java/cwms/cda/datasource/DelegatingConnectionPreparer.java index 56e194bf2..4aae41c6a 100644 --- a/cwms-data-api/src/main/java/cwms/cda/datasource/DelegatingConnectionPreparer.java +++ b/cwms-data-api/src/main/java/cwms/cda/datasource/DelegatingConnectionPreparer.java @@ -5,11 +5,11 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; public class DelegatingConnectionPreparer implements ConnectionPreparer { - public static final Logger logger = Logger.getLogger(DelegatingConnectionPreparer.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final List delegates = new ArrayList<>(); public DelegatingConnectionPreparer(List preparers) { @@ -20,7 +20,7 @@ public DelegatingConnectionPreparer(List preparers) { public DelegatingConnectionPreparer(ConnectionPreparer... preparers) { for(ConnectionPreparer p : preparers) { - Objects.requireNonNull(p,"A null prepared should not be passed to this function"); + Objects.requireNonNull(p,"A null ConnectionPreparer should not be passed to this function"); delegates.add(p); } } @@ -38,7 +38,7 @@ public DelegatingConnectionPreparer(ConnectionPreparer prep1, ConnectionPreparer public Connection prepare(Connection connection) throws SQLException { Connection retval = connection; for (ConnectionPreparer delegate : delegates) { - logger.fine(delegate.getClass().getName()); + logger.atFine().log(delegate.getClass().getName()); retval = delegate.prepare(retval); } diff --git a/cwms-data-api/src/main/java/cwms/cda/formatters/Formats.java b/cwms-data-api/src/main/java/cwms/cda/formatters/Formats.java index c7342aaa7..e71eb1262 100644 --- a/cwms-data-api/src/main/java/cwms/cda/formatters/Formats.java +++ b/cwms-data-api/src/main/java/cwms/cda/formatters/Formats.java @@ -36,8 +36,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jetbrains.annotations.NotNull; @@ -45,7 +44,7 @@ public class Formats { - public static final Logger logger = Logger.getLogger(Formats.class.getName()); + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String PLAIN = "text/plain"; // Only used as a constant, not for any // data mapping public static final String JSON = "application/json"; @@ -114,7 +113,7 @@ public static String getLegacyTypeFromContentType(ContentType contentType) { private String getFormatted(ContentType type, CwmsDTOBase toFormat) throws FormattingException { Objects.requireNonNull(toFormat, "Object to be formatted should not be null"); - formatters.keySet().forEach(k -> logger.fine(k::toString)); + formatters.keySet().forEach(k -> logger.atFine().log("%s", k.toString())); OutputFormatter outputFormatter = getOutputFormatterInternal(type, toFormat.getClass()); if (outputFormatter != null) { @@ -130,7 +129,7 @@ private String getFormatted(ContentType type, CwmsDTOBase toFormat) throws Forma private String getFormatted(ContentType type, List dtos, Class rootType) throws FormattingException { for (ContentType key : formatters.keySet()) { - logger.finest(() -> key.toString()); + logger.atFinest().log("%s", key.toString()); } OutputFormatter outputFormatter = getOutputFormatterInternal(type, rootType); @@ -209,7 +208,7 @@ private OutputFormatter getOutputFormatterInternal(ContentType type, formatters.computeIfAbsent(type, k -> new HashMap<>()) .put(klass,outputFormatter); } catch (Exception ex) { - logger.log(Level.SEVERE, "Unable to create formatter.", ex); + logger.atSevere().withCause(ex).log("Unable to create formatter."); return null; } } @@ -353,12 +352,12 @@ public static ContentType parseQueryParam(String queryParam, Class contentTypes = new TreeSet<>(); String[] all = header.split(","); - logger.log(Level.FINEST, "Finding handlers {0}", all.length); + logger.atFinest().log("Finding handlers %d", all.length); for (String ct : all) { ContentType aliasType = aliasMap.getContentType(ct); //Found type defined in annotations, add to the priority list. if (aliasType != null) { - logger.finest(() -> ct + " converted to " + aliasType); + logger.atFinest().log("%s converted to %s", ct, aliasType); contentTypes.add(aliasType); } else { //If the DTO parameter is null, alias map is empty. Compare against well-known types @@ -370,10 +369,10 @@ public static ContentType parseQueryParam(String queryParam, Class "have " + contentTypes.size()); + logger.atFinest().log("have %d", contentTypes.size()); //Look through known content types to match using priority sorted TreeSet for (ContentType ct : contentTypes) { - logger.finest(() -> "checking " + ct.toString()); + logger.atFinest().log("checking %s", ct.toString()); if (contentTypeList.contains(ct)) { return ct; } diff --git a/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv1.java b/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv1.java index 9c3287156..20a5d6fbb 100644 --- a/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv1.java +++ b/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv1.java @@ -22,11 +22,10 @@ import java.time.ZoneId; import java.util.Collections; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; public class XMLv1 implements OutputFormatter { - private static final Logger logger = Logger.getLogger(XMLv1.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public XMLv1() { @@ -50,7 +49,7 @@ public String format(CwmsDTOBase dto) { "Error rendering '" + dto + "' to XML" : "Null element passed to formatter"; - logger.log(Level.WARNING, msg, ex); + logger.atWarning().withCause(ex).log(msg); throw new InternalServerErrorResponse("Invalid Parameters"); } } @@ -65,7 +64,7 @@ public String format(List dtoList) { } return xmlMapper.writeValueAsString(dtoList); } catch (Exception err) { - logger.log(Level.WARNING, "Error doing XML format of office list", err); + logger.atWarning().withCause(err).log("Error doing XML format of office list"); throw new InternalServerErrorResponse("Invalid Parameters"); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv2.java b/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv2.java index ccc9510f7..a28dd01fa 100644 --- a/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv2.java +++ b/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv2.java @@ -21,11 +21,10 @@ import java.io.InputStream; import java.time.ZoneId; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; public class XMLv2 implements OutputFormatter { - private static final Logger logger = Logger.getLogger(XMLv2.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public XMLv2() { } @@ -44,7 +43,7 @@ public String format(CwmsDTOBase dto) { "Error rendering '" + dto + "' to XML" : "Null element passed to formatter"; - logger.log(Level.WARNING, msg, ex); + logger.atWarning().withCause(ex).log(msg); throw new InternalServerErrorResponse("Invalid Parameters"); } } @@ -58,7 +57,7 @@ public String format(List dtoList) { "Error rendering '" + dtoList + "' to XML" : "Null element passed to formatter"; - logger.log(Level.WARNING, msg, ex); + logger.atWarning().withCause(ex).log(msg); throw new InternalServerErrorResponse("Invalid Parameters"); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv2Office.java b/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv2Office.java index 5b5e393e3..4063485ca 100644 --- a/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv2Office.java +++ b/cwms-data-api/src/main/java/cwms/cda/formatters/xml/XMLv2Office.java @@ -19,8 +19,7 @@ import java.io.InputStream; import java.io.StringWriter; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; @@ -34,7 +33,7 @@ * overrides. */ public class XMLv2Office implements OutputFormatter { - private static final Logger logger = Logger.getLogger(XMLv2Office.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public XMLv2Office() { } @@ -53,7 +52,7 @@ public String format(CwmsDTOBase dto) { "Error rendering '" + dto + "' to XML" : "Null element passed to formatter"; - logger.log(Level.WARNING, msg, ex); + logger.atWarning().withCause(ex).log(msg); throw new InternalServerErrorResponse("Invalid Parameters"); } } @@ -91,7 +90,7 @@ public String format(List dtoList) { "Error rendering '" + dtoList + "' to XML" : "Null element passed to formatter"; - logger.log(Level.WARNING, msg, ex); + logger.atWarning().withCause(ex).log(msg); throw new InternalServerErrorResponse("Invalid Parameters"); } } diff --git a/cwms-data-api/src/main/java/cwms/cda/helpers/ResourceHelper.java b/cwms-data-api/src/main/java/cwms/cda/helpers/ResourceHelper.java index 3ef0f3ff8..e7be8795f 100644 --- a/cwms-data-api/src/main/java/cwms/cda/helpers/ResourceHelper.java +++ b/cwms-data-api/src/main/java/cwms/cda/helpers/ResourceHelper.java @@ -4,12 +4,11 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.stream.Collectors; public final class ResourceHelper { - private static final Logger logger = Logger.getLogger(ResourceHelper.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** * Returns resource as a string, null if resource can't be found. * @param resource The path to the resource @@ -21,7 +20,7 @@ public static String getResourceAsString(String resource, Class context) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(formatList));) { return reader.lines().collect(Collectors.joining("\n")); } catch (IOException e) { - logger.log(Level.SEVERE,"Error access resource",e); + logger.atSevere().withCause(e).log("Error access resource"); } return null; } diff --git a/cwms-data-api/src/main/java/cwms/cda/security/CwmsAaaIdentityProvider.java b/cwms-data-api/src/main/java/cwms/cda/security/CwmsAaaIdentityProvider.java index 5ba3d82c3..117d8199d 100644 --- a/cwms-data-api/src/main/java/cwms/cda/security/CwmsAaaIdentityProvider.java +++ b/cwms-data-api/src/main/java/cwms/cda/security/CwmsAaaIdentityProvider.java @@ -14,8 +14,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.jetbrains.annotations.NotNull; @@ -24,7 +23,7 @@ @AutoService(IdentityProvider.class) public class CwmsAaaIdentityProvider implements IdentityProvider { - private static final Logger logger = Logger.getLogger(CwmsAaaIdentityProvider.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String SESSION_COOKIE_NAME = "JSESSIONIDSSO"; private DataApiPrincipal getApiPrincipal(Context ctx) { @@ -42,7 +41,7 @@ private static Optional getUser(Context ctx) { if (ctx != null && ctx.req != null && ctx.req.getUserPrincipal() != null) { retval = Optional.of(ctx.req.getUserPrincipal().getName()); } else { - logger.log(Level.FINE, "No user principal found in request."); + logger.atFine().log("No user principal found in request."); } return retval; } @@ -75,9 +74,9 @@ private static Set getRoles(Principal principal) { if (roleNames != null) { roleNames.stream().map(CwmsAaaIdentityProvider::buildRole).forEach(retval::add); } - logger.log(Level.FINE, "Principal had roles: {0}", retval); + logger.atFine().log("Principal had roles: %s", retval); } catch (ClassCastException e) { - logger.severe("cwmsaaa api and implementation jars should only be in the system " + logger.atSevere().log("cwmsaaa api and implementation jars should only be in the system " + "classpath, not the war file. Verify and restart application"); } } else { From d0c030dd179fd215f6b2dc2b0cd5f28c95c7415e Mon Sep 17 00:00:00 2001 From: rma-rripken <89810919+rma-rripken@users.noreply.github.com> Date: Tue, 18 Nov 2025 15:12:18 -0800 Subject: [PATCH 2/4] Checking for read-only connections and not attempting to set the user or office if the connection is read-only. --- .../cda/datasource/DirectUserPreparer.java | 28 +++++++++++++------ .../cda/datasource/SessionOfficePreparer.java | 21 +++++++++----- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/datasource/DirectUserPreparer.java b/cwms-data-api/src/main/java/cwms/cda/datasource/DirectUserPreparer.java index 94876824e..b0ec66f83 100644 --- a/cwms-data-api/src/main/java/cwms/cda/datasource/DirectUserPreparer.java +++ b/cwms-data-api/src/main/java/cwms/cda/datasource/DirectUserPreparer.java @@ -2,10 +2,14 @@ import java.sql.Connection; import java.sql.PreparedStatement; +import java.util.concurrent.TimeUnit; + +import com.google.common.flogger.FluentLogger; import org.jooq.exception.DataAccessException; public class DirectUserPreparer implements ConnectionPreparer { + public static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final String user; public DirectUserPreparer(String user) { @@ -14,15 +18,23 @@ public DirectUserPreparer(String user) { @Override public Connection prepare(Connection conn) { - if (user != null) { - String sql = "begin cwms_env.set_session_user_direct(upper(?)); end;"; - try (PreparedStatement setApiUser = conn.prepareStatement(sql)) { - setApiUser.setString(1,user); - setApiUser.execute(); - } catch (Exception e) { - throw new DataAccessException("Unable to set user session. " - + "user empty = " + user.isEmpty(), e); + try { + if (!conn.isReadOnly()) { + if (user != null) { + String sql = "begin cwms_env.set_session_user_direct(upper(?)); end;"; + try (PreparedStatement setApiUser = conn.prepareStatement(sql)) { + setApiUser.setString(1, user); + setApiUser.execute(); + } + } + } else { + logger.atFiner() + .atMostEvery(10, TimeUnit.MINUTES) + .log("Connection is read-only. No user session set."); } + } catch (Exception e) { + throw new DataAccessException("Unable to set user session. " + + "user empty = " + user.isEmpty(), e); } return conn; diff --git a/cwms-data-api/src/main/java/cwms/cda/datasource/SessionOfficePreparer.java b/cwms-data-api/src/main/java/cwms/cda/datasource/SessionOfficePreparer.java index bc5044ab4..c869c17c2 100644 --- a/cwms-data-api/src/main/java/cwms/cda/datasource/SessionOfficePreparer.java +++ b/cwms-data-api/src/main/java/cwms/cda/datasource/SessionOfficePreparer.java @@ -1,7 +1,8 @@ package cwms.cda.datasource; import java.sql.Connection; -import java.util.logging.Logger; + +import com.google.common.flogger.FluentLogger; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -10,7 +11,7 @@ import usace.cwms.db.jooq.codegen.packages.CWMS_ENV_PACKAGE; public class SessionOfficePreparer implements ConnectionPreparer { - private static final Logger logger = Logger.getLogger(SessionOfficePreparer.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final String office; @@ -21,16 +22,22 @@ public SessionOfficePreparer(String office) { @Override public Connection prepare(Connection conn) { - if(office != null && !office.isEmpty()) { - DSLContext dsl = DSL.using(conn, SQLDialect.ORACLE18C); + if (office != null && !office.isEmpty()) { try { - logger.fine("Setting office to: " + office); - CWMS_ENV_PACKAGE.call_SET_SESSION_OFFICE_ID(dsl.configuration(), office); + if (!conn.isReadOnly()) { + DSLContext dsl = DSL.using(conn, SQLDialect.ORACLE18C); + + logger.atFine().log("Setting office to: %s", office); + CWMS_ENV_PACKAGE.call_SET_SESSION_OFFICE_ID(dsl.configuration(), office); + } else { + logger.atFiner().atMostEvery(10, java.util.concurrent.TimeUnit.MINUTES) + .log("Connection is read-only. No office session set."); + } } catch (Exception e) { throw new DataAccessException("Unable to set session office id to " + office, e); } } else { - logger.fine("Office is null or empty."); + logger.atFine().log("Office is null or empty."); // Should we call clear_session_privileges ? } return conn; From ad2f6f5dd616f3cd57bfd5ddc925bd00c58f78da Mon Sep 17 00:00:00 2001 From: rma-rripken <89810919+rma-rripken@users.noreply.github.com> Date: Tue, 18 Nov 2025 15:23:00 -0800 Subject: [PATCH 3/4] Replace JUL with Flogger --- .../src/main/java/cwms/cda/ApiServlet.java | 2 +- .../cda/api/LocationCategoryController.java | 2 +- .../java/cwms/cda/api/LocationController.java | 2 +- .../cwms/cda/api/LocationGroupController.java | 2 +- .../java/cwms/cda/api/PoolController.java | 6 +- .../java/cwms/cda/api/ProjectController.java | 2 +- .../cda/api/TimeSeriesCategoryController.java | 2 +- .../cda/api/TimeSeriesGroupController.java | 2 +- ...eSeriesIdentifierDescriptorController.java | 2 +- .../main/java/cwms/cda/data/dao/AuthDao.java | 2 +- .../main/java/cwms/cda/data/dao/UserDao.java | 10 +- .../DelegatingConnectionPreparer.java | 2 +- .../cda/datasource/DirectUserPreparer.java | 2 +- .../java/cwms/cda/formatters/Formats.java | 2 +- .../java/cwms/cda/helpers/ResourceHelper.java | 2 +- .../java/cwms/cda/security/Authenticator.java | 2 +- .../cwms/cda/security/CdaAccessManager.java | 2 +- .../java/cwms/cda/api/ClobControllerTest.java | 2 +- .../api/LocationGroupControllerTestIT.java | 9 +- .../java/cwms/cda/api/LockControllerIT.java | 21 +- .../api/TimeSeriesGroupControllerTestIT.java | 11 +- .../api/TimeSeriesProfileControllerIT.java | 7 +- ...TimeSeriesProfileInstanceControllerIT.java | 12 +- .../TimeSeriesProfileParserControllerIT.java | 9 +- .../cda/api/TimeSeriesRecentControllerIT.java | 11 +- .../WaterContractTypeControllerTestIT.java | 8 +- .../WaterSupplyAccountingControllerIT.java | 29 +- .../cda/api/auth/OpenIdConnectTestIT.java | 3 - .../api/project/ProjectLockHandlerUtil.java | 4 +- .../ProjectPublishStatusUpdateHandlerIT.java | 3 +- .../cda/api/rating/RatingsControllerTest.java | 11 +- .../cda/api/users/UserManagementTestIT.java | 5 - .../cwms/cda/data/dao/TimeSeriesDaoTest.java | 477 +++++++++--------- .../cda/data/dao/location/kind/LockDaoIT.java | 21 +- .../TimeSeriesProfileInstanceDaoIT.java | 7 +- .../test/java/fixtures/KeyCloakExtension.java | 13 +- .../test/java/helpers/TsRandomSampler.java | 10 +- 37 files changed, 330 insertions(+), 389 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/ApiServlet.java b/cwms-data-api/src/main/java/cwms/cda/ApiServlet.java index e63d41dcd..ad08d1ecc 100644 --- a/cwms-data-api/src/main/java/cwms/cda/ApiServlet.java +++ b/cwms-data-api/src/main/java/cwms/cda/ApiServlet.java @@ -256,7 +256,7 @@ }) public class ApiServlet extends HttpServlet { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // based on https://bitbucket.hecdev.net/projects/CWMS/repos/cwms_aaa/browse/IntegrationTests/src/test/resources/sql/load_testusers.sql public static final String CWMS_USERS_ROLE = "CWMS Users"; diff --git a/cwms-data-api/src/main/java/cwms/cda/api/LocationCategoryController.java b/cwms-data-api/src/main/java/cwms/cda/api/LocationCategoryController.java index 35c4cf6cd..314109ce5 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/LocationCategoryController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/LocationCategoryController.java @@ -53,7 +53,7 @@ import org.jooq.DSLContext; public class LocationCategoryController implements CrudHandler { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String TAG = "Location Categories"; private final MetricRegistry metrics; diff --git a/cwms-data-api/src/main/java/cwms/cda/api/LocationController.java b/cwms-data-api/src/main/java/cwms/cda/api/LocationController.java index f94bfd5b3..7b8728457 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/LocationController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/LocationController.java @@ -72,7 +72,7 @@ public class LocationController implements CrudHandler { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final MetricRegistry metrics; private final Histogram requestResultSize; diff --git a/cwms-data-api/src/main/java/cwms/cda/api/LocationGroupController.java b/cwms-data-api/src/main/java/cwms/cda/api/LocationGroupController.java index 235827eac..4de616ef3 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/LocationGroupController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/LocationGroupController.java @@ -57,7 +57,7 @@ import org.jooq.DSLContext; public class LocationGroupController implements CrudHandler { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String LOCATION_OFFICE_ID = "location-office-id"; public static final String TAG = "Location Groups"; diff --git a/cwms-data-api/src/main/java/cwms/cda/api/PoolController.java b/cwms-data-api/src/main/java/cwms/cda/api/PoolController.java index 7a2dd82b5..5d7616031 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/PoolController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/PoolController.java @@ -47,7 +47,7 @@ import org.jooq.DSLContext; public class PoolController implements CrudHandler { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int defaultPageSize = 100; private final MetricRegistry metrics; @@ -99,7 +99,7 @@ private Timer.Context markAndTime(String subject) { tags = {"Pools"}) @Override public void getAll(@NotNull Context ctx) { - try (final Timer.Context timeContext = markAndTime(GET_ALL);){ + try (final Timer.Context timeContext = markAndTime(GET_ALL)){ DSLContext dsl = getDslContext(ctx); PoolDao dao = new PoolDao(dsl); @@ -179,7 +179,7 @@ public void getAll(@NotNull Context ctx) { description = "Retrieves requested Pool", tags = {"Pools"}) @Override public void getOne(@NotNull Context ctx, @NotNull String poolId) { - try (final Timer.Context timeContext = markAndTime(GET_ONE);){ + try (final Timer.Context timeContext = markAndTime(GET_ONE)){ DSLContext dsl = getDslContext(ctx); PoolDao dao = new PoolDao(dsl); diff --git a/cwms-data-api/src/main/java/cwms/cda/api/ProjectController.java b/cwms-data-api/src/main/java/cwms/cda/api/ProjectController.java index 4261d016b..62c92d9e7 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/ProjectController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/ProjectController.java @@ -71,7 +71,7 @@ import org.jooq.DSLContext; public class ProjectController implements CrudHandler { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final int DEFAULT_PAGE_SIZE = 100; public static final String TAG = "Projects"; diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesCategoryController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesCategoryController.java index 0993bee92..e7f455ae7 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesCategoryController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesCategoryController.java @@ -53,7 +53,7 @@ import org.jooq.DSLContext; public class TimeSeriesCategoryController implements CrudHandler { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String TAG = "TimeSeries Categories"; private final MetricRegistry metrics; diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesGroupController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesGroupController.java index 34ece4b81..2c4f86c29 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesGroupController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesGroupController.java @@ -75,7 +75,7 @@ import org.jooq.DSLContext; public class TimeSeriesGroupController implements CrudHandler { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String TAG = "Timeseries Groups"; private final MetricRegistry metrics; diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesIdentifierDescriptorController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesIdentifierDescriptorController.java index 1ee916c83..b54717b26 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesIdentifierDescriptorController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesIdentifierDescriptorController.java @@ -58,7 +58,7 @@ import org.jooq.exception.DataAccessException; public class TimeSeriesIdentifierDescriptorController implements CrudHandler { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String TAG = "TimeSeries Identifier"; private static final int DEFAULT_PAGE_SIZE = 500; diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/AuthDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/AuthDao.java index 06d30cac6..b6309ac48 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/AuthDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/AuthDao.java @@ -49,7 +49,7 @@ import static cwms.cda.data.dao.JooqDao.connection; public class AuthDao extends Dao { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String SCHEMA_TOO_OLD = "The CWMS-Data-API requires schema version " + "23.03.16 or later to handle authorization operations."; public static final String DATA_API_PRINCIPAL = "DataApiPrincipal"; diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java index c2e12d63f..4912dd558 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java @@ -4,10 +4,8 @@ import static org.jooq.impl.DSL.*; import java.sql.CallableStatement; -import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -18,12 +16,9 @@ import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; -import org.jooq.Record; import org.jooq.Record1; -import org.jooq.Record4; import org.jooq.Record5; import org.jooq.SelectConditionStep; -import org.jooq.SelectLimitPercentStep; import org.jooq.SelectSeekStep2; import org.jooq.Table; import org.jooq.conf.ParamType; @@ -31,17 +26,14 @@ import com.google.common.flogger.FluentLogger; -import cwms.cda.data.dto.Clob; -import cwms.cda.data.dto.Clobs; import cwms.cda.data.dto.CwmsDTOPaginated; import cwms.cda.data.dto.auth.users.User; import cwms.cda.data.dto.auth.users.Users; -import cwms.cda.security.CwmsAuthException; import cwms.cda.security.DataApiPrincipal; import usace.cwms.db.jooq.codegen.tables.AV_SEC_USERS; public class UserDao extends JooqDao { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String GET_USER = "select ut.userid as username,ut.email, ut.principle_name,groups.db_office_id as \"office\",groups.user_group_id as \"role\" " + diff --git a/cwms-data-api/src/main/java/cwms/cda/datasource/DelegatingConnectionPreparer.java b/cwms-data-api/src/main/java/cwms/cda/datasource/DelegatingConnectionPreparer.java index 4aae41c6a..8ce234a7a 100644 --- a/cwms-data-api/src/main/java/cwms/cda/datasource/DelegatingConnectionPreparer.java +++ b/cwms-data-api/src/main/java/cwms/cda/datasource/DelegatingConnectionPreparer.java @@ -9,7 +9,7 @@ public class DelegatingConnectionPreparer implements ConnectionPreparer { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final List delegates = new ArrayList<>(); public DelegatingConnectionPreparer(List preparers) { diff --git a/cwms-data-api/src/main/java/cwms/cda/datasource/DirectUserPreparer.java b/cwms-data-api/src/main/java/cwms/cda/datasource/DirectUserPreparer.java index b0ec66f83..9ca683b4e 100644 --- a/cwms-data-api/src/main/java/cwms/cda/datasource/DirectUserPreparer.java +++ b/cwms-data-api/src/main/java/cwms/cda/datasource/DirectUserPreparer.java @@ -9,7 +9,7 @@ public class DirectUserPreparer implements ConnectionPreparer { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final String user; public DirectUserPreparer(String user) { diff --git a/cwms-data-api/src/main/java/cwms/cda/formatters/Formats.java b/cwms-data-api/src/main/java/cwms/cda/formatters/Formats.java index e71eb1262..1cd1568d2 100644 --- a/cwms-data-api/src/main/java/cwms/cda/formatters/Formats.java +++ b/cwms-data-api/src/main/java/cwms/cda/formatters/Formats.java @@ -44,7 +44,7 @@ public class Formats { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final String PLAIN = "text/plain"; // Only used as a constant, not for any // data mapping public static final String JSON = "application/json"; diff --git a/cwms-data-api/src/main/java/cwms/cda/helpers/ResourceHelper.java b/cwms-data-api/src/main/java/cwms/cda/helpers/ResourceHelper.java index e7be8795f..3fa22f58a 100644 --- a/cwms-data-api/src/main/java/cwms/cda/helpers/ResourceHelper.java +++ b/cwms-data-api/src/main/java/cwms/cda/helpers/ResourceHelper.java @@ -17,7 +17,7 @@ public final class ResourceHelper { * */ public static String getResourceAsString(String resource, Class context) { InputStream formatList = getResourceAsStream(resource, context); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(formatList));) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(formatList))) { return reader.lines().collect(Collectors.joining("\n")); } catch (IOException e) { logger.atSevere().withCause(e).log("Error access resource"); diff --git a/cwms-data-api/src/main/java/cwms/cda/security/Authenticator.java b/cwms-data-api/src/main/java/cwms/cda/security/Authenticator.java index d26120eee..53fa72b63 100644 --- a/cwms-data-api/src/main/java/cwms/cda/security/Authenticator.java +++ b/cwms-data-api/src/main/java/cwms/cda/security/Authenticator.java @@ -13,7 +13,7 @@ import io.javalin.http.Handler; public final class Authenticator implements Handler { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final ArrayList providers = new ArrayList<>(); public Authenticator() { diff --git a/cwms-data-api/src/main/java/cwms/cda/security/CdaAccessManager.java b/cwms-data-api/src/main/java/cwms/cda/security/CdaAccessManager.java index ab92fd49c..cc8f9a274 100644 --- a/cwms-data-api/src/main/java/cwms/cda/security/CdaAccessManager.java +++ b/cwms-data-api/src/main/java/cwms/cda/security/CdaAccessManager.java @@ -20,7 +20,7 @@ import java.util.concurrent.TimeUnit; public final class CdaAccessManager implements AccessManager { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); // specify the maximum number of requests allowed per time unit public static final String REQUEST_LIMIT_KEY = "cwms.dataapi.request.limit"; diff --git a/cwms-data-api/src/test/java/cwms/cda/api/ClobControllerTest.java b/cwms-data-api/src/test/java/cwms/cda/api/ClobControllerTest.java index 239aab655..13b8f05c8 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/ClobControllerTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/ClobControllerTest.java @@ -26,7 +26,7 @@ import org.junit.jupiter.api.Test; public class ClobControllerTest extends ControllerTest { - public static final FluentLogger logger = FluentLogger.forEnclosingClass(); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Test diff --git a/cwms-data-api/src/test/java/cwms/cda/api/LocationGroupControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/LocationGroupControllerTestIT.java index 886855ce9..fe6f3b6ff 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/LocationGroupControllerTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/LocationGroupControllerTestIT.java @@ -42,8 +42,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import mil.army.usace.hec.test.database.CwmsDatabaseContainer; import org.apache.commons.lang3.RandomStringUtils; @@ -64,7 +63,7 @@ @Tag("integration") class LocationGroupControllerTestIT extends DataApiTestIT { - private static final Logger LOGGER = Logger.getLogger(LocationGroupControllerTestIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private final List groupsToCleanup = new ArrayList<>(); private final List categoriesToCleanup = new ArrayList<>(); TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; @@ -86,14 +85,14 @@ void tearDown() throws Exception { locationGroupDao.delete(group.getLocationCategory().getId(), group.getId(), true, group.getOfficeId()); } } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, String.format("Failed to delete location group: %s", group.getId()), e); + LOGGER.atConfig().withCause(e).log("Failed to delete location group: %s", group.getId()); } } for (LocationCategory category : categoriesToCleanup) { try { locationCategoryDao.delete(category.getId(), true, category.getOfficeId()); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, String.format("Failed to delete location category: %s", category.getId()), e); + LOGGER.atConfig().withCause(e).log("Failed to delete location category: %s", category.getId()); } } }, CwmsDataApiSetupCallback.getWebUser()); diff --git a/cwms-data-api/src/test/java/cwms/cda/api/LockControllerIT.java b/cwms-data-api/src/test/java/cwms/cda/api/LockControllerIT.java index 5e70195ad..aebd12f0d 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/LockControllerIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/LockControllerIT.java @@ -65,8 +65,7 @@ import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import mil.army.usace.hec.test.database.CwmsDatabaseContainer; import org.apache.commons.io.IOUtils; @@ -84,7 +83,7 @@ @Tag("integration") final class LockControllerIT extends DataApiTestIT { - private static final Logger LOGGER = Logger.getLogger(LockControllerIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private static final Location PROJECT_LOC; private static final Location PROJECT_LOC2; private static final Location LOCK_LOC; @@ -177,14 +176,14 @@ static void tearDown() throws Exception { } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, String.format("Unable to delete Lock location: %s", ex.getMessage())); + LOGGER.atConfig().log("Unable to delete Lock location: %s", ex.getMessage()); } try { locationsDao.deleteLocation(LOCK_LOC2.getName(), LOCK_LOC2.getOfficeId(), true); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, String.format("Unable to delete Lock location: %s", ex.getMessage())); + LOGGER.atConfig().log("Unable to delete Lock location: %s", ex.getMessage()); } try { CWMS_PROJECT_PACKAGE.call_DELETE_PROJECT(context.configuration(), PROJECT_LOC.getName(), @@ -192,19 +191,19 @@ static void tearDown() throws Exception { } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, String.format("Unable to delete project: %s", ex.getMessage())); + LOGGER.atConfig().log("Unable to delete project: %s", ex.getMessage()); } try { locationsDao.deleteLocation(PROJECT_LOC.getName(), PROJECT_LOC.getOfficeId(), true); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, String.format("Unable to delete project location: %s", ex.getMessage())); + LOGGER.atConfig().log("Unable to delete project location: %s", ex.getMessage()); } try { locationsDao.deleteLocation(PROJECT_LOC2.getName(), PROJECT_LOC2.getOfficeId(), true); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, String.format("Unable to delete project location: %s", ex.getMessage())); + LOGGER.atConfig().log("Unable to delete project location: %s", ex.getMessage()); } }, CwmsDataApiSetupCallback.getWebUser()); } @@ -221,7 +220,7 @@ void cleanupBetween() throws Exception { lockDao.deleteLock(CwmsId.buildCwmsId(lockToCleanup.getLocation().getOfficeId(), lockToCleanup.getLocation().getName()), DeleteRule.DELETE_ALL); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, String.format("Unable to delete lock: %s", ex.getMessage())); + LOGGER.atConfig().log("Unable to delete lock: %s", ex.getMessage()); } } for (LocationLevel level : createLocationLevelList(LOCK)) { @@ -229,7 +228,7 @@ void cleanupBetween() throws Exception { levelsDao.deleteLocationLevel(level.getLocationLevelId(), level.getLevelDate(), level.getOfficeId(), true); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, String.format("Unable to delete location level: %s", ex.getMessage())); + LOGGER.atConfig().log("Unable to delete location level: %s", ex.getMessage()); } } for (LocationLevel level : locationLevelsToCleanup) { @@ -237,7 +236,7 @@ void cleanupBetween() throws Exception { levelsDao.deleteLocationLevel(level.getLocationLevelId(), level.getLevelDate(), level.getOfficeId(), true); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, String.format("Unable to delete location level: %s", ex.getMessage())); + LOGGER.atConfig().log("Unable to delete location level: %s", ex.getMessage()); } } locationLevelsToCleanup.clear(); diff --git a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesGroupControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesGroupControllerTestIT.java index 9f49102b7..a74b25314 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesGroupControllerTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesGroupControllerTestIT.java @@ -50,8 +50,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletResponse; import mil.army.usace.hec.test.database.CwmsDatabaseContainer; import org.apache.commons.io.IOUtils; @@ -81,7 +80,7 @@ final class TimeSeriesGroupControllerTestIT extends DataApiTestIT { private List categoriesToCleanup = new ArrayList<>(); private List groupsToCleanup = new ArrayList<>(); private List timeSeriesToCleanup = new ArrayList<>(); - private static final Logger LOGGER = Logger.getLogger(TimeSeriesGroupControllerTestIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; TestAccounts.KeyUser user2 = TestAccounts.KeyUser.SWT_NORMAL; @@ -122,14 +121,14 @@ void clear_data() throws Exception { groupDao.delete(group.getTimeSeriesCategory().getId(), group.getId(), group.getOfficeId()); } } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Group not found", e); + LOGGER.atConfig().withCause(e).log("Group not found"); } } for (TimeSeriesCategory category : categoriesToCleanup) { try { categoryDao.delete(category.getId(), true, category.getOfficeId()); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Category not found", e); + LOGGER.atConfig().withCause(e).log("Category not found"); } } for (TimeSeries ts : timeSeriesToCleanup) { @@ -138,7 +137,7 @@ void clear_data() throws Exception { .withStartTimeInclusive(true).withEndTimeInclusive(true).withMaxVersion(false) .withOverrideProtection(formatBool(true)).build()); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Time Series not found", e); + LOGGER.atConfig().withCause(e).log("Time Series not found"); } } groupsToCleanup.clear(); diff --git a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileControllerIT.java b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileControllerIT.java index f4ba123f6..70cda80cf 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileControllerIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileControllerIT.java @@ -46,8 +46,7 @@ import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -59,7 +58,7 @@ @Tag("integration") final class TimeSeriesProfileControllerIT extends DataApiTestIT { - private static final Logger LOGGER = Logger.getLogger(TimeSeriesProfileControllerIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private static final String OFFICE_ID = "SPK"; private static final TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; private final InputStream resource = this.getClass() @@ -555,7 +554,7 @@ private void cleanupTS(String locationId, String keyParameter) throws Exception dao.deleteTimeSeriesProfile(locationId, keyParameter, OFFICE_ID); }); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Unable to cleanup TS Profile - not found", e); + LOGGER.atConfig().withCause(e).log("Unable to cleanup TS Profile - not found"); } } } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileInstanceControllerIT.java b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileInstanceControllerIT.java index 72376bd77..681f1945d 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileInstanceControllerIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileInstanceControllerIT.java @@ -54,8 +54,7 @@ import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.time.Instant; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; @@ -75,8 +74,7 @@ @Tag("integration") final class TimeSeriesProfileInstanceControllerIT extends DataApiTestIT { - public static final Logger LOGGER = - Logger.getLogger(TimeSeriesProfileInstanceControllerIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private static final String OFFICE_ID = "SPK"; private static final TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; private final InputStream resource = this.getClass() @@ -1850,7 +1848,7 @@ private void cleanupParser(DSLContext dsl, String locationId, String parameterId TimeSeriesProfileParserDao dao = new TimeSeriesProfileParserDao(dsl); dao.deleteTimeSeriesProfileParser(locationId, parameterId, OFFICE_ID); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Cleanup failed for parser - no matching parser found in DB", e); + LOGGER.atConfig().withCause(e).log("Cleanup failed for parser - no matching parser found in DB"); } } @@ -1859,7 +1857,7 @@ private void cleanupTS(DSLContext dsl, String locationId, String keyParameter) { TimeSeriesProfileDao dao = new TimeSeriesProfileDao(dsl); dao.deleteTimeSeriesProfile(locationId, keyParameter, OFFICE_ID); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Cleanup failed for Timeseries - no matching TS found in DB", e); + LOGGER.atConfig().withCause(e).log("Cleanup failed for Timeseries - no matching TS found in DB"); } } @@ -1870,7 +1868,7 @@ private void cleanupInstance(DSLContext dsl, CwmsId locationId, String keyParame dao.deleteTimeSeriesProfileInstance(locationId, keyParameter, version, firstDate, timeZone, overrideProt, versionDate); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Cleanup failed for instance - no matching instance found in DB", e); + LOGGER.atConfig().withCause(e).log("Cleanup failed for instance - no matching instance found in DB"); } } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileParserControllerIT.java b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileParserControllerIT.java index 687ad6ce0..619ba2bcc 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileParserControllerIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesProfileParserControllerIT.java @@ -49,8 +49,7 @@ import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -63,7 +62,7 @@ @Tag("integration") final class TimeSeriesProfileParserControllerIT extends DataApiTestIT { private static final String OFFICE_ID = "SPK"; - private static final Logger LOGGER = Logger.getLogger(TimeSeriesProfileParserControllerIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private static final TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; private final InputStream resourceIndexed = this.getClass() .getResourceAsStream("/cwms/cda/api/timeseriesprofile/ts_profile_parser_indexed.json"); @@ -414,7 +413,7 @@ private void cleanupParser(String locationId, String parameterId) throws Excepti dao.deleteTimeSeriesProfileParser(locationId, parameterId, OFFICE_ID); }, CwmsDataApiSetupCallback.getWebUser()); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Parser Cleanup failed", e); + LOGGER.atConfig().withCause(e).log("Parser Cleanup failed"); } } @@ -427,7 +426,7 @@ private void cleanupTS(String locationId, String keyParameter) throws Exception dao.deleteTimeSeriesProfile(locationId, keyParameter, OFFICE_ID); }, CwmsDataApiSetupCallback.getWebUser()); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "TS Cleanup failed", e); + LOGGER.atConfig().withCause(e).log("TS Cleanup failed"); } } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesRecentControllerIT.java b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesRecentControllerIT.java index 338c1bfbf..027ee5231 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesRecentControllerIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/TimeSeriesRecentControllerIT.java @@ -56,8 +56,7 @@ import java.util.Collections; import java.util.Date; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import mil.army.usace.hec.test.database.CwmsDatabaseContainer; import org.jetbrains.annotations.NotNull; import org.jooq.DSLContext; @@ -71,7 +70,7 @@ @Tag("integration") class TimeSeriesRecentControllerIT extends DataApiTestIT { TestAccounts.KeyUser user = TestAccounts.KeyUser.SPK_NORMAL; - private static final Logger LOGGER = Logger.getLogger(TimeSeriesRecentControllerIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private static final String OFFICE_ID = "SPK"; private static final String LOCATION = "Sacramento River Delta"; private static final String TS_ID = LOCATION + ".Depth.Inst.15Minutes.0.OBS-Raw"; @@ -100,18 +99,18 @@ static void cleanup() throws Exception { .withVersionDate(Date.from(VERSION_DATE.toInstant())).withMaxVersion(false) .withOverrideProtection("F").withEndTimeInclusive(true).withStartTimeInclusive(true).build()); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "TimeSeries not found"); + LOGGER.atConfig().log("TimeSeries not found"); } try { tsGroupDao.unassignAllTs(group, OFFICE_ID); tsGroupDao.delete(CATEGORY_ID, GROUP_ID, OFFICE_ID); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Group not found"); + LOGGER.atConfig().log("Group not found"); } try { tsCategoryDao.delete(CATEGORY_ID, true, OFFICE_ID); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, "Category not found"); + LOGGER.atConfig().log("Category not found"); } }); } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java index 998cff8c6..17fdec320 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterContractTypeControllerTestIT.java @@ -53,8 +53,7 @@ import java.sql.SQLException; import java.util.Arrays; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; @Tag("integration") @@ -64,8 +63,7 @@ class WaterContractTypeControllerTestIT extends DataApiTestIT { private static final String OFFICE_ID_TEXT = "office-id"; private static final String MESSAGE = "message"; private static final String IDENTIFIER = "identifier"; - public static final Logger LOGGER = - Logger.getLogger(WaterContractTypeControllerTestIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); static { CONTRACT_TYPE = new LookupType.Builder().withActive(true).withOfficeId(OFFICE_ID) .withDisplayValue("TEST Contract Type").withTooltip("TEST LOOKUP").build(); @@ -251,7 +249,7 @@ private void cleanupType() throws SQLException { lookupTypeDao.deleteLookupType("AT_WS_CONTRACT_TYPE", "WS_CONTRACT_TYPE", CONTRACT_TYPE.getOfficeId(), CONTRACT_TYPE.getDisplayValue()); } catch (NotFoundException e) { - LOGGER.log(Level.CONFIG, format("Cleanup failed to delete lookup type: %s", e.getMessage())); + LOGGER.atConfig().log("Cleanup failed to delete lookup type: %s", e.getMessage()); } }, CwmsDataApiSetupCallback.getWebUser()); } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/WaterSupplyAccountingControllerIT.java b/cwms-data-api/src/test/java/cwms/cda/api/WaterSupplyAccountingControllerIT.java index fe5d0ec3a..ff06a5e73 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/WaterSupplyAccountingControllerIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/WaterSupplyAccountingControllerIT.java @@ -62,8 +62,7 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.ZoneId; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import static cwms.cda.api.Controllers.UNIT; import static cwms.cda.data.dao.DaoTest.getDslContext; @@ -74,7 +73,7 @@ @Tag("integration") class WaterSupplyAccountingControllerIT extends DataApiTestIT { - private static final Logger LOGGER = Logger.getLogger(WaterSupplyAccountingControllerIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private static final String OFFICE_ID = "SPK"; private static WaterSupplyAccounting waterSupplyAccounting; private static final String START_TIME = "start"; @@ -121,7 +120,7 @@ class WaterSupplyAccountingControllerIT extends DataApiTestIT { pump3 = buildTestLocation(waterSupplyAccounting.getPumpLocations().getPumpBelow().getName(), "PUMP"); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete location: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete location: %s", e.getMessage()); } } @@ -154,13 +153,13 @@ static void setup() throws Exception { lookupTypeDao.storeLookupType("AT_PHYSICAL_TRANSFER_TYPE","PHYS_TRANS_TYPE", testTransferType); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to store lookup type: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to store lookup type: %s", e.getMessage()); } try { lookupTypeDao.storeLookupType("AT_WS_CONTRACT_TYPE","WS_CONTRACT_TYPE", testContractType); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to store lookup type: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to store lookup type: %s", e.getMessage()); } try { projectDao.store(project, false); @@ -218,55 +217,55 @@ static void cleanup() { { waterContractDao.deleteWaterContract(contract, DeleteMethod.DELETE_ALL); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete water contract: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete water contract: %s", e.getMessage()); } try { lookupTypeDao.deleteLookupType("AT_PHYSICAL_TRANSFER_TYPE", "PHYS_TRANS_TYPE", OFFICE_ID, testTransferType.getDisplayValue()); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete lookup type: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete lookup type: %s", e.getMessage()); } try { lookupTypeDao.deleteLookupType("AT_WS_CONTRACT_TYPE", "WS_CONTRACT_TYPE", OFFICE_ID, testContractType.getDisplayValue()); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete contract lookup type: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete contract lookup type: %s", e.getMessage()); } try { projectDao.delete(contract.getOfficeId(), contract.getWaterUser().getProjectId().getName(), DeleteRule.DELETE_ALL); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete project: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete project: %s", e.getMessage()); } try { locationsDao.deleteLocation(pump1.getName(), pump1.getOfficeId(), true); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete location: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete location: %s", e.getMessage()); } try { locationsDao.deleteLocation(pump3.getName(), pump3.getOfficeId(), true); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete location: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete location: %s", e.getMessage()); } try { locationsDao.deleteLocation(contractLocation.getName(), contractLocation.getOfficeId(), true); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete location: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete location: %s", e.getMessage()); } try { locationsDao.deleteLocation(parentLocation.getName(), parentLocation.getOfficeId(), true); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete location: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete location: %s", e.getMessage()); } }, CwmsDataApiSetupCallback.getWebUser()); } catch (Exception e) { - LOGGER.log(Level.CONFIG, String.format("Unable to delete object: %s", e.getMessage())); + LOGGER.atConfig().log("Unable to delete object: %s", e.getMessage()); } } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/auth/OpenIdConnectTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/auth/OpenIdConnectTestIT.java index be635a5fc..ffa71eb81 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/auth/OpenIdConnectTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/auth/OpenIdConnectTestIT.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Optional; -import java.util.logging.Logger; import org.junit.jupiter.api.Tag; @@ -16,12 +15,10 @@ import fixtures.KeyCloakExtension; import io.javalin.http.HttpCode; import io.restassured.filter.log.LogDetail; -import io.restassured.http.ContentType; @Tag("integration") @ExtendWith(KeyCloakExtension.class) public class OpenIdConnectTestIT extends DataApiTestIT { - private static final Logger logger = Logger.getLogger(OpenIdConnectTestIT.class.getName()); @Test diff --git a/cwms-data-api/src/test/java/cwms/cda/api/project/ProjectLockHandlerUtil.java b/cwms-data-api/src/test/java/cwms/cda/api/project/ProjectLockHandlerUtil.java index 0d566982e..f9b8df74c 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/project/ProjectLockHandlerUtil.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/project/ProjectLockHandlerUtil.java @@ -35,7 +35,7 @@ import java.time.Instant; import java.time.ZoneId; import java.util.List; -import java.util.logging.Level; + import org.jooq.DSLContext; public class ProjectLockHandlerUtil { @@ -88,7 +88,7 @@ public static void deleteProject(DSLContext dsl, String projId, String office, S prjDao.delete(office, projId, DeleteRule.DELETE_ALL); } catch (Exception e) { ProjectLockDao lockDao = new ProjectLockDao(dsl); - logger.at(Level.WARNING).withCause(e).log("Failed to delete project: %s", projId); + logger.atWarning().withCause(e).log("Failed to delete project: %s", projId); List locks = lockDao.retrieveLocks(office, projId, appId); locks.forEach(lock -> { logger.atFine().log("Remaining Locks: " + lock.getProjectId() + " " + diff --git a/cwms-data-api/src/test/java/cwms/cda/api/project/ProjectPublishStatusUpdateHandlerIT.java b/cwms-data-api/src/test/java/cwms/cda/api/project/ProjectPublishStatusUpdateHandlerIT.java index 16f095177..e90243f56 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/project/ProjectPublishStatusUpdateHandlerIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/project/ProjectPublishStatusUpdateHandlerIT.java @@ -41,7 +41,6 @@ import io.restassured.filter.log.LogDetail; import java.sql.SQLException; import java.time.Instant; -import java.util.logging.Level; import javax.servlet.http.HttpServletResponse; import org.jooq.DSLContext; import org.junit.jupiter.api.AfterEach; @@ -78,7 +77,7 @@ void tearDown() throws SQLException { try { prjDao.delete(OFFICE, projId, DeleteRule.DELETE_ALL); } catch (Exception e) { - logger.at(Level.WARNING).withCause(e).log("Failed to delete project: %s", projId); + logger.atWarning().withCause(e).log("Failed to delete project: %s", projId); } }); } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/rating/RatingsControllerTest.java b/cwms-data-api/src/test/java/cwms/cda/api/rating/RatingsControllerTest.java index 4a2b2ba55..1dd831ede 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/rating/RatingsControllerTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/rating/RatingsControllerTest.java @@ -54,8 +54,7 @@ import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.HashMap; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; @@ -71,7 +70,7 @@ class RatingsControllerTest { - private static final Logger logger = Logger.getLogger(RatingsControllerTest.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private DataSource ds = mock(DataSource.class); private Connection conn = null; @@ -114,11 +113,11 @@ void post_to_create_passed_to_deserializeXml() throws Exception when(request.getHeader(Header.ACCEPT)).thenReturn(Formats.XMLV2); when(request.getContentType()).thenReturn(Formats.XMLV2); - logger.log(Level.INFO, "Test post_to_create_passed_to_deserializeXml may trigger a RatingException - this is fine."); + logger.atInfo().log("Test post_to_create_passed_to_deserializeXml may trigger a RatingException - this is fine."); try { controller.create(context); } catch (IllegalArgumentException e){ - logger.log(Level.INFO, "Test post_to_create_passed_to_deserializeXml caught an IllegalArgumentException - this is fine."); + logger.atInfo().log("Test post_to_create_passed_to_deserializeXml caught an IllegalArgumentException - this is fine."); } // For this test, it's ok that the server throws a RatingException // Only want to check that the controller accessed our mock dao in the expected way @@ -351,7 +350,7 @@ public int getLoginTimeout() throws SQLException } @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException + public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } diff --git a/cwms-data-api/src/test/java/cwms/cda/api/users/UserManagementTestIT.java b/cwms-data-api/src/test/java/cwms/cda/api/users/UserManagementTestIT.java index 8204447c5..0aa61184c 100644 --- a/cwms-data-api/src/test/java/cwms/cda/api/users/UserManagementTestIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/api/users/UserManagementTestIT.java @@ -7,9 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; -import java.util.Optional; -import java.util.logging.Logger; - import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -17,7 +14,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; -import cwms.cda.ApiServlet; import cwms.cda.api.DataApiTestIT; import cwms.cda.data.dto.auth.users.User; import cwms.cda.data.dto.auth.users.Users; @@ -32,7 +28,6 @@ @Tag("integration") @ExtendWith(KeyCloakExtension.class) public class UserManagementTestIT extends DataApiTestIT { - private static final Logger logger = Logger.getLogger(UserManagementTestIT.class.getName()); @ParameterizedTest @ArgumentsSource(UserSpecSource.class) diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dao/TimeSeriesDaoTest.java b/cwms-data-api/src/test/java/cwms/cda/data/dao/TimeSeriesDaoTest.java index 9de7371a2..096f68683 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dao/TimeSeriesDaoTest.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dao/TimeSeriesDaoTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import cwms.cda.data.dto.TimeSeries; + import java.math.BigDecimal; import java.sql.Connection; import java.sql.SQLException; @@ -15,8 +16,8 @@ import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; -import java.util.logging.Level; -import java.util.logging.Logger; + +import com.google.common.flogger.FluentLogger; import org.jooq.DSLContext; import org.jooq.Record1; import org.jooq.Result; @@ -32,253 +33,227 @@ import usace.cwms.db.jooq.codegen.tables.AV_LOC; @Disabled -public class TimeSeriesDaoTest -{ - private static final Logger LOGGER = Logger.getLogger(TimeSeriesDaoTest.class.getName()); - - public static final String LOC_ID = "RYAN3"; - public static final String TIME_SERIES_ID = LOC_ID + ".Stage.Inst.5Minutes.0.ZSTORE_TS_TEST" + Calendar.getInstance().get( - Calendar.MILLISECOND); - - public static final String UNITS = "m"; - public static final Timestamp VERSION_DATE = null; - - public static final Timestamp START_TIME; - - static - { - Calendar startCal = Calendar.getInstance(); - startCal.set(2010, 1, 1, 0, 0, 0); - startCal.set(Calendar.MILLISECOND, 0); - START_TIME = new Timestamp(startCal.getTimeInMillis()); - } - - public static final Timestamp END_TIME; - - static - { - Calendar endCal = Calendar.getInstance(); - endCal.set(2010, 2, 1, 0, 0, 0); - endCal.set(Calendar.MILLISECOND, 0); - END_TIME = new Timestamp(endCal.getTimeInMillis()); - } - - public static final Number INCLUSIVE = 1; - public static final boolean TRIM = true; - public static final Timestamp[] TRANSACTION_TIME = new Timestamp[1]; - public static final String STORE_RULE = "DELETE INSERT"; - public static final boolean OVERRIDE_PROTECTION = true; - public static final int COUNT = 500; - public static final long[] TIME_ARRAY; - - static - { - TIME_ARRAY = new long[COUNT]; - Calendar cal = Calendar.getInstance(); - cal.set(2010, 1, 2, 0, 0, 0); - cal.set(Calendar.MILLISECOND, 0); - for(int i = 0; i < COUNT; i++) - { - TIME_ARRAY[i] = cal.getTimeInMillis(); - cal.add(Calendar.MINUTE, 5); - } - } - - public static final double[] VALUE_ARRAY; - - static - { - VALUE_ARRAY = new double[COUNT]; - for(int i = 0; i < COUNT; i++) - { - VALUE_ARRAY[i] = COUNT + i * 1.2; - } - } - - public static final int[] QUALITY_ARRAY; - - static - { - QUALITY_ARRAY = new int[COUNT]; - Calendar cal = Calendar.getInstance(); - cal.set(2010, 1, 2, 0, 0, 0); - for(int i = 0; i < COUNT; i++) - { - QUALITY_ARRAY[i] = 3; - } - } - - - @Test - void testCreateEmpty() throws Exception - { - - String officeId = "LRL"; - try(Connection connection = getConnection()) - { - DSLContext lrl = getDslContext(connection, officeId); - TimeSeriesDao dao = new TimeSeriesDaoImpl(lrl); - - // String tsId858 = "RYAN3.Stage.Inst.5Minutes.0.ZSTORE_TS_TEST858"; - // BigDecimal tsCode = retrieveTsCode(connection, tsId858); - - String tsId = "RYAN3.Stage.Inst.5Minutes.0.ZSTORE_TS_TEST" + Calendar.getInstance().get( - Calendar.MILLISECOND); - // Do I need to somehow check whether the location exists? Its not going to exist if I add the millis to it... - if(!locationExists(connection, "RYAN3")) - { - storeLocation(connection, officeId, "RYAN3"); - } - - ZonedDateTime start = ZonedDateTime.parse("2021-06-21T08:00:00-07:00[PST8PDT]"); - ZonedDateTime end = ZonedDateTime.parse("2021-06-22T08:00:00-07:00[PST8PDT]"); - TimeSeries ts = new TimeSeries(null, -1, 0, tsId, officeId, start, end, null, Duration.ZERO); - dao.create(ts); - } - - - } - - @Test - void testCreateWithData() throws Exception - { - - String officeId = "LRL"; - try(Connection connection = getConnection()) - { - DSLContext lrl = getDslContext(connection, officeId); - TimeSeriesDao dao = new TimeSeriesDaoImpl(lrl); - - String tsId = TIME_SERIES_ID; - // Do I need to somehow check whether the location exists? Its not going to exist if I add the millis to it... - if(!locationExists(connection, "RYAN3")) - { - storeLocation(connection, officeId, "RYAN3"); - } - - ZonedDateTime start = ZonedDateTime.parse("2021-06-21T08:00:00-07:00[PST8PDT]"); - ZonedDateTime end = ZonedDateTime.parse("2021-06-21T09:00:00-07:00[PST8PDT]"); - - long diff = end.toEpochSecond() - start.toEpochSecond(); - assertEquals(3600, diff); // just to make sure I've got the date parsing thing right. - - int minutes = 15; - int count = 60 / 15; // do I need a +1? ie should this be 12 or 13? - // Also, should end be the last point or the next interval? - - TimeSeries ts = new TimeSeries(null, -1, 0, tsId, - officeId, start, end, "m", Duration.ofMinutes(minutes), null, - null, null, null, null); - - ZonedDateTime next = start; - for(int i = 0; i < count; i++) - { - Timestamp dateTime = Timestamp.valueOf(next.toLocalDateTime()); - ts.addValue(dateTime, (double) i, 0); - next = next.plus(minutes, ChronoUnit.MINUTES); - } - - dao.create(ts); - } - - - } - - - private boolean locationExists(Connection connection, String locId) - { - Integer count = 0; - - Record1 record = DSL.using(connection).selectCount().from(AV_LOC.AV_LOC).where( - AV_LOC.AV_LOC.LOCATION_ID.eq(locId)).fetchOptional().orElse(null); - if(record != null) - { - count = record.value1(); - } - return count > 0; - } - - private void storeLocation(Connection connection, String officeId, String locationId) - { - CWMS_LOC_PACKAGE.call_STORE_LOCATION(getDslContext(connection, officeId).configuration(), locationId, - null, null, null, null, null, - null, null, locationId, null, null, - "PST", null, null, null, null, officeId); - } - - @Test - void testTimeSeriesStoreRetrieve() throws Exception - { - Connection connection = getConnection(); - - createTs(connection); - String officeId = "LRL"; - String timeSeriesDesc = TIME_SERIES_ID; - String units = UNITS; - int count = COUNT; - String storeRule = STORE_RULE; - boolean overrideProtection = OVERRIDE_PROTECTION; - Timestamp versionDate = null; - - long[] timeArray = new long[]{START_TIME.getTime()}; - double[] valueArray = new double[]{9999999.0}; - int[] qualityArray = new int[]{0}; - LOGGER.info("Office Id: " + officeId); - LOGGER.info("Time Series ID: " + TIME_SERIES_ID); - LOGGER.info("Storing: " + valueArray[0] + " at " + new Date(timeArray[0])); - NUMBER_ARRAY times = new NUMBER_ARRAY(); - DOUBLE_ARRAY values = new DOUBLE_ARRAY(); - NUMBER_ARRAY qualities = new NUMBER_ARRAY(); - for (int i = 0; i < count; i++) { - times.put(i, BigDecimal.valueOf(timeArray[i])); - values.put(i, valueArray[i]); - qualities.put(i, BigDecimal.valueOf(qualityArray[i])); - } - - CWMS_TS_PACKAGE.call_STORE_TS__3(getDslContext(connection, officeId).configuration(), timeSeriesDesc, units, - times, values, qualities, storeRule, overrideProtection ? "T" : "F", versionDate, officeId, "F"); - LOGGER.log(Level.INFO, "Test time series stored."); - RETRIEVE_TS_2 - result = CWMS_TS_PACKAGE.call_RETRIEVE_TS_2(getDslContext(connection, officeId).configuration(), UNITS, - officeId, TIME_SERIES_ID, START_TIME, END_TIME, null, 0, 1, VERSION_DATE, 1); - assertFalse(result.getP_AT_TSV_RC().isEmpty()); - } - - private void createTs(Connection connection) throws SQLException - { - String timeSeriesDesc = TIME_SERIES_ID; - String officeId = "LRL"; - try - { - storeLocation(connection, officeId, LOC_ID); - - CWMS_TS_PACKAGE.call_CREATE_TS_CODE(getDslContext(connection, officeId).configuration(), timeSeriesDesc, - 0, 0, 0, "F", "T", "F", officeId); - connection.commit(); - } - catch(Exception e) - { - LOGGER.log(Level.CONFIG, "Unable to create TimeSeries: " + e.getMessage()); - } - } - - @Test - void testVersion() throws SQLException - { - try(Connection connection = getConnection()) - { - Result results = DSL.using(connection).selectFrom(AV_DB_CHANGE_LOG.AV_DB_CHANGE_LOG).fetch(); - - for (usace.cwms.db.jooq.codegen.tables.records.AV_DB_CHANGE_LOG rec : results) { - String title = rec.getTITLE(); - String application = rec.getAPPLICATION(); - String description = rec.getDESCRIPTION(); - String version = rec.getVERSION(); - assertFalse(title.isEmpty()); - assertFalse(application.isEmpty()); - assertFalse(description.isEmpty()); - assertFalse(version.isEmpty()); - } - } - } +public class TimeSeriesDaoTest { + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); + + public static final String LOC_ID = "RYAN3"; + public static final String TIME_SERIES_ID = LOC_ID + ".Stage.Inst.5Minutes.0.ZSTORE_TS_TEST" + Calendar.getInstance().get( + Calendar.MILLISECOND); + + public static final String UNITS = "m"; + public static final Timestamp VERSION_DATE = null; + + public static final Timestamp START_TIME; + + static { + Calendar startCal = Calendar.getInstance(); + startCal.set(2010, 1, 1, 0, 0, 0); + startCal.set(Calendar.MILLISECOND, 0); + START_TIME = new Timestamp(startCal.getTimeInMillis()); + } + + public static final Timestamp END_TIME; + + static { + Calendar endCal = Calendar.getInstance(); + endCal.set(2010, 2, 1, 0, 0, 0); + endCal.set(Calendar.MILLISECOND, 0); + END_TIME = new Timestamp(endCal.getTimeInMillis()); + } + + public static final Number INCLUSIVE = 1; + public static final boolean TRIM = true; + public static final Timestamp[] TRANSACTION_TIME = new Timestamp[1]; + public static final String STORE_RULE = "DELETE INSERT"; + public static final boolean OVERRIDE_PROTECTION = true; + public static final int COUNT = 500; + public static final long[] TIME_ARRAY; + + static { + TIME_ARRAY = new long[COUNT]; + Calendar cal = Calendar.getInstance(); + cal.set(2010, 1, 2, 0, 0, 0); + cal.set(Calendar.MILLISECOND, 0); + for (int i = 0; i < COUNT; i++) { + TIME_ARRAY[i] = cal.getTimeInMillis(); + cal.add(Calendar.MINUTE, 5); + } + } + + public static final double[] VALUE_ARRAY; + + static { + VALUE_ARRAY = new double[COUNT]; + for (int i = 0; i < COUNT; i++) { + VALUE_ARRAY[i] = COUNT + i * 1.2; + } + } + + public static final int[] QUALITY_ARRAY; + + static { + QUALITY_ARRAY = new int[COUNT]; + Calendar cal = Calendar.getInstance(); + cal.set(2010, 1, 2, 0, 0, 0); + for (int i = 0; i < COUNT; i++) { + QUALITY_ARRAY[i] = 3; + } + } + + + @Test + void testCreateEmpty() throws Exception { + + String officeId = "LRL"; + try (Connection connection = getConnection()) { + DSLContext lrl = getDslContext(connection, officeId); + TimeSeriesDao dao = new TimeSeriesDaoImpl(lrl); + + // String tsId858 = "RYAN3.Stage.Inst.5Minutes.0.ZSTORE_TS_TEST858"; + // BigDecimal tsCode = retrieveTsCode(connection, tsId858); + + String tsId = "RYAN3.Stage.Inst.5Minutes.0.ZSTORE_TS_TEST" + Calendar.getInstance().get( + Calendar.MILLISECOND); + // Do I need to somehow check whether the location exists? Its not going to exist if I add the millis to it... + if (!locationExists(connection, "RYAN3")) { + storeLocation(connection, officeId, "RYAN3"); + } + + ZonedDateTime start = ZonedDateTime.parse("2021-06-21T08:00:00-07:00[PST8PDT]"); + ZonedDateTime end = ZonedDateTime.parse("2021-06-22T08:00:00-07:00[PST8PDT]"); + TimeSeries ts = new TimeSeries(null, -1, 0, tsId, officeId, start, end, null, Duration.ZERO); + dao.create(ts); + } + + + } + + @Test + void testCreateWithData() throws Exception { + + String officeId = "LRL"; + try (Connection connection = getConnection()) { + DSLContext lrl = getDslContext(connection, officeId); + TimeSeriesDao dao = new TimeSeriesDaoImpl(lrl); + + String tsId = TIME_SERIES_ID; + // Do I need to somehow check whether the location exists? Its not going to exist if I add the millis to it... + if (!locationExists(connection, "RYAN3")) { + storeLocation(connection, officeId, "RYAN3"); + } + + ZonedDateTime start = ZonedDateTime.parse("2021-06-21T08:00:00-07:00[PST8PDT]"); + ZonedDateTime end = ZonedDateTime.parse("2021-06-21T09:00:00-07:00[PST8PDT]"); + + long diff = end.toEpochSecond() - start.toEpochSecond(); + assertEquals(3600, diff); // just to make sure I've got the date parsing thing right. + + int minutes = 15; + int count = 60 / 15; // do I need a +1? ie should this be 12 or 13? + // Also, should end be the last point or the next interval? + + TimeSeries ts = new TimeSeries(null, -1, 0, tsId, + officeId, start, end, "m", Duration.ofMinutes(minutes), null, + null, null, null, null); + + ZonedDateTime next = start; + for (int i = 0; i < count; i++) { + Timestamp dateTime = Timestamp.valueOf(next.toLocalDateTime()); + ts.addValue(dateTime, (double) i, 0); + next = next.plus(minutes, ChronoUnit.MINUTES); + } + + dao.create(ts); + } + + + } + + + private boolean locationExists(Connection connection, String locId) { + Integer count = 0; + + Record1 record = DSL.using(connection).selectCount().from(AV_LOC.AV_LOC).where( + AV_LOC.AV_LOC.LOCATION_ID.eq(locId)).fetchOptional().orElse(null); + if (record != null) { + count = record.value1(); + } + return count > 0; + } + + private void storeLocation(Connection connection, String officeId, String locationId) { + CWMS_LOC_PACKAGE.call_STORE_LOCATION(getDslContext(connection, officeId).configuration(), locationId, + null, null, null, null, null, + null, null, locationId, null, null, + "PST", null, null, null, null, officeId); + } + + @Test + void testTimeSeriesStoreRetrieve() throws Exception { + Connection connection = getConnection(); + + createTs(connection); + String officeId = "LRL"; + String timeSeriesDesc = TIME_SERIES_ID; + String units = UNITS; + int count = COUNT; + String storeRule = STORE_RULE; + boolean overrideProtection = OVERRIDE_PROTECTION; + Timestamp versionDate = null; + + long[] timeArray = new long[]{START_TIME.getTime()}; + double[] valueArray = new double[]{9999999.0}; + int[] qualityArray = new int[]{0}; + LOGGER.atInfo().log("Office Id: %s", officeId); + LOGGER.atInfo().log("Time Series ID: %s", TIME_SERIES_ID); + LOGGER.atInfo().log("Storing: %s at %s", valueArray[0], new Date(timeArray[0])); + NUMBER_ARRAY times = new NUMBER_ARRAY(); + DOUBLE_ARRAY values = new DOUBLE_ARRAY(); + NUMBER_ARRAY qualities = new NUMBER_ARRAY(); + for (int i = 0; i < count; i++) { + times.put(i, BigDecimal.valueOf(timeArray[i])); + values.put(i, valueArray[i]); + qualities.put(i, BigDecimal.valueOf(qualityArray[i])); + } + + CWMS_TS_PACKAGE.call_STORE_TS__3(getDslContext(connection, officeId).configuration(), timeSeriesDesc, units, + times, values, qualities, storeRule, overrideProtection ? "T" : "F", versionDate, officeId, "F"); + LOGGER.atInfo().log("Test time series stored."); + RETRIEVE_TS_2 + result = CWMS_TS_PACKAGE.call_RETRIEVE_TS_2(getDslContext(connection, officeId).configuration(), UNITS, + officeId, TIME_SERIES_ID, START_TIME, END_TIME, null, 0, 1, VERSION_DATE, 1); + assertFalse(result.getP_AT_TSV_RC().isEmpty()); + } + + private void createTs(Connection connection) throws SQLException { + String timeSeriesDesc = TIME_SERIES_ID; + String officeId = "LRL"; + try { + storeLocation(connection, officeId, LOC_ID); + + CWMS_TS_PACKAGE.call_CREATE_TS_CODE(getDslContext(connection, officeId).configuration(), timeSeriesDesc, + 0, 0, 0, "F", "T", "F", officeId); + connection.commit(); + } catch (Exception e) { + LOGGER.atConfig().log("Unable to create TimeSeries: %s", e.getMessage()); + } + } + + @Test + void testVersion() throws SQLException { + try (Connection connection = getConnection()) { + Result results = DSL.using(connection).selectFrom(AV_DB_CHANGE_LOG.AV_DB_CHANGE_LOG).fetch(); + + for (usace.cwms.db.jooq.codegen.tables.records.AV_DB_CHANGE_LOG rec : results) { + String title = rec.getTITLE(); + String application = rec.getAPPLICATION(); + String description = rec.getDESCRIPTION(); + String version = rec.getVERSION(); + assertFalse(title.isEmpty()); + assertFalse(application.isEmpty()); + assertFalse(description.isEmpty()); + assertFalse(version.isEmpty()); + } + } + } } \ No newline at end of file diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dao/location/kind/LockDaoIT.java b/cwms-data-api/src/test/java/cwms/cda/data/dao/location/kind/LockDaoIT.java index 18983ef9f..d8014393a 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dao/location/kind/LockDaoIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dao/location/kind/LockDaoIT.java @@ -49,8 +49,7 @@ import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import mil.army.usace.hec.test.database.CwmsDatabaseContainer; import org.jooq.DSLContext; import org.junit.jupiter.api.AfterAll; @@ -68,7 +67,7 @@ final class LockDaoIT extends ProjectStructureIT { private static final Location LOCK_LOC1 = buildProjectStructureLocation("LOCK_LOC1_IT", LOCK_KIND); private static final Location LOCK_LOC2 = buildProjectStructureLocation("LOCK_LOC2_IT", LOCK_KIND); private static final Location LOCK_LOC3 = buildProjectStructureLocation("LOCK_LOC3_IT", LOCK_KIND); - private static final Logger LOGGER = Logger.getLogger(LockDaoIT.class.getName()); + private static final FluentLogger LOGGER = FluentLogger.forEnclosingClass(); private List locksToCleanup = new ArrayList<>(); private List locationLevelsToCleanup = new ArrayList<>(); @@ -102,32 +101,32 @@ void tearDown() throws Exception { locationsDao.deleteLocation(LOCK_LOC1.getName(), OFFICE_ID, true); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, "Error deleting location - location does not exist", ex); + LOGGER.atConfig().withCause(ex).log("Error deleting location - location does not exist"); } try { locationsDao.deleteLocation(LOCK_LOC2.getName(), OFFICE_ID, true); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, "Error deleting location - location does not exist", ex); + LOGGER.atConfig().withCause(ex).log("Error deleting location - location does not exist"); } try { locationsDao.deleteLocation(LOCK_LOC3.getName(), OFFICE_ID, true); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, "Error deleting location - location does not exist", ex); + LOGGER.atConfig().withCause(ex).log("Error deleting location - location does not exist"); } try{ locationsDao.deleteLocation(LOCK_LOC1.getName() + "New", OFFICE_ID, true); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, "Error deleting location - location does not exist", ex); + LOGGER.atConfig().withCause(ex).log("Error deleting location - location does not exist"); } for (CwmsId lock : locksToCleanup) { try { lockDao.deleteLock(lock, DeleteRule.DELETE_ALL); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, "Error deleting lock - does not exist", ex); + LOGGER.atConfig().withCause(ex).log("Error deleting lock - does not exist"); } } locksToCleanup.clear(); @@ -135,7 +134,7 @@ void tearDown() throws Exception { try { locationLevelsDao.deleteLocationLevel(locationLevel.getLocationLevelId(), locationLevel.getLevelDate(), locationLevel.getOfficeId(), true); } catch (NotFoundException ex) { - LOGGER.log(Level.CONFIG, "Error deleting location level - does not exist", ex); + LOGGER.atConfig().withCause(ex).log("Error deleting location level - does not exist"); } } locationLevelsToCleanup.clear(); @@ -157,7 +156,7 @@ void cleanup() throws Exception lockDao.deleteLock(lock, DeleteRule.DELETE_ALL); } catch (NotFoundException ex) { /* only an error within the tests below. */ - LOGGER.log(Level.CONFIG, "Error deleting lock - does not exist", ex); + LOGGER.atConfig().withCause(ex).log("Error deleting lock - does not exist"); } } locksToCleanup.clear(); @@ -165,7 +164,7 @@ void cleanup() throws Exception try { locationLevelsDao.deleteLocationLevel(locationLevel.getLocationLevelId(), locationLevel.getLevelDate(), locationLevel.getOfficeId(), true); } catch (NotFoundException ex) { - LOGGER.log(Level.CONFIG, "Error deleting location level - does not exist", ex); + LOGGER.atConfig().withCause(ex).log("Error deleting location level - does not exist"); } } locationLevelsToCleanup.clear(); diff --git a/cwms-data-api/src/test/java/cwms/cda/data/dao/timeseriesprofile/TimeSeriesProfileInstanceDaoIT.java b/cwms-data-api/src/test/java/cwms/cda/data/dao/timeseriesprofile/TimeSeriesProfileInstanceDaoIT.java index a16d3a970..fd1081cc4 100644 --- a/cwms-data-api/src/test/java/cwms/cda/data/dao/timeseriesprofile/TimeSeriesProfileInstanceDaoIT.java +++ b/cwms-data-api/src/test/java/cwms/cda/data/dao/timeseriesprofile/TimeSeriesProfileInstanceDaoIT.java @@ -34,8 +34,7 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import usace.cwms.db.jooq.codegen.packages.CWMS_TS_PACKAGE; import static cwms.cda.data.dao.DaoTest.getDslContext; @@ -43,7 +42,7 @@ @Tag("integration") class TimeSeriesProfileInstanceDaoIT extends DataApiTestIT { - private static final Logger logger = Logger.getLogger(TimeSeriesProfileInstanceDaoIT.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); @Test void testStoreTimeSeriesProfileInstanceWithDataBlock() throws SQLException { @@ -897,7 +896,7 @@ private TimeSeriesProfileInstance retrieveTimeSeriesProfileInstance(String offic } catch(cwms.cda.api.errors.NotFoundException ex) { - logger.log(Level.SEVERE, "TimeSeriesProfileInstance not found"); + logger.atSevere().withCause(ex).log("TimeSeriesProfileInstance not found"); // return null for not found } }, CwmsDataApiSetupCallback.getWebUser()); diff --git a/cwms-data-api/src/test/java/fixtures/KeyCloakExtension.java b/cwms-data-api/src/test/java/fixtures/KeyCloakExtension.java index e77d1dd71..293c4848f 100644 --- a/cwms-data-api/src/test/java/fixtures/KeyCloakExtension.java +++ b/cwms-data-api/src/test/java/fixtures/KeyCloakExtension.java @@ -13,8 +13,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.extension.BeforeAllCallback; @@ -36,7 +35,7 @@ * Sets up a KeyCloak instance to use for testing. */ public final class KeyCloakExtension implements BeforeAllCallback { - private static final Logger logger = Logger.getLogger(KeyCloakExtension.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static final String WELL_KNOWN = "realms/cwms/.well-known/openid-configuration"; private static final ObjectMapper mapper = new ObjectMapper(); private static final GenericContainer kcc = new GenericContainer<>("quay.io/keycloak/keycloak:19.0.1") @@ -49,7 +48,7 @@ public final class KeyCloakExtension implements BeforeAllCallback { .withReuse(false) .withLogConsumer(frame -> { - logger.info(frame.getUtf8String()); + logger.atInfo().log(frame.getUtf8String()); }) ; @@ -92,7 +91,7 @@ static void setup() throws IOException { issuer = oidcConfig.get("issuer").asText(); codeUrl = oidcConfig.get("authorization_endpoint").asText(); tokenUrl = oidcConfig.get("token_endpoint").asText(); - logger.fine(response::asPrettyString); + logger.atFine().log(response.asPrettyString()); } @Override @@ -144,11 +143,11 @@ public static Optional tokenForUser(String username, String password) { .when() .post(new URL(getTokenUrl())); - logger.fine(response::asPrettyString); + logger.atFine().log(response.asPrettyString()); JsonNode tokenInfo = mapper.readTree(response.asString()); return Optional.of(tokenInfo.get("access_token").asText()); } catch (JsonProcessingException | MalformedURLException ex) { - logger.log(Level.WARNING, ex, () -> "Unable to retrieve token for user " + username); + logger.atWarning().withCause(ex).log("Unable to retrieve token for user %s", username); return Optional.empty(); } } diff --git a/cwms-data-api/src/test/java/helpers/TsRandomSampler.java b/cwms-data-api/src/test/java/helpers/TsRandomSampler.java index c8d1d97d5..0a0647cf2 100644 --- a/cwms-data-api/src/test/java/helpers/TsRandomSampler.java +++ b/cwms-data-api/src/test/java/helpers/TsRandomSampler.java @@ -10,8 +10,7 @@ import java.sql.Types; import java.util.ArrayList; import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; +import com.google.common.flogger.FluentLogger; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; @@ -23,7 +22,7 @@ */ public class TsRandomSampler { - private static final Logger logger = Logger.getLogger(TsRandomSampler.class.getName()); + private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private static CSVFormat TS_SAMPLE_FORMAT = CSVFormat.Builder .create(CSVFormat.DEFAULT) .setNullString("null") @@ -81,7 +80,7 @@ public static void main(String[] args) throws IOException { } } } catch (SQLException e) { - logger.log(Level.SEVERE, "failed to sample data", e); + logger.atSevere().withCause(e).log("failed to sample data"); } } @@ -286,8 +285,7 @@ public static void save_to_db(List samples, Connection c) { } catch (SQLException e) { - logger.log(Level.WARNING, "failed to save timeseries and location base data at " - + "element " + lastSample, e); + logger.atWarning().withCause(e).log("failed to save timeseries and location base data at element %s", lastSample); } catch (IOException e) { throw new RuntimeException("Unable to load creation query", e); } From 2180e07e81d8c96d1c53b3e005ba0fc87e2ba45c Mon Sep 17 00:00:00 2001 From: rma-rripken <89810919+rma-rripken@users.noreply.github.com> Date: Wed, 17 Dec 2025 13:34:24 -0800 Subject: [PATCH 4/4] Fixing merge --- .../src/main/java/cwms/cda/api/TimeSeriesController.java | 2 +- cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesController.java b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesController.java index e72020a9f..45e463879 100644 --- a/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesController.java +++ b/cwms-data-api/src/main/java/cwms/cda/api/TimeSeriesController.java @@ -542,7 +542,7 @@ public void getAll(@NotNull Context ctx) { requestResultSize.update(results.length()); } catch (NotFoundException e) { CdaError re = new CdaError("Not found."); - logger.log(Level.WARNING, re.toString(), e); + logger.atSevere().withCause(e).log("%s", re.toString()); ctx.status(HttpServletResponse.SC_NOT_FOUND); ctx.json(re); } catch (IllegalArgumentException ex) { diff --git a/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java b/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java index 66f40c9bf..fce14d29d 100644 --- a/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java +++ b/cwms-data-api/src/main/java/cwms/cda/data/dao/UserDao.java @@ -8,6 +8,7 @@ import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -51,7 +52,7 @@ public UserDao(DSLContext dsl) { @Override public Optional getByUniqueName(String uniqueName, String cac_role) { - return Optional.of(dsl.connectionResult(c -> { + return Optional.ofNullable(dsl.connectionResult(c -> { AuthDao.setSessionForAuthCheck(c); try (PreparedStatement getUser = c.prepareStatement(GET_USER)) { getUser.setString(1, uniqueName); @@ -77,7 +78,7 @@ public Optional getByUniqueName(String uniqueName, String cac_role) { logger.atInfo().log("Building user object."); return new User(userName, principalName, email, cac_role != null, roles); } else { - return (User)null; + return null; } } }