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..e9a14279 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 = "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/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) {
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..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
@@ -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,9 +11,9 @@
public class PrefixedSimpleKey implements Serializable {
private final String prefix;
- private final Object[] params;
+ private transient Object[] params;
private final String methodName;
- private int hashCode;
+ private int hashCodeValue ;
/**
* Constructor for PrefixedSimpleKey.
@@ -30,30 +29,33 @@ 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);
+
+ hashCodeValue = prefix.hashCode();
+ hashCodeValue = 31 * hashCodeValue + methodName.hashCode();
+ hashCodeValue = 31 * hashCodeValue + Arrays.deepHashCode(params);
}
/** {@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} */
@Override
public final int hashCode() {
- return hashCode;
+ return hashCodeValue ;
}
/** {@inheritDoc} */
@Override
public String toString() {
- return prefix + " " + getClass().getSimpleName() + methodName + " [" + StringUtils.arrayToCommaDelimitedString(
- params) + "]";
+ return prefix + " " + getClass().getSimpleName() + methodName + " [" + StringUtils.arrayToCommaDelimitedString(params) + "]";
}
}
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);
}
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..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
@@ -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);
}
}
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;
}
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..75f916d5 100644
--- a/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java
+++ b/jhipster-framework/src/main/java/tech/jhipster/service/ConditionBuilder.java
@@ -24,12 +24,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 +43,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 +82,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 +96,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 +176,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())
)
);
}
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/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..0f8ee781
--- /dev/null
+++ b/jhipster-framework/src/main/java/tech/jhipster/web/util/LinkHeaderUtil.java
@@ -0,0 +1,59 @@
+/*
+ * 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;
+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..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
@@ -22,8 +22,6 @@
import org.springframework.http.HttpHeaders;
import org.springframework.web.util.UriComponentsBuilder;
-import java.text.MessageFormat;
-
/**
* Utility class for handling pagination.
*
@@ -34,10 +32,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 +48,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");
- }
}
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();
}
}
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();
}
-
}