Browse Source

Added CORS for 'Access-Control-Allow-Origin' header

Lukas Cerny 4 years ago
parent
commit
52f77dcf70

+ 4 - 4
src/main/java/cz/senslog/analyzer/app/Application.java

@@ -88,12 +88,12 @@ public class Application extends Thread {
 
 
         ConnectionModule connectionModule = ConnectionModule.create(storageConfig);
-        logger.info("Module {} was created successfully.", ConnectionModule.class.getSimpleName());
+        logger.info("Module '{}' was created successfully.", connectionModule.getClass().getSimpleName());
 
         Analyzer<Observation> analyzer = DaggerAnalyzerComponent.builder()
                 .connectionModule(connectionModule)
                 .build().createNewObservationAnalyzer();
-        logger.info("Component {} was created successfully.", Analyzer.class.getSimpleName());
+        logger.info("Component '{}' was created successfully.", analyzer.getClass().getSimpleName());
 
 
         DataProviderComponent dataProviderComponent = DaggerDataProviderComponent.builder()
@@ -101,12 +101,12 @@ public class Application extends Thread {
 
         DataProvider<Observation> dataProvider = dataProviderComponent.scheduledDatabaseProvider()
                 .config(config).deployAnalyzer(analyzer);
-        logger.info("Component {} was created successfully.", DataProvider.class.getSimpleName());
+        logger.info("Component '{}' was created successfully.", dataProvider.getClass().getSimpleName());
 
         Server server = DaggerServerComponent.builder()
                 .connectionModule(connectionModule).build()
                 .createServer();
-        logger.info("Component {} was created successfully.", Server.class.getSimpleName());
+        logger.info("Component '{}' was created successfully.", server.getClass().getSimpleName());
 
         server.start(port);
         dataProvider.start();

+ 79 - 79
src/main/java/cz/senslog/analyzer/storage/ConnectionModule.java

@@ -1,79 +1,79 @@
-package cz.senslog.analyzer.storage;
-
-import com.zaxxer.hikari.HikariConfig;
-import com.zaxxer.hikari.HikariDataSource;
-import cz.senslog.analyzer.storage.inmemory.InMemoryConnection;
-import cz.senslog.analyzer.storage.inmemory.InMemoryStorageConfig;
-import cz.senslog.analyzer.storage.permanent.PermanentStorageConfig;
-import cz.senslog.analyzer.storage.permanent.PermanentConnection;
-import dagger.Module;
-import dagger.Provides;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.jdbi.v3.core.Jdbi;
-import org.jdbi.v3.jodatime2.JodaTimePlugin;
-import org.jdbi.v3.postgres.PostgresPlugin;
-import org.postgresql.ds.PGSimpleDataSource;
-
-import javax.inject.Singleton;
-
-import static java.lang.String.format;
-
-@Module
-public class ConnectionModule {
-
-    private static final Logger logger = LogManager.getLogger(ConnectionModule.class);
-
-    private final StorageConfig config;
-
-    public static ConnectionModule create(StorageConfig storageConfig) {
-        return new ConnectionModule(storageConfig);
-    }
-
-    private ConnectionModule(StorageConfig config) {
-        this.config = config;
-    }
-
-    private PermanentConnection permanentConnection;
-    private InMemoryConnection inMemoryConnection;
-
-    @Provides @Singleton
-    public PermanentConnection providePermanentStorageConnection() {
-        if (permanentConnection == null) {
-            PermanentStorageConfig config = this.config.getPermanentStorageConfig();
-            logger.info("Creating a connection to the database of the class: {}.", Jdbi.class);
-            PGSimpleDataSource ds = new PGSimpleDataSource();
-            ds.setUrl(config.getConnectionUrl());
-            ds.setPassword(config.getPassword());
-            ds.setUser(config.getUsername());
-            ds.setLoadBalanceHosts(true);
-            HikariConfig hc = new HikariConfig();
-            hc.setDataSource(ds);
-            hc.setMaximumPoolSize(config.getConnectionPoolSize());
-
-            permanentConnection = new PermanentConnection(Jdbi
-                    .create(new HikariDataSource(hc))
-                    .installPlugin(new PostgresPlugin())
-                    .installPlugin(new JodaTimePlugin())
-            );
-        }
-        return permanentConnection;
-    }
-
-    @Provides @Singleton
-    public InMemoryConnection provideInMemoryStorageConnection() {
-        if (inMemoryConnection == null) {
-            InMemoryStorageConfig config = this.config.getInMemoryStorageConfig();
-
-            StringBuilder url = new StringBuilder("jdbc:h2");
-            url.append(config.isPersistence() ? ":file" : ":mem");
-            url.append(":").append(config.getPath());
-            if (!config.getParameters().isEmpty()) {
-                url.append(":").append(config.getParameters());
-            }
-
-            inMemoryConnection = new InMemoryConnection(Jdbi.create(url.toString()));
-        }
-        return inMemoryConnection;
-    }
-}
+package cz.senslog.analyzer.storage;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import cz.senslog.analyzer.storage.inmemory.InMemoryConnection;
+import cz.senslog.analyzer.storage.inmemory.InMemoryStorageConfig;
+import cz.senslog.analyzer.storage.permanent.PermanentStorageConfig;
+import cz.senslog.analyzer.storage.permanent.PermanentConnection;
+import dagger.Module;
+import dagger.Provides;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.jdbi.v3.core.Jdbi;
+import org.jdbi.v3.jodatime2.JodaTimePlugin;
+import org.jdbi.v3.postgres.PostgresPlugin;
+import org.postgresql.ds.PGSimpleDataSource;
+
+import javax.inject.Singleton;
+
+import static java.lang.String.format;
+
+@Module
+public class ConnectionModule {
+
+    private static final Logger logger = LogManager.getLogger(ConnectionModule.class);
+
+    private final StorageConfig config;
+
+    public static ConnectionModule create(StorageConfig storageConfig) {
+        return new ConnectionModule(storageConfig);
+    }
+
+    private ConnectionModule(StorageConfig config) {
+        this.config = config;
+    }
+
+    private PermanentConnection permanentConnection;
+    private InMemoryConnection inMemoryConnection;
+
+    @Provides @Singleton
+    public PermanentConnection providePermanentStorageConnection() {
+        if (permanentConnection == null) {
+            PermanentStorageConfig config = this.config.getPermanentStorageConfig();
+            logger.info("Creating a connection to the database of the class: {}.", Jdbi.class);
+            PGSimpleDataSource ds = new PGSimpleDataSource();
+            ds.setUrl(config.getConnectionUrl());
+            ds.setPassword(config.getPassword());
+            ds.setUser(config.getUsername());
+            ds.setLoadBalanceHosts(true);
+            HikariConfig hc = new HikariConfig();
+            hc.setDataSource(ds);
+            hc.setMaximumPoolSize(config.getConnectionPoolSize());
+
+            permanentConnection = new PermanentConnection(Jdbi
+                    .create(new HikariDataSource(hc))
+                    .installPlugin(new PostgresPlugin())
+                    .installPlugin(new JodaTimePlugin())
+            );
+        }
+        return permanentConnection;
+    }
+
+    @Provides @Singleton
+    public InMemoryConnection provideInMemoryStorageConnection() {
+        if (inMemoryConnection == null) {
+            InMemoryStorageConfig config = this.config.getInMemoryStorageConfig();
+
+            StringBuilder url = new StringBuilder("jdbc:h2");
+            url.append(config.isPersistence() ? ":file" : ":mem");
+            url.append(":").append(config.getPath());
+            if (!config.getParameters().isEmpty()) {
+                url.append(":").append(config.getParameters());
+            }
+
+            inMemoryConnection = new InMemoryConnection(Jdbi.create(url.toString()));
+        }
+        return inMemoryConnection;
+    }
+}

+ 4 - 0
src/main/java/cz/senslog/analyzer/util/StringUtils.java

@@ -8,6 +8,10 @@ public final class StringUtils {
         return string == null || string.isEmpty();
     }
 
+    public static String getOrDefault(String string, String defaultValue) {
+        return isEmpty(string) ? defaultValue : string;
+    }
+
     public static boolean isBlank(String string) {
         return string == null || string.replaceAll("\\s+", "").isEmpty();
     }

+ 8 - 6
src/main/java/cz/senslog/analyzer/ws/vertx/VertxServer.java

@@ -5,11 +5,9 @@ import cz.senslog.analyzer.ws.handler.GroupsHandler;
 import cz.senslog.analyzer.ws.handler.InfoHandler;
 import cz.senslog.analyzer.ws.handler.StatisticsHandler;
 import io.vertx.core.*;
-import io.vertx.core.http.HttpMethod;
 import io.vertx.core.http.HttpServerResponse;
 import io.vertx.core.json.JsonObject;
 import io.vertx.ext.web.Router;
-import io.vertx.ext.web.handler.CorsHandler;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
@@ -17,6 +15,7 @@ import javax.inject.Inject;
 import java.util.HashMap;
 import java.util.Map;
 
+import static cz.senslog.analyzer.util.StringUtils.getOrDefault;
 import static cz.senslog.analyzer.util.http.HttpContentType.APPLICATION_JSON;
 import static cz.senslog.analyzer.util.http.HttpHeader.CONTENT_TYPE;
 
@@ -49,14 +48,17 @@ public class VertxServer extends AbstractVerticle implements Server {
     public void start(final Promise<Void> promise) {
 
         Router router = Router.router(vertx);
+
+        router.route().handler(ctx -> {
+            String origin = getOrDefault(ctx.request().getHeader("origin"), "*");
+            ctx.response().putHeader("Access-Control-Allow-Origin", origin);
+            ctx.next();
+        });
+
         for (Map.Entry<String, AbstractRestHandler> handlerEntry : restHandlers.entrySet()) {
             router.mountSubRouter(handlerEntry.getKey(), handlerEntry.getValue().start(vertx));
         }
 
-        router.route().handler(CorsHandler.create()
-                .allowedMethod(HttpMethod.GET)
-        );
-
         router.route().failureHandler(ctx -> {
             logger.catching(ctx.failure());
             HttpServerResponse response = ctx.response();

+ 35 - 0
src/main/resources/log4j2.xml

@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Configuration xmlns="http://logging.apache.org/log4j/2.0/config" status="INFO">
+
+    <Properties>
+        <Property name="logPath">./</Property>
+    </Properties>
+
+    <Appenders>
+
+        <Console name="console" target="SYSTEM_OUT">
+            <PatternLayout pattern="%-5p | %d{yyyy-MM-dd HH:mm:ss} | [%t] %C{2} (%F:%L) - %m%n" />
+        </Console>
+
+        <RollingFile name="filebeat"
+                     fileName="${sys:logPath}/app.log"
+                     filePattern="${sys:logPath}/app.%i.log.gz"
+        >
+            <PatternLayout alwaysWriteExceptions="false"
+                    pattern='{"app.date":"%d{ISO8601}","app.thread":"%t","app.level":"%level","app.logger":"%logger:%L", "app.exception":"%enc{%ex}{JSON}", "app.message":"%msg"}%n'
+            />
+            <Policies>
+<!--                <TimeBasedTriggeringPolicy interval="1"/> &lt;!&ndash; Number of days for a log file &ndash;&gt;-->
+                <SizeBasedTriggeringPolicy size="10MB" />
+            </Policies>
+        </RollingFile>
+
+    </Appenders>
+    <Loggers>
+        <Logger name="cz.senslog" level="info" />
+        <Root level="info">
+            <AppenderRef ref="console" />
+            <AppenderRef ref="filebeat" />
+        </Root>
+    </Loggers>
+</Configuration>