Skip to content

Commit

Permalink
feature: use SteveConfiguration as Spring component
Browse files Browse the repository at this point in the history
  • Loading branch information
juherr committed Jul 29, 2023
1 parent c49d0c0 commit 9fcd112
Show file tree
Hide file tree
Showing 40 changed files with 515 additions and 290 deletions.
6 changes: 3 additions & 3 deletions src/main/java/de/rwth/idsg/steve/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public Application() {
// For Hibernate validator
System.setProperty("org.jboss.logging.provider", "slf4j");

SteveConfiguration sc = SteveConfiguration.CONFIG;
SteveConfiguration sc = new SteveConfiguration();
log.info("Loaded the properties. Starting with the '{}' profile", sc.getProfile());

TimeZone.setDefault(TimeZone.getTimeZone(sc.getTimeZoneId()));
Expand All @@ -46,11 +46,11 @@ public Application() {

switch (sc.getProfile()) {
case DEV:
delegate = new SteveDevStarter();
delegate = new SteveDevStarter(sc);
break;
case TEST:
case PROD:
delegate = new SteveProdStarter();
delegate = new SteveProdStarter(sc);
break;
default:
throw new RuntimeException("Unexpected profile");
Expand Down
41 changes: 22 additions & 19 deletions src/main/java/de/rwth/idsg/steve/JettyServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,14 @@
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static de.rwth.idsg.steve.SteveConfiguration.CONFIG;

/**
* @author Sevket Goekay <sevketgokay@gmail.com>
* @since 12.12.2014
*/
@Slf4j
public class JettyServer {

private final SteveConfiguration config;
private Server server;
private SteveAppContext steveAppContext;

Expand All @@ -69,6 +68,10 @@ public class JettyServer {
private static final long STOP_TIMEOUT = TimeUnit.SECONDS.toMillis(5);
private static final long IDLE_TIMEOUT = TimeUnit.MINUTES.toMillis(1);

public JettyServer(SteveConfiguration config) {
this.config = config;
}

Check failure on line 74 in src/main/java/de/rwth/idsg/steve/JettyServer.java

View workflow job for this annotation

GitHub Actions / checkstyle

[checkstyle] reported by reviewdog 🐶 Line has trailing spaces. Raw Output: /github/workspace/./src/main/java/de/rwth/idsg/steve/JettyServer.java:74:0: error: Line has trailing spaces. (com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineCheck)
/**
* A fully configured Jetty Server instance
*/
Expand All @@ -89,7 +92,7 @@ private void prepare() {
// HTTP Configuration
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme(HttpScheme.HTTPS.asString());
httpConfig.setSecurePort(CONFIG.getJetty().getHttpsPort());
httpConfig.setSecurePort(config.getJetty().getHttpsPort());
httpConfig.setOutputBufferSize(32768);
httpConfig.setRequestHeaderSize(8192);
httpConfig.setResponseHeaderSize(8192);
Expand All @@ -107,23 +110,23 @@ private void prepare() {
server.setStopAtShutdown(true);
server.setStopTimeout(STOP_TIMEOUT);

if (CONFIG.getJetty().isHttpEnabled()) {
if (config.getJetty().isHttpEnabled()) {
server.addConnector(httpConnector(httpConfig));
}

if (CONFIG.getJetty().isHttpsEnabled()) {
if (config.getJetty().isHttpsEnabled()) {
server.addConnector(httpsConnector(httpConfig));
}

steveAppContext = new SteveAppContext();
steveAppContext = new SteveAppContext(config);
server.setHandler(steveAppContext.getHandlers());
}

private ServerConnector httpConnector(HttpConfiguration httpConfig) {
// === jetty-http.xml ===
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
http.setHost(CONFIG.getJetty().getServerHost());
http.setPort(CONFIG.getJetty().getHttpPort());
http.setHost(config.getJetty().getServerHost());
http.setPort(config.getJetty().getHttpPort());
http.setIdleTimeout(IDLE_TIMEOUT);
return http;
}
Expand All @@ -132,9 +135,9 @@ private ServerConnector httpsConnector(HttpConfiguration httpConfig) {
// === jetty-https.xml ===
// SSL Context Factory
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath(CONFIG.getJetty().getKeyStorePath());
sslContextFactory.setKeyStorePassword(CONFIG.getJetty().getKeyStorePassword());
sslContextFactory.setKeyManagerPassword(CONFIG.getJetty().getKeyStorePassword());
sslContextFactory.setKeyStorePath(config.getJetty().getKeyStorePath());
sslContextFactory.setKeyStorePassword(config.getJetty().getKeyStorePassword());
sslContextFactory.setKeyManagerPassword(config.getJetty().getKeyStorePassword());
sslContextFactory.setExcludeCipherSuites(
"SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA",
Expand All @@ -152,8 +155,8 @@ private ServerConnector httpsConnector(HttpConfiguration httpConfig) {
ServerConnector https = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfig));
https.setHost(CONFIG.getJetty().getServerHost());
https.setPort(CONFIG.getJetty().getHttpsPort());
https.setHost(config.getJetty().getServerHost());
https.setPort(config.getJetty().getHttpsPort());
https.setIdleTimeout(IDLE_TIMEOUT);
return https;
}
Expand Down Expand Up @@ -206,12 +209,12 @@ private List<String> getConnectorPathList() {
}

return Arrays.stream(server.getConnectors())
.map(JettyServer::getConnectorPath)
.map(this::getConnectorPath)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}

private static List<String> getConnectorPath(Connector c) {
private List<String> getConnectorPath(Connector c) {
ServerConnector sc = (ServerConnector) c;

final String prefix;
Expand All @@ -224,12 +227,12 @@ private static List<String> getConnectorPath(Connector c) {
Set<String> ips = new HashSet<>();
String host = sc.getHost();
if (host == null || host.equals("0.0.0.0")) {

Check warning on line 229 in src/main/java/de/rwth/idsg/steve/JettyServer.java

View workflow job for this annotation

GitHub Actions / pmd

Do not hard code the IP address

Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP adresses is preferable. AvoidUsingHardCodedIP (Priority: 3, Ruleset: Best Practices) https://pmd.github.io/pmd-6.49.0/pmd_rules_java_bestpractices.html#avoidusinghardcodedip
ips.addAll(getPossibleIpAddresses());
ips.addAll(getPossibleIpAddresses(config));
} else {
ips.add(host);
}

String layout = "%s://%s:%d" + CONFIG.getContextPath();
String layout = "%s://%s:%d" + config.getContextPath();

return ips.stream()
.map(k -> String.format(layout, prefix, k, sc.getPort()))
Expand All @@ -253,7 +256,7 @@ private String getElementPrefix(String str, boolean replaceHttp) {
/**
* Uses different APIs to find out the IP of this machine.
*/
private static List<String> getPossibleIpAddresses() {
private static List<String> getPossibleIpAddresses(SteveConfiguration config) {
final String host = "treibhaus.informatik.rwth-aachen.de";
final List<String> ips = new ArrayList<>();

Expand Down Expand Up @@ -300,7 +303,7 @@ private static List<String> getPossibleIpAddresses() {
if (ips.isEmpty()) {
// Well, we failed to read from system, fall back to main.properties.
// Better than nothing
ips.add(CONFIG.getJetty().getServerHost());
ips.add(config.getJetty().getServerHost());
}

return ips;
Expand Down
36 changes: 22 additions & 14 deletions src/main/java/de/rwth/idsg/steve/SteveAppContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
import java.util.HashSet;
import java.util.List;

import static de.rwth.idsg.steve.SteveConfiguration.CONFIG;
import static de.rwth.idsg.steve.config.WebSocketConfiguration.IDLE_TIMEOUT;
import static de.rwth.idsg.steve.config.WebSocketConfiguration.MAX_MSG_SIZE;

Expand All @@ -59,13 +58,22 @@
*/
public class SteveAppContext {

private final SteveConfiguration config;
private final AnnotationConfigWebApplicationContext springContext;
private final WebAppContext webAppContext;

public SteveAppContext() {
springContext = new AnnotationConfigWebApplicationContext();
public SteveAppContext(SteveConfiguration config) {
this.config = config;
this.springContext = createSpringContext(config);
this.webAppContext = initWebApp(config, springContext);
}

private static AnnotationConfigWebApplicationContext createSpringContext(SteveConfiguration config) {
AnnotationConfigWebApplicationContext springContext = new AnnotationConfigWebApplicationContext();
springContext.getEnvironment().setActiveProfiles(config.getProfile().name());
springContext.addBeanFactoryPostProcessor(factory -> factory.registerSingleton(SteveConfiguration.class.getName(), config));

Check failure on line 74 in src/main/java/de/rwth/idsg/steve/SteveAppContext.java

View workflow job for this annotation

GitHub Actions / checkstyle

[checkstyle] reported by reviewdog 🐶 Line is longer than 120 characters (found 132). Raw Output: /github/workspace/./src/main/java/de/rwth/idsg/steve/SteveAppContext.java:74:0: error: Line is longer than 120 characters (found 132). (com.puppycrawl.tools.checkstyle.checks.sizes.LineLengthCheck)
springContext.scan("de.rwth.idsg.steve.config");
webAppContext = initWebApp();
return springContext;
}

public HandlerCollection getHandlers() {
Expand All @@ -85,7 +93,7 @@ public void configureWebSocket() {
}

private Handler getWebApp() {
if (!CONFIG.getJetty().isGzipEnabled()) {
if (!config.getJetty().isGzipEnabled()) {
return webAppContext;
}

Expand All @@ -96,9 +104,9 @@ private Handler getWebApp() {
return gzipHandler;
}

private WebAppContext initWebApp() {
private static WebAppContext initWebApp(SteveConfiguration config, AnnotationConfigWebApplicationContext springContext) {

Check failure on line 107 in src/main/java/de/rwth/idsg/steve/SteveAppContext.java

View workflow job for this annotation

GitHub Actions / checkstyle

[checkstyle] reported by reviewdog 🐶 Line is longer than 120 characters (found 125). Raw Output: /github/workspace/./src/main/java/de/rwth/idsg/steve/SteveAppContext.java:107:0: error: Line is longer than 120 characters (found 125). (com.puppycrawl.tools.checkstyle.checks.sizes.LineLengthCheck)
WebAppContext ctx = new WebAppContext();
ctx.setContextPath(CONFIG.getContextPath());
ctx.setContextPath(config.getContextPath());
ctx.setResourceBase(getWebAppURIAsString());

// if during startup an exception happens, do not swallow it, throw it
Expand All @@ -111,15 +119,15 @@ private WebAppContext initWebApp() {
ServletHolder cxf = new ServletHolder("cxf", new CXFServlet());

ctx.addEventListener(new ContextLoaderListener(springContext));
ctx.addServlet(web, CONFIG.getSpringMapping());
ctx.addServlet(cxf, CONFIG.getCxfMapping() + "/*");
ctx.addServlet(web, config.getSpringMapping());
ctx.addServlet(cxf, config.getCxfMapping() + "/*");

if (CONFIG.getProfile().isProd()) {
if (config.getProfile().isProd()) {
// If PROD, add security filter
ctx.addFilter(
// The bean name is not arbitrary, but is as expected by Spring
new FilterHolder(new DelegatingFilterProxy(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)),
CONFIG.getSpringMapping() + "*",
config.getSpringMapping() + "*",
EnumSet.allOf(DispatcherType.class)
);
}
Expand All @@ -137,14 +145,14 @@ private Handler getRedirectHandler() {
RedirectPatternRule rule = new RedirectPatternRule();
rule.setTerminating(true);
rule.setPattern(redirect);
rule.setLocation(CONFIG.getContextPath() + "/manager/home");
rule.setLocation(config.getContextPath() + "/manager/home");
rewrite.addRule(rule);
}
return rewrite;
}

private HashSet<String> getRedirectSet() {
String path = CONFIG.getContextPath();
String path = config.getContextPath();

HashSet<String> redirectSet = new HashSet<>(3);
redirectSet.add("");
Expand All @@ -165,7 +173,7 @@ private HashSet<String> getRedirectSet() {
* https://github.com/jasonish/jetty-springmvc-jsp-template
* http://examples.javacodegeeks.com/enterprise-java/jetty/jetty-jsp-example
*/
private void initJSP(WebAppContext ctx) {
private static void initJSP(WebAppContext ctx) {
// Ensure the JSP engine is initialized correctly
List<ContainerInitializer> initializers = new ArrayList<>();
initializers.add(new ContainerInitializer(new JettyJasperInitializer(), null));
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/de/rwth/idsg/steve/SteveConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@
* @since 19.08.2014
*/
@Getter
public enum SteveConfiguration {
CONFIG;
public class SteveConfiguration {

// Root mapping for Spring
private final String springMapping = "/";
Expand Down Expand Up @@ -61,7 +60,7 @@ public enum SteveConfiguration {
private final DB db;
private final Jetty jetty;

SteveConfiguration() {
public SteveConfiguration() {
PropertiesFileLoader p = new PropertiesFileLoader("main.properties");

contextPath = sanitizeContextPath(p.getOptionalString("context.path"));
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/de/rwth/idsg/steve/SteveDevStarter.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ public class SteveDevStarter implements ApplicationStarter {

private final JettyServer jettyServer;

SteveDevStarter() {
this.jettyServer = new JettyServer();
SteveDevStarter(SteveConfiguration config) {
this.jettyServer = new JettyServer(config);
}

@Override
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/de/rwth/idsg/steve/SteveProdCondition.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import org.springframework.context.annotation.Profile;
import org.springframework.core.type.AnnotatedTypeMetadata;

import static de.rwth.idsg.steve.SteveConfiguration.CONFIG;
import java.util.Arrays;

/**
* We might also have used {@link Profile} for registering beans depending on profile,
Expand All @@ -44,6 +44,8 @@ public class SteveProdCondition implements Condition {

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return CONFIG.getProfile().isProd();
return Arrays.stream(context.getEnvironment().getActiveProfiles())
.map(ApplicationProfile::fromName)
.anyMatch(ApplicationProfile::isProd);
}
}
4 changes: 2 additions & 2 deletions src/main/java/de/rwth/idsg/steve/SteveProdStarter.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ public class SteveProdStarter implements ApplicationStarter {
private final JettyServer jettyServer;
private Thread dotThread;

SteveProdStarter() {
this.jettyServer = new JettyServer();
SteveProdStarter(SteveConfiguration config) {
this.jettyServer = new JettyServer(config);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,15 @@ public class ApiDocsConfiguration {
}

@Bean
public Docket apiDocs() {
public Docket apiDocs(SteveConfiguration config) {
String title = "SteVe REST API Documentation";

var apiInfo = new ApiInfoBuilder()
.title(title)
.description(title)
.license("GPL-3.0")
.licenseUrl("https://github.com/steve-community/steve/blob/master/LICENSE.txt")
.version(SteveConfiguration.CONFIG.getSteveVersion())
.version(config.getSteveVersion())
.build();

return new Docket(DocumentationType.OAS_30)
Expand Down
Loading

0 comments on commit 9fcd112

Please sign in to comment.