Skip to content

Commit

Permalink
Merge pull request #1472 from DishaAnand/main
Browse files Browse the repository at this point in the history
refactor & sonar fixes
  • Loading branch information
DanielFran authored Nov 22, 2023
2 parents 8235d73 + e70aa68 commit f21dc57
Show file tree
Hide file tree
Showing 12 changed files with 243 additions and 218 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
* <p>ExceptionHandlingAsyncTaskExecutor class.</p>
*/
public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor,
InitializingBean, DisposableBean {
public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor, InitializingBean, DisposableBean {

static final String EXCEPTION_MESSAGE = "Caught async exception";

Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;

/**
* <p>PrefixedKeyGenerator class.</p>
* <p>
Expand All @@ -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;

/**
* <p>Constructor for PrefixedKeyGenerator.</p>
Expand All @@ -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);
}

Expand All @@ -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();
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
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;

/**
* <p>PrefixedSimpleKey class.</p>
*/
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 ;

/**
* <p>Constructor for PrefixedSimpleKey.</p>
Expand All @@ -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) + "]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@
*/
public class H2ConfigurationHelper {

private H2ConfigurationHelper() {
throw new AssertionError("The class should not be instantiated");
}

/**
* <p>createServer.</p>
*
Expand All @@ -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) {
Expand Down Expand Up @@ -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);
}
}

Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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. <p> By default, this asynchronous version only works when using the "dev" profile.<p> The standard
Expand All @@ -46,15 +45,13 @@ public class AsyncSpringLiquibase extends DataSourceClosingSpringLiquibase {
/** Constant <code>DISABLED_MESSAGE="Liquibase is disabled"</code> */
public static final String DISABLED_MESSAGE = "Liquibase is disabled";
/** Constant <code>STARTING_ASYNC_MESSAGE="Starting Liquibase asynchronously, your"{trunked}</code> */
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 <code>STARTING_SYNC_MESSAGE="Starting Liquibase synchronously"</code> */
public static final String STARTING_SYNC_MESSAGE = "Starting Liquibase synchronously";
/** Constant <code>STARTED_MESSAGE="Liquibase has updated your database in "{trunked}</code> */
public static final String STARTED_MESSAGE = "Liquibase has updated your database in {} ms";
/** Constant <code>EXCEPTION_MESSAGE="Liquibase could not start correctly, yo"{trunked}</code> */
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 <code>SLOWNESS_THRESHOLD=5</code> */
public static final long SLOWNESS_THRESHOLD = 5; // seconds
Expand Down Expand Up @@ -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);
}
}

Expand All @@ -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);
}
}
Expand Down
Loading

0 comments on commit f21dc57

Please sign in to comment.