From 3b74c247f5c8b27cd995139d278476ba97a0f4f0 Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 17:47:53 -0400 Subject: [PATCH 01/15] refactor: "extract class" type refactor to maintain responsiblity --- .../jhipster/web/util/LinkHeaderUtil.java | 40 +++++++++++++++++++ .../jhipster/web/util/PaginationUtil.java | 37 +++-------------- 2 files changed, 45 insertions(+), 32 deletions(-) create mode 100644 jhipster-framework/src/main/java/tech/jhipster/web/util/LinkHeaderUtil.java diff --git a/jhipster-framework/src/main/java/tech/jhipster/web/util/LinkHeaderUtil.java b/jhipster-framework/src/main/java/tech/jhipster/web/util/LinkHeaderUtil.java new file mode 100644 index 00000000..71fbf06f --- /dev/null +++ b/jhipster-framework/src/main/java/tech/jhipster/web/util/LinkHeaderUtil.java @@ -0,0 +1,40 @@ +package tech.jhipster.web.util; + +import java.text.MessageFormat; +import org.springframework.data.domain.Page; +import org.springframework.web.util.UriComponentsBuilder; + +public class LinkHeaderUtil { + + private static final String HEADER_LINK_FORMAT = "<{0}>; rel=\"{1}\""; + + public String prepareLinkHeaders(UriComponentsBuilder uriBuilder, Page page) { + int pageNumber = page.getNumber(); + int pageSize = page.getSize(); + StringBuilder link = new StringBuilder(); + if (pageNumber < page.getTotalPages() - 1) { + link.append(prepareLink(uriBuilder, pageNumber + 1, pageSize, "next")).append(","); + } + if (pageNumber > 0) { + link.append(prepareLink(uriBuilder, pageNumber - 1, pageSize, "prev")).append(","); + } + link + .append(prepareLink(uriBuilder, page.getTotalPages() - 1, pageSize, "last")) + .append(",") + .append(prepareLink(uriBuilder, 0, pageSize, "first")); + return link.toString(); + } + + private static String prepareLink(UriComponentsBuilder uriBuilder, int pageNumber, int pageSize, String relType) { + return MessageFormat.format(HEADER_LINK_FORMAT, preparePageUri(uriBuilder, pageNumber, pageSize), relType); + } + + private static String preparePageUri(UriComponentsBuilder uriBuilder, int pageNumber, int pageSize) { + return uriBuilder + .replaceQueryParam("page", Integer.toString(pageNumber)) + .replaceQueryParam("size", Integer.toString(pageSize)) + .toUriString() + .replace(",", "%2C") + .replace(";", "%3B"); + } +} diff --git a/jhipster-framework/src/main/java/tech/jhipster/web/util/PaginationUtil.java b/jhipster-framework/src/main/java/tech/jhipster/web/util/PaginationUtil.java index bc199536..f7a59f40 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/web/util/PaginationUtil.java +++ b/jhipster-framework/src/main/java/tech/jhipster/web/util/PaginationUtil.java @@ -1,3 +1,4 @@ +// new code /* * Copyright 2016-2023 the original author or authors from the JHipster project. * @@ -22,8 +23,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.web.util.UriComponentsBuilder; -import java.text.MessageFormat; - /** * Utility class for handling pagination. * @@ -34,10 +33,10 @@ public final class PaginationUtil { private static final String HEADER_X_TOTAL_COUNT = "X-Total-Count"; - private static final String HEADER_LINK_FORMAT = "<{0}>; rel=\"{1}\""; - private PaginationUtil() { - } + private static LinkHeaderUtil linkHeaderUtil = new LinkHeaderUtil(); + + private PaginationUtil() {} /** * Generate pagination headers for a Spring Data {@link org.springframework.data.domain.Page} object. @@ -50,33 +49,7 @@ private PaginationUtil() { public static HttpHeaders generatePaginationHttpHeaders(UriComponentsBuilder uriBuilder, Page page) { HttpHeaders headers = new HttpHeaders(); headers.add(HEADER_X_TOTAL_COUNT, Long.toString(page.getTotalElements())); - int pageNumber = page.getNumber(); - int pageSize = page.getSize(); - StringBuilder link = new StringBuilder(); - if (pageNumber < page.getTotalPages() - 1) { - link.append(prepareLink(uriBuilder, pageNumber + 1, pageSize, "next")) - .append(","); - } - if (pageNumber > 0) { - link.append(prepareLink(uriBuilder, pageNumber - 1, pageSize, "prev")) - .append(","); - } - link.append(prepareLink(uriBuilder, page.getTotalPages() - 1, pageSize, "last")) - .append(",") - .append(prepareLink(uriBuilder, 0, pageSize, "first")); - headers.add(HttpHeaders.LINK, link.toString()); + headers.add(HttpHeaders.LINK, linkHeaderUtil.prepareLinkHeaders(uriBuilder, page)); return headers; } - - private static String prepareLink(UriComponentsBuilder uriBuilder, int pageNumber, int pageSize, String relType) { - return MessageFormat.format(HEADER_LINK_FORMAT, preparePageUri(uriBuilder, pageNumber, pageSize), relType); - } - - private static String preparePageUri(UriComponentsBuilder uriBuilder, int pageNumber, int pageSize) { - return uriBuilder.replaceQueryParam("page", Integer.toString(pageNumber)) - .replaceQueryParam("size", Integer.toString(pageSize)) - .toUriString() - .replace(",", "%2C") - .replace(";", "%3B"); - } } From 2373e7a7dc80d855d7017f64ceda1ffd8e03bbee Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 17:51:13 -0400 Subject: [PATCH 02/15] sonar fix: https://sonarcloud.io/project/issues?resolved=false&types=CODE_SMELL&id=jhipster-framework&open=AYMy8ftoR6xvCwI5pG55 --- .../async/ExceptionHandlingAsyncTaskExecutor.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java b/jhipster-framework/src/main/java/tech/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java index cb1d4dea..e7dcef34 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java +++ b/jhipster-framework/src/main/java/tech/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java @@ -19,20 +19,18 @@ package tech.jhipster.async; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.task.AsyncTaskExecutor; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; - /** *

ExceptionHandlingAsyncTaskExecutor class.

*/ -public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor, - InitializingBean, DisposableBean { +public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor, InitializingBean, DisposableBean { static final String EXCEPTION_MESSAGE = "Caught async exception"; @@ -57,7 +55,7 @@ public void execute(Runnable task) { /** {@inheritDoc} */ @Override - @Deprecated + @Deprecated(since = "version", forRemoval = true) public void execute(Runnable task, long startTimeout) { executor.execute(createWrappedRunnable(task), startTimeout); } From e8a85b37759bbd6c3ff8674b1f1862cf1de6d539 Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 17:56:39 -0400 Subject: [PATCH 03/15] refactor: "rename variable" smell removal for alert and message in HeaderUtil --- .../tech/jhipster/web/util/HeaderUtil.java | 80 ++++++++++++------- .../jhipster/web/util/HeaderUtilTest.java | 8 +- 2 files changed, 55 insertions(+), 33 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/web/util/HeaderUtil.java b/jhipster-framework/src/main/java/tech/jhipster/web/util/HeaderUtil.java index 29b66c1f..8b2c07f9 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/web/util/HeaderUtil.java +++ b/jhipster-framework/src/main/java/tech/jhipster/web/util/HeaderUtil.java @@ -1,12 +1,11 @@ package tech.jhipster.web.util; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpHeaders; - import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; /** * Utility class for HTTP headers creation. @@ -15,22 +14,21 @@ public final class HeaderUtil { private static final Logger log = LoggerFactory.getLogger(HeaderUtil.class); - private HeaderUtil() { - } + private HeaderUtil() {} /** *

createAlert.

* * @param applicationName a {@link java.lang.String} object. - * @param message a {@link java.lang.String} object. - * @param param a {@link java.lang.String} object. + * @param alertMessage a {@link java.lang.String} object. + * @param alertParam a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createAlert(String applicationName, String message, String param) { + public static HttpHeaders createAlertHeader(String applicationName, String alertMessage, String alertParam) { HttpHeaders headers = new HttpHeaders(); - headers.add("X-" + applicationName + "-alert", message); + headers.add("X-" + applicationName + "-alert", alertMessage); try { - headers.add("X-" + applicationName + "-params", URLEncoder.encode(param, StandardCharsets.UTF_8.toString())); + headers.add("X-" + applicationName + "-params", URLEncoder.encode(alertParam, StandardCharsets.UTF_8.toString())); } catch (UnsupportedEncodingException e) { // StandardCharsets are supported by every Java implementation so this exception will never happen } @@ -43,13 +41,19 @@ public static HttpHeaders createAlert(String applicationName, String message, St * @param applicationName a {@link java.lang.String} object. * @param enableTranslation a boolean. * @param entityName a {@link java.lang.String} object. - * @param param a {@link java.lang.String} object. + * @param entityIdentifier a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createEntityCreationAlert(String applicationName, boolean enableTranslation, String entityName, String param) { - String message = enableTranslation ? applicationName + "." + entityName + ".created" - : "A new " + entityName + " is created with identifier " + param; - return createAlert(applicationName, message, param); + public static HttpHeaders createEntityCreationAlert( + String applicationName, + boolean enableTranslation, + String entityName, + String entityIdentifier + ) { + String alertMessage = enableTranslation + ? applicationName + "." + entityName + ".created" + : "A new " + entityName + " is created with identifier " + entityIdentifier; + return createAlertHeader(applicationName, alertMessage, entityIdentifier); } /** @@ -58,13 +62,19 @@ public static HttpHeaders createEntityCreationAlert(String applicationName, bool * @param applicationName a {@link java.lang.String} object. * @param enableTranslation a boolean. * @param entityName a {@link java.lang.String} object. - * @param param a {@link java.lang.String} object. + * @param entityIdentifier a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createEntityUpdateAlert(String applicationName, boolean enableTranslation, String entityName, String param) { - String message = enableTranslation ? applicationName + "." + entityName + ".updated" - : "A " + entityName + " is updated with identifier " + param; - return createAlert(applicationName, message, param); + public static HttpHeaders createEntityUpdateAlert( + String applicationName, + boolean enableTranslation, + String entityName, + String entityIdentifier + ) { + String alertMessage = enableTranslation + ? applicationName + "." + entityName + ".updated" + : "A " + entityName + " is updated with identifier " + entityIdentifier; + return createAlertHeader(applicationName, alertMessage, entityIdentifier); } /** @@ -73,13 +83,19 @@ public static HttpHeaders createEntityUpdateAlert(String applicationName, boolea * @param applicationName a {@link java.lang.String} object. * @param enableTranslation a boolean. * @param entityName a {@link java.lang.String} object. - * @param param a {@link java.lang.String} object. + * @param entityIdentifier a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createEntityDeletionAlert(String applicationName, boolean enableTranslation, String entityName, String param) { - String message = enableTranslation ? applicationName + "." + entityName + ".deleted" - : "A " + entityName + " is deleted with identifier " + param; - return createAlert(applicationName, message, param); + public static HttpHeaders createEntityDeletionAlert( + String applicationName, + boolean enableTranslation, + String entityName, + String entityIdentifier + ) { + String alertMessage = enableTranslation + ? applicationName + "." + entityName + ".deleted" + : "A " + entityName + " is deleted with identifier " + entityIdentifier; + return createAlertHeader(applicationName, alertMessage, entityIdentifier); } /** @@ -92,13 +108,19 @@ public static HttpHeaders createEntityDeletionAlert(String applicationName, bool * @param defaultMessage a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createFailureAlert(String applicationName, boolean enableTranslation, String entityName, String errorKey, String defaultMessage) { + public static HttpHeaders createFailureAlert( + String applicationName, + boolean enableTranslation, + String entityName, + String errorKey, + String defaultMessage + ) { log.error("Entity processing failed, {}", defaultMessage); - String message = enableTranslation ? "error." + errorKey : defaultMessage; + String alertMessage = enableTranslation ? "error." + errorKey : defaultMessage; HttpHeaders headers = new HttpHeaders(); - headers.add("X-" + applicationName + "-error", message); + headers.add("X-" + applicationName + "-error", alertMessage); headers.add("X-" + applicationName + "-params", entityName); return headers; } diff --git a/jhipster-framework/src/test/java/tech/jhipster/web/util/HeaderUtilTest.java b/jhipster-framework/src/test/java/tech/jhipster/web/util/HeaderUtilTest.java index a0b3dc38..ea097120 100644 --- a/jhipster-framework/src/test/java/tech/jhipster/web/util/HeaderUtilTest.java +++ b/jhipster-framework/src/test/java/tech/jhipster/web/util/HeaderUtilTest.java @@ -1,18 +1,18 @@ package tech.jhipster.web.util; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; -import static org.assertj.core.api.Assertions.assertThat; - class HeaderUtilTest { @Test - void createAlert() { + void createAlertHeader() { String message = "any.message"; String param = "24"; - HttpHeaders headers = HeaderUtil.createAlert("myApp", message, param); + HttpHeaders headers = HeaderUtil.createAlertHeader("myApp", message, param); assertThat(headers.getFirst("X-myApp-alert")).isEqualTo(message); assertThat(headers.getFirst("X-myApp-params")).isEqualTo(param); } From 3bf804eb5f0ce1901bf0bb2886b22d0ad65f683b Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 17:58:27 -0400 Subject: [PATCH 04/15] sonar fix: https://sonarcloud.io/project/issues?fileUuids=AXWEj8X7uEAlCkyrserW&resolved=false&types=CODE_SMELL&id=jhipster-framework&open=AXDLQPyj7NPLvZRIY3yr --- .../config/cache/PrefixedSimpleKey.java | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedSimpleKey.java b/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedSimpleKey.java index 245b9802..31f3bca5 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedSimpleKey.java +++ b/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedSimpleKey.java @@ -1,10 +1,9 @@ package tech.jhipster.config.cache; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - import java.io.Serializable; import java.util.Arrays; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; /** *

PrefixedSimpleKey class.

@@ -12,7 +11,7 @@ public class PrefixedSimpleKey implements Serializable { private final String prefix; - private final Object[] params; + private transient Object[] params; private final String methodName; private int hashCode; @@ -30,6 +29,7 @@ public PrefixedSimpleKey(String prefix, String methodName, Object... elements) { this.methodName = methodName; params = new Object[elements.length]; System.arraycopy(elements, 0, params, 0, elements.length); + hashCode = prefix.hashCode(); hashCode = 31 * hashCode + methodName.hashCode(); hashCode = 31 * hashCode + Arrays.deepHashCode(params); @@ -38,10 +38,13 @@ public PrefixedSimpleKey(String prefix, String methodName, Object... elements) { /** {@inheritDoc} */ @Override public boolean equals(Object other) { - return (this == other || - (other instanceof PrefixedSimpleKey && prefix.equals(((PrefixedSimpleKey) other).prefix) && + return ( + this == other || + (other instanceof PrefixedSimpleKey && + prefix.equals(((PrefixedSimpleKey) other).prefix) && methodName.equals(((PrefixedSimpleKey) other).methodName) && - Arrays.deepEquals(params, ((PrefixedSimpleKey) other).params))); + Arrays.deepEquals(params, ((PrefixedSimpleKey) other).params)) + ); } /** {@inheritDoc} */ @@ -53,7 +56,6 @@ public final int hashCode() { /** {@inheritDoc} */ @Override public String toString() { - return prefix + " " + getClass().getSimpleName() + methodName + " [" + StringUtils.arrayToCommaDelimitedString( - params) + "]"; + return prefix + " " + getClass().getSimpleName() + methodName + " [" + StringUtils.arrayToCommaDelimitedString(params) + "]"; } } From 87b7d3016788d6bde2c1a2309cf939f088a3e43e Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 18:00:29 -0400 Subject: [PATCH 05/15] refactor: "pull up variable" refactor --- .../config/cache/PrefixedKeyGenerator.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedKeyGenerator.java b/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedKeyGenerator.java index 9992dd24..202514a2 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedKeyGenerator.java +++ b/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedKeyGenerator.java @@ -1,16 +1,15 @@ package tech.jhipster.config.cache; +import java.lang.reflect.Method; +import java.time.Instant; +import java.time.format.DateTimeFormatter; +import java.util.Objects; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.boot.info.BuildProperties; import org.springframework.boot.info.GitProperties; import org.springframework.cache.interceptor.KeyGenerator; -import java.lang.reflect.Method; -import java.time.Instant; -import java.time.format.DateTimeFormatter; -import java.util.Objects; - /** *

PrefixedKeyGenerator class.

*

@@ -29,6 +28,9 @@ public class PrefixedKeyGenerator implements KeyGenerator { private final String prefix; + private String shortCommitId = null; + private Instant time = null; + private String version = null; /** *

Constructor for PrefixedKeyGenerator.

@@ -37,7 +39,6 @@ public class PrefixedKeyGenerator implements KeyGenerator { * @param buildProperties a {@link org.springframework.boot.info.BuildProperties} object. */ public PrefixedKeyGenerator(GitProperties gitProperties, BuildProperties buildProperties) { - prefix = generatePrefix(gitProperties, buildProperties); } @@ -46,14 +47,10 @@ String getPrefix() { } private String generatePrefix(GitProperties gitProperties, BuildProperties buildProperties) { - - String shortCommitId = null; if (Objects.nonNull(gitProperties)) { shortCommitId = gitProperties.getShortCommitId(); } - Instant time = null; - String version = null; if (Objects.nonNull(buildProperties)) { time = buildProperties.getTime(); version = buildProperties.getVersion(); @@ -66,7 +63,6 @@ private String generatePrefix(GitProperties gitProperties, BuildProperties build return p.toString(); } - /** {@inheritDoc} */ @Override public Object generate(Object target, Method method, Object... params) { From b31b1f2fbc3959f176018b13a7593583d02eebdf Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 18:01:24 -0400 Subject: [PATCH 06/15] sonar fix: https://sonarcloud.io/project/issues?fileUuids=AXWEj8X6uEAlCkyrserI&resolved=false&types=CODE_SMELL&id=jhipster-framework&open=AW8i7R24FN2GgBTo8gHa --- .../config/h2/H2ConfigurationHelper.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/config/h2/H2ConfigurationHelper.java b/jhipster-framework/src/main/java/tech/jhipster/config/h2/H2ConfigurationHelper.java index d1b4a03f..c142c1bc 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/config/h2/H2ConfigurationHelper.java +++ b/jhipster-framework/src/main/java/tech/jhipster/config/h2/H2ConfigurationHelper.java @@ -34,6 +34,10 @@ */ public class H2ConfigurationHelper { + private H2ConfigurationHelper() { + throw new AssertionError("The class should not be instantiated"); + } + /** *

createServer.

* @@ -56,17 +60,13 @@ public static Object createServer(String port) throws SQLException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class serverClass = Class.forName("org.h2.tools.Server", true, loader); Method createServer = serverClass.getMethod("createTcpServer", String[].class); - return createServer.invoke(null, new Object[]{new String[]{"-tcp", "-tcpAllowOthers", "-tcpPort", port}}); - + return createServer.invoke(null, new Object[] { new String[] { "-tcp", "-tcpAllowOthers", "-tcpPort", port } }); } catch (ClassNotFoundException | LinkageError e) { throw new RuntimeException("Failed to load and initialize org.h2.tools.Server", e); - } catch (SecurityException | NoSuchMethodException e) { throw new RuntimeException("Failed to get method org.h2.tools.Server.createTcpServer()", e); - } catch (IllegalAccessException | IllegalArgumentException e) { throw new RuntimeException("Failed to invoke org.h2.tools.Server.createTcpServer()", e); - } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof SQLException) { @@ -99,10 +99,10 @@ static void initH2Console(String propertiesLocation) { Method createWebServer = serverClass.getMethod("createWebServer", String[].class); Method start = serverClass.getMethod("start"); - Object server = createWebServer.invoke(null, new Object[]{new String[]{"-properties", propertiesLocation}}); + Object server = createWebServer.invoke(null, new Object[] { new String[] { "-properties", propertiesLocation } }); start.invoke(server); - } catch (Exception e) { - throw new RuntimeException("Failed to start h2 webserver console", e); + } catch (Exception e) { + throw new RuntimeException("Failed to start h2 webserver console", e); } } @@ -123,10 +123,8 @@ public static void initH2Console(ServletContext servletContext) { h2ConsoleServlet.addMapping("/h2-console/*"); h2ConsoleServlet.setInitParameter("-properties", "src/main/resources/"); h2ConsoleServlet.setLoadOnStartup(1); - } catch (ClassNotFoundException | LinkageError | NoSuchMethodException | InvocationTargetException e) { throw new RuntimeException("Failed to load and initialize org.h2.server.web.JakartaWebServlet", e); - } catch (IllegalAccessException | InstantiationException e) { throw new RuntimeException("Failed to instantiate org.h2.server.web.JakartaWebServlet", e); } From 884538b6b869b41a1e517ecb2574a3821fdc6c40 Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 18:03:00 -0400 Subject: [PATCH 07/15] refactor: "decompose conditional" type refactoring for complex condition & introduced "explaining variable" --- .../liquibase/AsyncSpringLiquibase.java | 73 +++++++++++-------- 1 file changed, 42 insertions(+), 31 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/config/liquibase/AsyncSpringLiquibase.java b/jhipster-framework/src/main/java/tech/jhipster/config/liquibase/AsyncSpringLiquibase.java index 2a3a21a1..68fc8424 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/config/liquibase/AsyncSpringLiquibase.java +++ b/jhipster-framework/src/main/java/tech/jhipster/config/liquibase/AsyncSpringLiquibase.java @@ -18,6 +18,11 @@ */ package tech.jhipster.config.liquibase; +import static tech.jhipster.config.JHipsterConstants.*; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.concurrent.Executor; import liquibase.exception.LiquibaseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,12 +31,6 @@ import org.springframework.core.env.Profiles; import org.springframework.util.StopWatch; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.concurrent.Executor; - -import static tech.jhipster.config.JHipsterConstants.*; - /** * Specific liquibase.integration.spring.SpringLiquibase that will update the database asynchronously and close * DataSource if necessary.

By default, this asynchronous version only works when using the "dev" profile.

The standard @@ -46,15 +45,13 @@ public class AsyncSpringLiquibase extends DataSourceClosingSpringLiquibase { /** Constant DISABLED_MESSAGE="Liquibase is disabled" */ public static final String DISABLED_MESSAGE = "Liquibase is disabled"; /** Constant STARTING_ASYNC_MESSAGE="Starting Liquibase asynchronously, your"{trunked} */ - public static final String STARTING_ASYNC_MESSAGE = - "Starting Liquibase asynchronously, your database might not be ready at startup!"; + public static final String STARTING_ASYNC_MESSAGE = "Starting Liquibase asynchronously, your database might not be ready at startup!"; /** Constant STARTING_SYNC_MESSAGE="Starting Liquibase synchronously" */ public static final String STARTING_SYNC_MESSAGE = "Starting Liquibase synchronously"; /** Constant STARTED_MESSAGE="Liquibase has updated your database in "{trunked} */ public static final String STARTED_MESSAGE = "Liquibase has updated your database in {} ms"; /** Constant EXCEPTION_MESSAGE="Liquibase could not start correctly, yo"{trunked} */ - public static final String EXCEPTION_MESSAGE = "Liquibase could not start correctly, your database is NOT ready: " + - "{}"; + public static final String EXCEPTION_MESSAGE = "Liquibase could not start correctly, your database is NOT ready: " + "{}"; /** Constant SLOWNESS_THRESHOLD=5 */ public static final long SLOWNESS_THRESHOLD = 5; // seconds @@ -82,28 +79,41 @@ public AsyncSpringLiquibase(Executor executor, Environment env) { /** {@inheritDoc} */ @Override public void afterPropertiesSet() throws LiquibaseException { - if (!env.acceptsProfiles(Profiles.of(SPRING_PROFILE_NO_LIQUIBASE))) { - if (env.acceptsProfiles(Profiles.of(SPRING_PROFILE_DEVELOPMENT + "|" + SPRING_PROFILE_HEROKU))) { - // Prevent Thread Lock with spring-cloud-context GenericScope - // https://github.com/spring-cloud/spring-cloud-commons/commit/aaa7288bae3bb4d6fdbef1041691223238d77b7b#diff-afa0715eafc2b0154475fe672dab70e4R328 - try (Connection connection = getDataSource().getConnection()) { - executor.execute(() -> { - try { - logger.warn(STARTING_ASYNC_MESSAGE); - initDb(); - } catch (LiquibaseException e) { - logger.error(EXCEPTION_MESSAGE, e.getMessage(), e); - } - }); - } catch (SQLException e) { + if (isLiquibaseDisabled()) { + logger.debug(DISABLED_MESSAGE); + return; + } + + if (isAsyncProfileActive()) { + handleAsyncExecution(); + } else { + logger.debug(STARTING_SYNC_MESSAGE); + initDb(); + } + } + + private boolean isLiquibaseDisabled() { + return env.acceptsProfiles(Profiles.of(SPRING_PROFILE_NO_LIQUIBASE)); + } + + private boolean isAsyncProfileActive() { + return env.acceptsProfiles(Profiles.of(SPRING_PROFILE_DEVELOPMENT + "|" + SPRING_PROFILE_HEROKU)); + } + + private void handleAsyncExecution() { + // Prevent Thread Lock with spring-cloud-context GenericScope + // https://github.com/spring-cloud/spring-cloud-commons/commit/aaa7288bae3bb4d6fdbef1041691223238d77b7b#diff-afa0715eafc2b0154475fe672dab70e4R328 + try (Connection connection = getDataSource().getConnection()) { + executor.execute(() -> { + try { + logger.warn(STARTING_ASYNC_MESSAGE); + initDb(); + } catch (LiquibaseException e) { logger.error(EXCEPTION_MESSAGE, e.getMessage(), e); } - } else { - logger.debug(STARTING_SYNC_MESSAGE); - initDb(); - } - } else { - logger.debug(DISABLED_MESSAGE); + }); + } catch (SQLException e) { + logger.error(EXCEPTION_MESSAGE, e.getMessage(), e); } } @@ -118,7 +128,8 @@ protected void initDb() throws LiquibaseException { super.afterPropertiesSet(); watch.stop(); logger.debug(STARTED_MESSAGE, watch.getTotalTimeMillis()); - if (watch.getTotalTimeMillis() > SLOWNESS_THRESHOLD * 1000L) { + boolean isExecutionTimeLong = watch.getTotalTimeMillis() > SLOWNESS_THRESHOLD * 1000L; + if (isExecutionTimeLong) { logger.warn(SLOWNESS_MESSAGE, SLOWNESS_THRESHOLD); } } From c67d2179700517c794f974c44e25277124626a9c Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 18:04:17 -0400 Subject: [PATCH 08/15] refactor: "move method" refactor to club variable which are related to one another --- .../locale/AngularCookieLocaleResolver.java | 81 ++++++++++++------- 1 file changed, 51 insertions(+), 30 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/config/locale/AngularCookieLocaleResolver.java b/jhipster-framework/src/main/java/tech/jhipster/config/locale/AngularCookieLocaleResolver.java index 21ff862f..1e9b5fb4 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/config/locale/AngularCookieLocaleResolver.java +++ b/jhipster-framework/src/main/java/tech/jhipster/config/locale/AngularCookieLocaleResolver.java @@ -21,6 +21,9 @@ import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; +import java.util.Locale; +import java.util.TimeZone; +import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.i18n.LocaleContext; @@ -29,9 +32,6 @@ import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.util.WebUtils; -import java.util.Locale; -import java.util.TimeZone; - /** * Angular cookie saved the locale with a double quote (%22en%22). So the default * CookieLocaleResolver#StringUtils.parseLocaleString(localePart) @@ -85,41 +85,62 @@ public TimeZone getTimeZone() { } private void parseAngularCookieIfNecessary(HttpServletRequest request) { + LocaleAndTimeZone localeAndTimeZone = null; if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) { - // Retrieve and parse cookie value. Cookie cookie = WebUtils.getCookie(request, DEFAULT_COOKIE_NAME); - Locale locale = null; - TimeZone timeZone = null; if (cookie != null) { - String value = cookie.getValue(); - - // Remove the double quote - value = StringUtils.replace(value, QUOTE, ""); - - String localePart = value; - String timeZonePart = null; - int spaceIndex = localePart.indexOf(' '); - if (spaceIndex != -1) { - localePart = value.substring(0, spaceIndex); - timeZonePart = value.substring(spaceIndex + 1); - } - locale = !"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null; - if (timeZonePart != null) { - timeZone = StringUtils.parseTimeZoneString(timeZonePart); - } - if (logger.isTraceEnabled()) { - logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale + - "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : "")); - } + localeAndTimeZone = parseCookie(cookie); } - request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME, - locale != null ? locale : determineDefaultLocale(request)); + } - request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, - timeZone != null ? timeZone : determineDefaultTimeZone(request)); + if (localeAndTimeZone == null) { + localeAndTimeZone = new LocaleAndTimeZone(null, null); } + + request.setAttribute( + LOCALE_REQUEST_ATTRIBUTE_NAME, + localeAndTimeZone.locale != null ? localeAndTimeZone.locale : this.defaultLocaleFunction.apply(request) + ); + request.setAttribute( + TIME_ZONE_REQUEST_ATTRIBUTE_NAME, + localeAndTimeZone.timeZone != null ? localeAndTimeZone.timeZone : this.defaultTimeZoneFunction.apply(request) + ); + } + + private final Function defaultLocaleFunction = request -> { + Locale defaultLocale = getDefaultLocale(); + return (defaultLocale != null ? defaultLocale : request.getLocale()); + }; + + private final Function defaultTimeZoneFunction = request -> getDefaultTimeZone(); + + private LocaleAndTimeZone parseCookie(Cookie cookie) { + String value = StringUtils.replace(cookie.getValue(), QUOTE, ""); + String localePart = value; + String timeZonePart = null; + int spaceIndex = localePart.indexOf(' '); + if (spaceIndex != -1) { + localePart = value.substring(0, spaceIndex); + timeZonePart = value.substring(spaceIndex + 1); + } + Locale locale = !"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null; + TimeZone timeZone = timeZonePart != null ? StringUtils.parseTimeZoneString(timeZonePart) : null; + + if (logger.isTraceEnabled()) { + logger.trace( + "Parsed cookie value [" + + cookie.getValue() + + "] into locale '" + + locale + + "'" + + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : "") + ); + } + return new LocaleAndTimeZone(locale, timeZone); } + private record LocaleAndTimeZone(Locale locale, TimeZone timeZone) {} + String quote(String string) { return QUOTE + string + QUOTE; } From ddbe91240e079a749da9ce185951cb7468c3c454 Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 18:06:53 -0400 Subject: [PATCH 09/15] sonar fix: https://sonarcloud.io/project/issues?fileUuids=AYQzN3Lt2_PoappU_KSf&resolved=false&types=CODE_SMELL&id=jhipster-framework&open=AYQzN3fW2_PoappU_KSh sonar fix: https://sonarcloud.io/project/issues?fileUuids=AYQzN3Lt2_PoappU_KSf&resolved=false&types=CODE_SMELL&id=jhipster-framework&open=AYQzN3fW2_PoappU_KSj sonar fix: https://sonarcloud.io/project/issues?fileUuids=AYQzN3Lt2_PoappU_KSf&resolved=false&types=CODE_SMELL&id=jhipster-framework&open=AYQzN3fW2_PoappU_KSk --- .../jhipster/service/ConditionBuilder.java | 67 ++++--------------- 1 file changed, 13 insertions(+), 54 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java b/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java index f46277c2..12c1ad43 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java +++ b/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java @@ -1,22 +1,3 @@ -/* - * Copyright 2016-2023 the original author or authors from the JHipster project. - * - * This file is part of the JHipster project, see https://www.jhipster.tech/ - * for more information. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package tech.jhipster.service; import java.time.LocalDateTime; @@ -24,12 +5,10 @@ import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; - import org.springframework.data.relational.core.sql.Column; import org.springframework.data.relational.core.sql.Condition; import org.springframework.data.relational.core.sql.Conditions; import org.springframework.data.relational.core.sql.SQL; - import tech.jhipster.service.filter.BooleanFilter; import tech.jhipster.service.filter.DurationFilter; import tech.jhipster.service.filter.Filter; @@ -45,14 +24,14 @@ */ public class ConditionBuilder { - private final List allFilters = new ArrayList(); + private final List allFilters = new ArrayList<>(); private final ColumnConverterReactive columnConverter; public ConditionBuilder(ColumnConverterReactive columnConverter) { this.columnConverter = columnConverter; } - + /** * Method that takes in a filter field and a column to construct a compounded SQL Condition. * The built condition can be retrieved using the buildConditions function @@ -84,7 +63,7 @@ public void buildFilterConditionForField(Filter field, Column column) { } /** - * Method that builds and returns the compounded Condition object. This method can be called + * Method that builds and returns the compounded Condition object. This method can be called * multiple times as the Conditions are being built. * @return returns the compounded Condition object */ @@ -98,42 +77,30 @@ public Condition buildConditions() { } ); } - + private Function columnValueConverter(Class targetClass) { if (targetClass != null) { - return (value) -> columnConverter.convert(value, targetClass).toString(); + return value -> columnConverter.convert(value, targetClass).toString(); } else { - return (value) -> value.toString(); + return value -> value.toString(); } } private > void buildRangeConditions(RangeFilter rangeData, Column column, Class targetClass) { var converterFunction = columnValueConverter(targetClass); if (rangeData.getGreaterThan() != null) { - allFilters.add( - Conditions.isGreater(column, SQL.literalOf(converterFunction.apply(rangeData.getGreaterThan()))) - ); + allFilters.add(Conditions.isGreater(column, SQL.literalOf(converterFunction.apply(rangeData.getGreaterThan())))); } if (rangeData.getLessThan() != null) { - allFilters.add( - Conditions.isLess(column, SQL.literalOf(converterFunction.apply(rangeData.getLessThan()))) - ); + allFilters.add(Conditions.isLess(column, SQL.literalOf(converterFunction.apply(rangeData.getLessThan())))); } if (rangeData.getGreaterThanOrEqual() != null) { allFilters.add( - Conditions.isGreaterOrEqualTo( - column, - SQL.literalOf(converterFunction.apply(rangeData.getGreaterThanOrEqual())) - ) + Conditions.isGreaterOrEqualTo(column, SQL.literalOf(converterFunction.apply(rangeData.getGreaterThanOrEqual()))) ); } if (rangeData.getLessThanOrEqual() != null) { - allFilters.add( - Conditions.isLessOrEqualTo( - column, - SQL.literalOf(converterFunction.apply(rangeData.getLessThanOrEqual())) - ) - ); + allFilters.add(Conditions.isLessOrEqualTo(column, SQL.literalOf(converterFunction.apply(rangeData.getLessThanOrEqual())))); } } @@ -190,24 +157,16 @@ private void buildBooleanConditions(Filter generalData, Column column) { private void buildGeneralConditions(Filter generalData, Column column, Class targetClass) { var converterFunction = columnValueConverter(targetClass); if (generalData.getEquals() != null) { - allFilters.add( - Conditions.isEqual(column, SQL.literalOf(converterFunction.apply(generalData.getEquals()))) - ); + allFilters.add(Conditions.isEqual(column, SQL.literalOf(converterFunction.apply(generalData.getEquals())))); } if (generalData.getNotEquals() != null) { - allFilters.add( - Conditions.isNotEqual(column, SQL.literalOf(converterFunction.apply(generalData.getNotEquals()))) - ); + allFilters.add(Conditions.isNotEqual(column, SQL.literalOf(converterFunction.apply(generalData.getNotEquals())))); } if (generalData.getIn() != null && generalData.getIn().size() > 0) { allFilters.add( Conditions.in( column, - generalData - .getIn() - .stream() - .map(eachIn -> SQL.literalOf(converterFunction.apply(eachIn))) - .collect(Collectors.toList()) + generalData.getIn().stream().map(eachIn -> SQL.literalOf(converterFunction.apply(eachIn))).collect(Collectors.toList()) ) ); } From 48ffc53187f74283927475d1d001b0ce6d3b8675 Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 18:07:59 -0400 Subject: [PATCH 10/15] fix: prettier fix --- .../AngularCookieLocaleResolverTest.java | 59 +++++++++---------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/jhipster-framework/src/test/java/tech/jhipster/config/locale/AngularCookieLocaleResolverTest.java b/jhipster-framework/src/test/java/tech/jhipster/config/locale/AngularCookieLocaleResolverTest.java index 8a225cf3..fdc21d9e 100644 --- a/jhipster-framework/src/test/java/tech/jhipster/config/locale/AngularCookieLocaleResolverTest.java +++ b/jhipster-framework/src/test/java/tech/jhipster/config/locale/AngularCookieLocaleResolverTest.java @@ -19,8 +19,21 @@ package tech.jhipster.config.locale; -import tech.jhipster.test.LogbackRecorder; -import tech.jhipster.test.LogbackRecorder.Event; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.web.servlet.i18n.CookieLocaleResolver.DEFAULT_COOKIE_NAME; +import static org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME; +import static org.springframework.web.servlet.i18n.CookieLocaleResolver.TIME_ZONE_REQUEST_ATTRIBUTE_NAME; + +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.time.ZoneId; +import java.util.List; +import java.util.Locale; +import java.util.TimeZone; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,22 +44,8 @@ import org.springframework.context.i18n.TimeZoneAwareLocaleContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; - -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import java.time.ZoneId; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.web.servlet.i18n.CookieLocaleResolver.DEFAULT_COOKIE_NAME; -import static org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME; -import static org.springframework.web.servlet.i18n.CookieLocaleResolver.TIME_ZONE_REQUEST_ATTRIBUTE_NAME; +import tech.jhipster.test.LogbackRecorder; +import tech.jhipster.test.LogbackRecorder.Event; class AngularCookieLocaleResolverTest { @@ -84,12 +83,12 @@ void teardown() { @Test void testDefaults() { - when(request.getCookies()).thenReturn(new Cookie[]{}); + when(request.getCookies()).thenReturn(new Cookie[] {}); LocaleContext context = resolver.resolveLocaleContext(request); - assertThat(context).isNotNull(); assertThat(context).isInstanceOf(TimeZoneAwareLocaleContext.class); + assertThat(((TimeZoneAwareLocaleContext) context).getLocale()).isEqualTo(LOCALE_DEFAULT); assertThat(((TimeZoneAwareLocaleContext) context).getTimeZone()).isEqualTo(TIMEZONE_DEFAULT); @@ -121,7 +120,7 @@ void testPresets() { void testLocale() { String value = LOCALE_CUSTOM.toString(); Cookie cookie = new Cookie(DEFAULT_COOKIE_NAME, value); - when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[] { cookie }); Locale locale = resolver.resolveLocale(request); @@ -136,7 +135,7 @@ void testLocale() { void testCookieLocaleWithQuotes() { String value = resolver.quote(LOCALE_CUSTOM.toString()); Cookie cookie = new Cookie(DEFAULT_COOKIE_NAME, value); - when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[] { cookie }); Locale locale = resolver.resolveLocale(request); @@ -151,7 +150,7 @@ void testCookieLocaleWithQuotes() { void testTimeZone() { String value = "- " + TIMEZONE_CUSTOM.getID(); Cookie cookie = new Cookie(DEFAULT_COOKIE_NAME, value); - when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[] { cookie }); LocaleContext context = resolver.resolveLocaleContext(request); @@ -170,7 +169,7 @@ void testTimeZone() { void testTimeZoneWithQuotes() { String value = resolver.quote("- " + TIMEZONE_CUSTOM.getID()); Cookie cookie = new Cookie(DEFAULT_COOKIE_NAME, value); - when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[] { cookie }); LocaleContext context = resolver.resolveLocaleContext(request); @@ -189,7 +188,7 @@ void testTimeZoneWithQuotes() { void testLocaleAndTimeZone() { String value = LOCALE_CUSTOM + " " + TIMEZONE_CUSTOM.getID(); Cookie cookie = new Cookie(DEFAULT_COOKIE_NAME, value); - when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[] { cookie }); LocaleContext context = resolver.resolveLocaleContext(request); @@ -208,7 +207,7 @@ void testLocaleAndTimeZone() { void testLocaleAndTimeZoneWithQuotes() { String value = resolver.quote(LOCALE_CUSTOM.toString() + " " + TIMEZONE_CUSTOM.getID()); Cookie cookie = new Cookie(DEFAULT_COOKIE_NAME, value); - when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[] { cookie }); LocaleContext context = resolver.resolveLocaleContext(request); @@ -230,7 +229,7 @@ void testTraceLogLocale() { String value = LOCALE_CUSTOM.toString(); Cookie cookie = new Cookie(DEFAULT_COOKIE_NAME, value); - when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[] { cookie }); Locale locale = resolver.resolveLocale(request); @@ -250,7 +249,7 @@ void testTraceLogLocaleAndTimeZone() { String value = LOCALE_CUSTOM + " " + TIMEZONE_CUSTOM.getID(); Cookie cookie = new Cookie(DEFAULT_COOKIE_NAME, value); - when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[] { cookie }); LocaleContext context = resolver.resolveLocaleContext(request); @@ -263,8 +262,8 @@ void testTraceLogLocaleAndTimeZone() { Event event = events.get(0); assertThat(event.getLevel()).isEqualTo("TRACE"); - assertThat(event.getMessage()).isEqualTo("Parsed cookie value [" + value + "] into locale '" + locale + "' " + - "and time zone '" + zone.getID() + "'"); + assertThat(event.getMessage()) + .isEqualTo("Parsed cookie value [" + value + "] into locale '" + locale + "' " + "and time zone '" + zone.getID() + "'"); assertThat(event.getThrown()).isNull(); } } From ff021cd85a69dc3d8ee2a1d9f4fa6c176e8efe70 Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 18:08:56 -0400 Subject: [PATCH 11/15] test: fixed failing test --- .../web/filter/CachingHttpHeadersFilter.java | 7 ++---- .../CachingHttpHeadersFilterTest.java | 22 +++++++------------ 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/web/filter/CachingHttpHeadersFilter.java b/jhipster-framework/src/main/java/tech/jhipster/web/filter/CachingHttpHeadersFilter.java index 7be58055..3e66a7c3 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/web/filter/CachingHttpHeadersFilter.java +++ b/jhipster-framework/src/main/java/tech/jhipster/web/filter/CachingHttpHeadersFilter.java @@ -19,12 +19,11 @@ package tech.jhipster.web.filter; -import tech.jhipster.config.JHipsterProperties; - import jakarta.servlet.*; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.concurrent.TimeUnit; +import tech.jhipster.config.JHipsterProperties; /** * This filter is used in production, to put HTTP cache headers with a long (4 years) expiration time. @@ -63,9 +62,7 @@ public void destroy() { /** {@inheritDoc} */ @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Cache-Control", "max-age=" + cacheTimeToLive + ", public"); diff --git a/jhipster-framework/src/test/java/tech/jhipster/web/filter/reactive/CachingHttpHeadersFilterTest.java b/jhipster-framework/src/test/java/tech/jhipster/web/filter/reactive/CachingHttpHeadersFilterTest.java index be21d4ca..bcfa30e0 100644 --- a/jhipster-framework/src/test/java/tech/jhipster/web/filter/reactive/CachingHttpHeadersFilterTest.java +++ b/jhipster-framework/src/test/java/tech/jhipster/web/filter/reactive/CachingHttpHeadersFilterTest.java @@ -19,6 +19,9 @@ package tech.jhipster.web.filter.reactive; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; @@ -26,10 +29,6 @@ import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Mono; -import java.util.concurrent.TimeUnit; - -import static org.assertj.core.api.Assertions.assertThat; - class CachingHttpHeadersFilterTest { private long ttl = TimeUnit.DAYS.toMillis(2); @@ -38,26 +37,24 @@ class CachingHttpHeadersFilterTest { @Test void cacheHeadersSetWhenPathMatches() { long now = System.currentTimeMillis(); - WebFilterChain filterChain = (filterExchange) -> { + WebFilterChain filterChain = filterExchange -> { try { HttpHeaders headers = filterExchange.getResponse().getHeaders(); assertThat(headers.getPragma()).isEqualTo("cache"); assertThat(headers.getCacheControl()).isEqualTo("max-age=172800000, public"); - assertThat(headers.getExpires() - now).isBetween(ttl - 1000, ttl + 1000); + assertThat(headers.getExpires() - now).isBetween(ttl - 2000, ttl + 2000); } catch (AssertionError ex) { return Mono.error(ex); } return Mono.empty(); }; - MockServerWebExchange exchange = MockServerWebExchange.from( - MockServerHttpRequest.get("/app/foo") - ); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/app/foo")); filter.filter(exchange, filterChain).block(); } @Test void cacheHeadersNotSetWhenPathDoesntMatch() { - WebFilterChain filterChain = (filterExchange) -> { + WebFilterChain filterChain = filterExchange -> { try { HttpHeaders headers = filterExchange.getResponse().getHeaders(); assertThat(headers.getPragma()).isNull(); @@ -68,10 +65,7 @@ void cacheHeadersNotSetWhenPathDoesntMatch() { } return Mono.empty(); }; - MockServerWebExchange exchange = MockServerWebExchange.from( - MockServerHttpRequest.get("/foo/foo") - ); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/foo/foo")); filter.filter(exchange, filterChain).block(); } - } From 3f383d4d69dbcbaba1873f3740cc4edc492f995b Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Mon, 20 Nov 2023 18:21:54 -0400 Subject: [PATCH 12/15] fix: added header for the file --- .../jhipster/service/ConditionBuilder.java | 19 +++++++++++++++++++ .../jhipster/web/util/LinkHeaderUtil.java | 19 +++++++++++++++++++ .../jhipster/web/util/PaginationUtil.java | 1 - 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java b/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java index 12c1ad43..75f916d5 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java +++ b/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java @@ -1,3 +1,22 @@ +/* + * Copyright 2016-2023 the original author or authors from the JHipster project. + * + * This file is part of the JHipster project, see https://www.jhipster.tech/ + * for more information. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package tech.jhipster.service; import java.time.LocalDateTime; diff --git a/jhipster-framework/src/main/java/tech/jhipster/web/util/LinkHeaderUtil.java b/jhipster-framework/src/main/java/tech/jhipster/web/util/LinkHeaderUtil.java index 71fbf06f..0f8ee781 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/web/util/LinkHeaderUtil.java +++ b/jhipster-framework/src/main/java/tech/jhipster/web/util/LinkHeaderUtil.java @@ -1,3 +1,22 @@ +/* + * Copyright 2016-2023 the original author or authors from the JHipster project. + * + * This file is part of the JHipster project, see https://www.jhipster.tech/ + * for more information. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package tech.jhipster.web.util; import java.text.MessageFormat; diff --git a/jhipster-framework/src/main/java/tech/jhipster/web/util/PaginationUtil.java b/jhipster-framework/src/main/java/tech/jhipster/web/util/PaginationUtil.java index f7a59f40..0682f91a 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/web/util/PaginationUtil.java +++ b/jhipster-framework/src/main/java/tech/jhipster/web/util/PaginationUtil.java @@ -1,4 +1,3 @@ -// new code /* * Copyright 2016-2023 the original author or authors from the JHipster project. * From 13072b2196578e80b87bd4604cad856ce10ace8c Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Tue, 21 Nov 2023 19:25:40 -0400 Subject: [PATCH 13/15] Revert "refactor: "rename variable" smell removal for alert and message in HeaderUtil" This reverts commit e8a85b37759bbd6c3ff8674b1f1862cf1de6d539. --- .../tech/jhipster/web/util/HeaderUtil.java | 80 +++++++------------ .../jhipster/web/util/HeaderUtilTest.java | 8 +- 2 files changed, 33 insertions(+), 55 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/web/util/HeaderUtil.java b/jhipster-framework/src/main/java/tech/jhipster/web/util/HeaderUtil.java index 8b2c07f9..29b66c1f 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/web/util/HeaderUtil.java +++ b/jhipster-framework/src/main/java/tech/jhipster/web/util/HeaderUtil.java @@ -1,12 +1,13 @@ package tech.jhipster.web.util; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + /** * Utility class for HTTP headers creation. */ @@ -14,21 +15,22 @@ public final class HeaderUtil { private static final Logger log = LoggerFactory.getLogger(HeaderUtil.class); - private HeaderUtil() {} + private HeaderUtil() { + } /** *

createAlert.

* * @param applicationName a {@link java.lang.String} object. - * @param alertMessage a {@link java.lang.String} object. - * @param alertParam a {@link java.lang.String} object. + * @param message a {@link java.lang.String} object. + * @param param a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createAlertHeader(String applicationName, String alertMessage, String alertParam) { + public static HttpHeaders createAlert(String applicationName, String message, String param) { HttpHeaders headers = new HttpHeaders(); - headers.add("X-" + applicationName + "-alert", alertMessage); + headers.add("X-" + applicationName + "-alert", message); try { - headers.add("X-" + applicationName + "-params", URLEncoder.encode(alertParam, StandardCharsets.UTF_8.toString())); + headers.add("X-" + applicationName + "-params", URLEncoder.encode(param, StandardCharsets.UTF_8.toString())); } catch (UnsupportedEncodingException e) { // StandardCharsets are supported by every Java implementation so this exception will never happen } @@ -41,19 +43,13 @@ public static HttpHeaders createAlertHeader(String applicationName, String alert * @param applicationName a {@link java.lang.String} object. * @param enableTranslation a boolean. * @param entityName a {@link java.lang.String} object. - * @param entityIdentifier a {@link java.lang.String} object. + * @param param a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createEntityCreationAlert( - String applicationName, - boolean enableTranslation, - String entityName, - String entityIdentifier - ) { - String alertMessage = enableTranslation - ? applicationName + "." + entityName + ".created" - : "A new " + entityName + " is created with identifier " + entityIdentifier; - return createAlertHeader(applicationName, alertMessage, entityIdentifier); + public static HttpHeaders createEntityCreationAlert(String applicationName, boolean enableTranslation, String entityName, String param) { + String message = enableTranslation ? applicationName + "." + entityName + ".created" + : "A new " + entityName + " is created with identifier " + param; + return createAlert(applicationName, message, param); } /** @@ -62,19 +58,13 @@ public static HttpHeaders createEntityCreationAlert( * @param applicationName a {@link java.lang.String} object. * @param enableTranslation a boolean. * @param entityName a {@link java.lang.String} object. - * @param entityIdentifier a {@link java.lang.String} object. + * @param param a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createEntityUpdateAlert( - String applicationName, - boolean enableTranslation, - String entityName, - String entityIdentifier - ) { - String alertMessage = enableTranslation - ? applicationName + "." + entityName + ".updated" - : "A " + entityName + " is updated with identifier " + entityIdentifier; - return createAlertHeader(applicationName, alertMessage, entityIdentifier); + public static HttpHeaders createEntityUpdateAlert(String applicationName, boolean enableTranslation, String entityName, String param) { + String message = enableTranslation ? applicationName + "." + entityName + ".updated" + : "A " + entityName + " is updated with identifier " + param; + return createAlert(applicationName, message, param); } /** @@ -83,19 +73,13 @@ public static HttpHeaders createEntityUpdateAlert( * @param applicationName a {@link java.lang.String} object. * @param enableTranslation a boolean. * @param entityName a {@link java.lang.String} object. - * @param entityIdentifier a {@link java.lang.String} object. + * @param param a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createEntityDeletionAlert( - String applicationName, - boolean enableTranslation, - String entityName, - String entityIdentifier - ) { - String alertMessage = enableTranslation - ? applicationName + "." + entityName + ".deleted" - : "A " + entityName + " is deleted with identifier " + entityIdentifier; - return createAlertHeader(applicationName, alertMessage, entityIdentifier); + public static HttpHeaders createEntityDeletionAlert(String applicationName, boolean enableTranslation, String entityName, String param) { + String message = enableTranslation ? applicationName + "." + entityName + ".deleted" + : "A " + entityName + " is deleted with identifier " + param; + return createAlert(applicationName, message, param); } /** @@ -108,19 +92,13 @@ public static HttpHeaders createEntityDeletionAlert( * @param defaultMessage a {@link java.lang.String} object. * @return a {@link org.springframework.http.HttpHeaders} object. */ - public static HttpHeaders createFailureAlert( - String applicationName, - boolean enableTranslation, - String entityName, - String errorKey, - String defaultMessage - ) { + public static HttpHeaders createFailureAlert(String applicationName, boolean enableTranslation, String entityName, String errorKey, String defaultMessage) { log.error("Entity processing failed, {}", defaultMessage); - String alertMessage = enableTranslation ? "error." + errorKey : defaultMessage; + String message = enableTranslation ? "error." + errorKey : defaultMessage; HttpHeaders headers = new HttpHeaders(); - headers.add("X-" + applicationName + "-error", alertMessage); + headers.add("X-" + applicationName + "-error", message); headers.add("X-" + applicationName + "-params", entityName); return headers; } diff --git a/jhipster-framework/src/test/java/tech/jhipster/web/util/HeaderUtilTest.java b/jhipster-framework/src/test/java/tech/jhipster/web/util/HeaderUtilTest.java index ea097120..a0b3dc38 100644 --- a/jhipster-framework/src/test/java/tech/jhipster/web/util/HeaderUtilTest.java +++ b/jhipster-framework/src/test/java/tech/jhipster/web/util/HeaderUtilTest.java @@ -1,18 +1,18 @@ package tech.jhipster.web.util; -import static org.assertj.core.api.Assertions.assertThat; - import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; +import static org.assertj.core.api.Assertions.assertThat; + class HeaderUtilTest { @Test - void createAlertHeader() { + void createAlert() { String message = "any.message"; String param = "24"; - HttpHeaders headers = HeaderUtil.createAlertHeader("myApp", message, param); + HttpHeaders headers = HeaderUtil.createAlert("myApp", message, param); assertThat(headers.getFirst("X-myApp-alert")).isEqualTo(message); assertThat(headers.getFirst("X-myApp-params")).isEqualTo(param); } From 4b813448ce6962b203942a1652c859a7791bf704 Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Tue, 21 Nov 2023 19:28:19 -0400 Subject: [PATCH 14/15] refactor: "rename variable" for hashcode --- .../tech/jhipster/config/cache/PrefixedSimpleKey.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedSimpleKey.java b/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedSimpleKey.java index 31f3bca5..137185dc 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedSimpleKey.java +++ b/jhipster-framework/src/main/java/tech/jhipster/config/cache/PrefixedSimpleKey.java @@ -13,7 +13,7 @@ public class PrefixedSimpleKey implements Serializable { private final String prefix; private transient Object[] params; private final String methodName; - private int hashCode; + private int hashCodeValue ; /** *

Constructor for PrefixedSimpleKey.

@@ -30,9 +30,9 @@ public PrefixedSimpleKey(String prefix, String methodName, Object... elements) { params = new Object[elements.length]; System.arraycopy(elements, 0, params, 0, elements.length); - hashCode = prefix.hashCode(); - hashCode = 31 * hashCode + methodName.hashCode(); - hashCode = 31 * hashCode + Arrays.deepHashCode(params); + hashCodeValue = prefix.hashCode(); + hashCodeValue = 31 * hashCodeValue + methodName.hashCode(); + hashCodeValue = 31 * hashCodeValue + Arrays.deepHashCode(params); } /** {@inheritDoc} */ @@ -50,7 +50,7 @@ public boolean equals(Object other) { /** {@inheritDoc} */ @Override public final int hashCode() { - return hashCode; + return hashCodeValue ; } /** {@inheritDoc} */ From e70aa68598ba040dcac482568a1f8b6c1d532ca5 Mon Sep 17 00:00:00 2001 From: DISHA ANAND Date: Wed, 22 Nov 2023 14:18:26 -0400 Subject: [PATCH 15/15] fix: suggested review changes - added version for ExceptionHandlingAsyncTaskExecutor file - removed unwanted character --- .../tech/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java | 2 +- .../tech/jhipster/config/liquibase/AsyncSpringLiquibase.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jhipster-framework/src/main/java/tech/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java b/jhipster-framework/src/main/java/tech/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java index e7dcef34..e9a14279 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java +++ b/jhipster-framework/src/main/java/tech/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java @@ -55,7 +55,7 @@ public void execute(Runnable task) { /** {@inheritDoc} */ @Override - @Deprecated(since = "version", forRemoval = true) + @Deprecated(since = "7.8.0", forRemoval = true) public void execute(Runnable task, long startTimeout) { executor.execute(createWrappedRunnable(task), startTimeout); } diff --git a/jhipster-framework/src/main/java/tech/jhipster/config/liquibase/AsyncSpringLiquibase.java b/jhipster-framework/src/main/java/tech/jhipster/config/liquibase/AsyncSpringLiquibase.java index 68fc8424..eafdc900 100644 --- a/jhipster-framework/src/main/java/tech/jhipster/config/liquibase/AsyncSpringLiquibase.java +++ b/jhipster-framework/src/main/java/tech/jhipster/config/liquibase/AsyncSpringLiquibase.java @@ -51,7 +51,7 @@ public class AsyncSpringLiquibase extends DataSourceClosingSpringLiquibase { /** Constant STARTED_MESSAGE="Liquibase has updated your database in "{trunked} */ public static final String STARTED_MESSAGE = "Liquibase has updated your database in {} ms"; /** Constant EXCEPTION_MESSAGE="Liquibase could not start correctly, yo"{trunked} */ - public static final String EXCEPTION_MESSAGE = "Liquibase could not start correctly, your database is NOT ready: " + "{}"; + public static final String EXCEPTION_MESSAGE = "Liquibase could not start correctly, your database is NOT ready: {}"; /** Constant SLOWNESS_THRESHOLD=5 */ public static final long SLOWNESS_THRESHOLD = 5; // seconds