File remove_jetty.patch of Package spark-core
diff --git a/pom.xml b/pom.xml
index 0781cb8..6e90bf0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -30,7 +30,6 @@
<properties>
<java.version>1.8</java.version>
- <jetty.version>9.4.31.v20200723</jetty.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<powermock.version>1.7.4</powermock.version>
<mockito.version>1.10.19</mockito.version>
@@ -51,28 +50,11 @@
<scope>test</scope>
</dependency>
- <!-- JETTY DEPENDENCIES -->
<dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-server</artifactId>
- <version>${jetty.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.eclipse.jetty</groupId>
- <artifactId>jetty-webapp</artifactId>
- <version>${jetty.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.eclipse.jetty.websocket</groupId>
- <artifactId>websocket-server</artifactId>
- <version>${jetty.version}</version>
- </dependency>
- <dependency>
- <groupId>org.eclipse.jetty.websocket</groupId>
- <artifactId>websocket-servlet</artifactId>
- <version>${jetty.version}</version>
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
+ <version>4.0.1</version>
+ <scope>provided</scope>
</dependency>
<!-- JUNIT DEPENDENCY FOR TESTING -->
@@ -118,12 +100,6 @@
<version>2.8.5</version>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.eclipse.jetty.websocket</groupId>
- <artifactId>websocket-client</artifactId>
- <version>${jetty.version}</version>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
diff --git a/src/main/java/spark/Service.java b/src/main/java/spark/Service.java
index cee5fcc..e7ec9f4 100644
--- a/src/main/java/spark/Service.java
+++ b/src/main/java/spark/Service.java
@@ -30,10 +30,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.embeddedserver.EmbeddedServer;
-import spark.embeddedserver.EmbeddedServers;
-import spark.embeddedserver.jetty.websocket.WebSocketHandlerClassWrapper;
-import spark.embeddedserver.jetty.websocket.WebSocketHandlerInstanceWrapper;
-import spark.embeddedserver.jetty.websocket.WebSocketHandlerWrapper;
import spark.route.HttpMethod;
import spark.route.Routes;
import spark.route.ServletRoutes;
@@ -67,8 +63,6 @@ public final class Service extends Routable {
protected SslStores sslStores;
- protected Map<String, WebSocketHandlerWrapper> webSocketHandlers = null;
-
protected int maxThreads = -1;
protected int minThreads = -1;
protected int threadIdleTimeoutMillis = -1;
@@ -81,8 +75,6 @@ public final class Service extends Routable {
private CountDownLatch initLatch = new CountDownLatch(1);
private CountDownLatch stopLatch = new CountDownLatch(0);
- private Object embeddedServerIdentifier = EmbeddedServers.defaultIdentifier();
-
public final Redirect redirect;
public final StaticFiles staticFiles;
@@ -116,29 +108,6 @@ public final class Service extends Routable {
}
}
- /**
- * Set the identifier used to select the EmbeddedServer;
- * null for the default.
- *
- * @param obj the identifier passed to {@link EmbeddedServers}.
- */
- public synchronized void embeddedServerIdentifier(Object obj) {
- if (initialized) {
- throwBeforeRouteMappingException();
- }
- embeddedServerIdentifier = obj;
- }
-
- /**
- * Get the identifier used to select the EmbeddedServer;
- * null for the default.
- *
- * @param obj the identifier passed to {@link EmbeddedServers}.
- */
- public synchronized Object embeddedServerIdentifier() {
- return embeddedServerIdentifier;
- }
-
/**
* Set the IP address that Spark should listen on. If not called the default
* address is '0.0.0.0'. This has to be called before any route mapping is
@@ -186,117 +155,7 @@ public final class Service extends Routable {
}
}
- /**
- * Set the connection to be secure, using the specified keystore and
- * truststore. This has to be called before any route mapping is done. You
- * have to supply a keystore file, truststore file is optional (keystore
- * will be reused). By default, client certificates are not checked.
- * This method is only relevant when using embedded Jetty servers. It should
- * not be used if you are using Servlets, where you will need to secure the
- * connection in the servlet container
- *
- * @param keystoreFile The keystore file location as string
- * @param keystorePassword the password for the keystore
- * @param truststoreFile the truststore file location as string, leave null to reuse
- * keystore
- * @param truststorePassword the trust store password
- * @return the object with connection set to be secure
- */
- public synchronized Service secure(String keystoreFile,
- String keystorePassword,
- String truststoreFile,
- String truststorePassword) {
- return secure(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false);
- }
-
- /**
- * Set the connection to be secure, using the specified keystore and
- * truststore. This has to be called before any route mapping is done. You
- * have to supply a keystore file, truststore file is optional (keystore
- * will be reused). By default, client certificates are not checked.
- * This method is only relevant when using embedded Jetty servers. It should
- * not be used if you are using Servlets, where you will need to secure the
- * connection in the servlet container
- *
- * @param keystoreFile The keystore file location as string
- * @param keystorePassword the password for the keystore
- * @param certAlias the default certificate Alias
- * @param truststoreFile the truststore file location as string, leave null to reuse
- * keystore
- * @param truststorePassword the trust store password
- * @return the object with connection set to be secure
- */
- public synchronized Service secure(String keystoreFile,
- String keystorePassword,
- String certAlias,
- String truststoreFile,
- String truststorePassword) {
- return secure(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false);
- }
- /**
- * Set the connection to be secure, using the specified keystore and
- * truststore. This has to be called before any route mapping is done. You
- * have to supply a keystore file, truststore file is optional (keystore
- * will be reused).
- * This method is only relevant when using embedded Jetty servers. It should
- * not be used if you are using Servlets, where you will need to secure the
- * connection in the servlet container
- *
- * @param keystoreFile The keystore file location as string
- * @param keystorePassword the password for the keystore
- * @param truststoreFile the truststore file location as string, leave null to reuse
- * keystore
- * @param needsClientCert Whether to require client certificate to be supplied in
- * request
- * @param truststorePassword the trust store password
- * @return the object with connection set to be secure
- */
- public synchronized Service secure(String keystoreFile,
- String keystorePassword,
- String truststoreFile,
- String truststorePassword,
- boolean needsClientCert) {
- return secure(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert);
- }
-
- /**
- * Set the connection to be secure, using the specified keystore and
- * truststore. This has to be called before any route mapping is done. You
- * have to supply a keystore file, truststore file is optional (keystore
- * will be reused).
- * This method is only relevant when using embedded Jetty servers. It should
- * not be used if you are using Servlets, where you will need to secure the
- * connection in the servlet container
- *
- * @param keystoreFile The keystore file location as string
- * @param keystorePassword the password for the keystore
- * @param certAlias the default certificate Alias
- * @param truststoreFile the truststore file location as string, leave null to reuse
- * keystore
- * @param needsClientCert Whether to require client certificate to be supplied in
- * request
- * @param truststorePassword the trust store password
- * @return the object with connection set to be secure
- */
- public synchronized Service secure(String keystoreFile,
- String keystorePassword,
- String certAlias,
- String truststoreFile,
- String truststorePassword,
- boolean needsClientCert) {
- if (initialized) {
- throwBeforeRouteMappingException();
- }
-
- if (keystoreFile == null) {
- throw new IllegalArgumentException(
- "Must provide a keystore file to run secured");
- }
-
- sslStores = SslStores.create(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert);
- return this;
- }
/**
* Configures the embedded web server's thread pool.
@@ -395,44 +254,6 @@ public final class Service extends Routable {
return routes.remove(path, httpMethod);
}
- /**
- * Maps the given path to the given WebSocket handler class.
- * <p>
- * This is currently only available in the embedded server mode.
- *
- * @param path the WebSocket path.
- * @param handlerClass the handler class that will manage the WebSocket connection to the given path.
- */
- public void webSocket(String path, Class<?> handlerClass) {
- addWebSocketHandler(path, new WebSocketHandlerClassWrapper(handlerClass));
- }
-
- /**
- * Maps the given path to the given WebSocket handler instance.
- * <p>
- * This is currently only available in the embedded server mode.
- *
- * @param path the WebSocket path.
- * @param handler the handler instance that will manage the WebSocket connection to the given path.
- */
- public void webSocket(String path, Object handler) {
- addWebSocketHandler(path, new WebSocketHandlerInstanceWrapper(handler));
- }
-
- private synchronized void addWebSocketHandler(String path, WebSocketHandlerWrapper handlerWrapper) {
- if (initialized) {
- throwBeforeRouteMappingException();
- }
- if (isRunningFromServlet()) {
- throw new IllegalStateException("WebSockets are only supported in the embedded server");
- }
- requireNonNull(path, "WebSocket path cannot be null");
- if (webSocketHandlers == null) {
- webSocketHandlers = new HashMap<>();
- }
-
- webSocketHandlers.put(path, handlerWrapper);
- }
/**
* Sets the max idle timeout in milliseconds for WebSocket connections.
@@ -505,11 +326,6 @@ public final class Service extends Routable {
"This must be done before route mapping has begun");
}
- private boolean hasMultipleHandlers() {
- return webSocketHandlers != null;
- }
-
-
/**
* Stops the Spark server and clears all routes.
*/
@@ -612,42 +428,6 @@ public final class Service extends Routable {
initializeRouteMatcher();
- if (!isRunningFromServlet()) {
- new Thread(() -> {
- try {
- EmbeddedServers.initialize();
-
- if (embeddedServerIdentifier == null) {
- embeddedServerIdentifier = EmbeddedServers.defaultIdentifier();
- }
-
- server = EmbeddedServers.create(embeddedServerIdentifier,
- routes,
- exceptionMapper,
- staticFilesConfiguration,
- hasMultipleHandlers());
-
- server.configureWebSockets(webSocketHandlers, webSocketIdleTimeoutMillis);
-
- port = server.ignite(
- ipAddress,
- port,
- sslStores,
- maxThreads,
- minThreads,
- threadIdleTimeoutMillis);
- } catch (Exception e) {
- initExceptionHandler.accept(e);
- }
- try {
- initLatch.countDown();
- server.join();
- } catch (InterruptedException e) {
- LOG.error("server interrupted", e);
- Thread.currentThread().interrupt();
- }
- }).start();
- }
initialized = true;
}
}
@@ -660,15 +440,6 @@ public final class Service extends Routable {
}
}
- /**
- * @return The approximate number of currently active threads in the embedded Jetty server
- */
- public synchronized int activeThreadCount() {
- if (server != null) {
- return server.activeThreadCount();
- }
- return 0;
- }
//////////////////////////////////////////////////
// EXCEPTION mapper
diff --git a/src/main/java/spark/Spark.java b/src/main/java/spark/Spark.java
index bc5cdb3..9a825c8 100644
--- a/src/main/java/spark/Spark.java
+++ b/src/main/java/spark/Spark.java
@@ -1024,75 +1024,6 @@ public class Spark {
return getInstance().port();
}
- /**
- * Set the connection to be secure, using the specified keystore and
- * truststore. This has to be called before any route mapping is done. You
- * have to supply a keystore file, truststore file is optional (keystore
- * will be reused).
- * This method is only relevant when using embedded Jetty servers. It should
- * not be used if you are using Servlets, where you will need to secure the
- * connection in the servlet container
- *
- * @param keystoreFile The keystore file location as string
- * @param keystorePassword the password for the keystore
- * @param truststoreFile the truststore file location as string, leave null to reuse
- * keystore
- * @param truststorePassword the trust store password
- * @deprecated replaced by {@link #secure(String, String, String, String)}
- */
- public static void setSecure(String keystoreFile,
- String keystorePassword,
- String truststoreFile,
- String truststorePassword) {
- getInstance().secure(keystoreFile, keystorePassword, truststoreFile, truststorePassword);
- }
-
- /**
- * Set the connection to be secure, using the specified keystore and
- * truststore. This has to be called before any route mapping is done. You
- * have to supply a keystore file, truststore file is optional (keystore
- * will be reused).
- * This method is only relevant when using embedded Jetty servers. It should
- * not be used if you are using Servlets, where you will need to secure the
- * connection in the servlet container
- *
- * @param keystoreFile The keystore file location as string
- * @param keystorePassword the password for the keystore
- * @param truststoreFile the truststore file location as string, leave null to reuse
- * keystore
- * @param truststorePassword the trust store password
- */
- public static void secure(String keystoreFile,
- String keystorePassword,
- String truststoreFile,
- String truststorePassword) {
- getInstance().secure(keystoreFile, keystorePassword, truststoreFile, truststorePassword);
- }
-
- /**
- * Set the connection to be secure, using the specified keystore and
- * truststore. This has to be called before any route mapping is done. You
- * have to supply a keystore file, truststore file is optional (keystore
- * will be reused).
- * This method is only relevant when using embedded Jetty servers. It should
- * not be used if you are using Servlets, where you will need to secure the
- * connection in the servlet container
- *
- * @param keystoreFile The keystore file location as string
- * @param keystorePassword the password for the keystore
- * @param certAlias the default certificate Alias
- * @param truststoreFile the truststore file location as string, leave null to reuse
- * keystore
- * @param truststorePassword the trust store password
- */
- public static void secure(String keystoreFile,
- String keystorePassword,
- String certAlias,
- String truststoreFile,
- String truststorePassword) {
- getInstance().secure(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword);
- }
-
/**
* Overrides default exception handler during initialization phase
*
@@ -1102,78 +1033,6 @@ public class Spark {
getInstance().initExceptionHandler(initExceptionHandler);
}
- /**
- * Set the connection to be secure, using the specified keystore and
- * truststore. This has to be called before any route mapping is done. You
- * have to supply a keystore file, truststore file is optional (keystore
- * will be reused).
- * This method is only relevant when using embedded Jetty servers. It should
- * not be used if you are using Servlets, where you will need to secure the
- * connection in the servlet container
- *
- * @param keystoreFile The keystore file location as string
- * @param keystorePassword the password for the keystore
- * @param truststoreFile the truststore file location as string, leave null to reuse
- * keystore
- * @param needsClientCert Whether to require client certificate to be supplied in
- * request
- * @param truststorePassword the trust store password
- */
- public static void secure(String keystoreFile,
- String keystorePassword,
- String truststoreFile,
- String truststorePassword,
- boolean needsClientCert) {
- getInstance().secure(keystoreFile, keystorePassword, truststoreFile, truststorePassword, needsClientCert);
- }
-
- /**
- * Set the connection to be secure, using the specified keystore and
- * truststore. This has to be called before any route mapping is done. You
- * have to supply a keystore file, truststore file is optional (keystore
- * will be reused).
- * This method is only relevant when using embedded Jetty servers. It should
- * not be used if you are using Servlets, where you will need to secure the
- * connection in the servlet container
- *
- * @param keystoreFile The keystore file location as string
- * @param keystorePassword the password for the keystore
- * @param certAlias the default certificate Alias
- * @param truststoreFile the truststore file location as string, leave null to reuse
- * keystore
- * @param needsClientCert Whether to require client certificate to be supplied in
- * request
- * @param truststorePassword the trust store password
- */
- public static void secure(String keystoreFile,
- String keystorePassword,
- String certAlias,
- String truststoreFile,
- String truststorePassword,
- boolean needsClientCert) {
- getInstance().secure(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert);
- }
-
- /**
- * Configures the embedded web server's thread pool.
- *
- * @param maxThreads max nbr of threads.
- */
- public static void threadPool(int maxThreads) {
- getInstance().threadPool(maxThreads);
- }
-
- /**
- * Configures the embedded web server's thread pool.
- *
- * @param maxThreads max nbr of threads.
- * @param minThreads min nbr of threads.
- * @param idleTimeoutMillis thread idle timeout (ms).
- */
- public static void threadPool(int maxThreads, int minThreads, int idleTimeoutMillis) {
- getInstance().threadPool(maxThreads, minThreads, idleTimeoutMillis);
- }
-
/**
* Sets the folder in classpath serving static files. Observe: this method
* must be called before all other methods.
@@ -1224,22 +1083,6 @@ public class Spark {
////////////////
// Websockets //
- /**
- * Maps the given path to the given WebSocket handler.
- * <p>
- * This is currently only available in the embedded server mode.
- *
- * @param path the WebSocket path.
- * @param handler the handler class that will manage the WebSocket connection to the given path.
- */
- public static void webSocket(String path, Class<?> handler) {
- getInstance().webSocket(path, handler);
- }
-
- public static void webSocket(String path, Object handler) {
- getInstance().webSocket(path, handler);
- }
-
/**
* Sets the max idle timeout in milliseconds for WebSocket connections.
*
@@ -1277,13 +1120,6 @@ public class Spark {
getInstance().internalServerError(route);
}
- /**
- * Initializes the Spark server. SHOULD just be used when using the Websockets functionality.
- */
- public static void init() {
- getInstance().init();
- }
-
/**
* Constructs a ModelAndView with the provided model and view name
*
@@ -1301,13 +1137,4 @@ public class Spark {
public static List<RouteMatch> routes() {
return getInstance().routes();
}
-
- /**
- * @return The approximate number of currently active threads in the embedded Jetty server
- */
- public static int activeThreadCount() {
- return getInstance().activeThreadCount();
- }
-
-
}
diff --git a/src/main/java/spark/embeddedserver/EmbeddedServer.java b/src/main/java/spark/embeddedserver/EmbeddedServer.java
index 070d0be..bcf2845 100644
--- a/src/main/java/spark/embeddedserver/EmbeddedServer.java
+++ b/src/main/java/spark/embeddedserver/EmbeddedServer.java
@@ -19,7 +19,6 @@ package spark.embeddedserver;
import java.util.Map;
import java.util.Optional;
-import spark.embeddedserver.jetty.websocket.WebSocketHandlerWrapper;
import spark.ssl.SslStores;
/**
@@ -46,18 +45,6 @@ public interface EmbeddedServer {
int minThreads,
int threadIdleTimeoutMillis) throws Exception;
- /**
- * Configures the web sockets for the embedded server.
- *
- * @param webSocketHandlers - web socket handlers.
- * @param webSocketIdleTimeoutMillis - Optional WebSocket idle timeout (ms).
- */
- default void configureWebSockets(Map<String, WebSocketHandlerWrapper> webSocketHandlers,
- Optional<Integer> webSocketIdleTimeoutMillis) {
-
- NotSupportedException.raise(getClass().getSimpleName(), "Web Sockets");
- }
-
/**
* Joins the embedded server thread(s).
*/
diff --git a/src/main/java/spark/embeddedserver/EmbeddedServerFactory.java b/src/main/java/spark/embeddedserver/EmbeddedServerFactory.java
deleted file mode 100644
index dbd884b..0000000
--- a/src/main/java/spark/embeddedserver/EmbeddedServerFactory.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2016 - Per Wendel
- *
- * 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 spark.embeddedserver;
-
-import spark.ExceptionMapper;
-import spark.route.Routes;
-import spark.staticfiles.StaticFilesConfiguration;
-
-/**
- * @author Per Wendel
- */
-public interface EmbeddedServerFactory {
-
- @Deprecated
- default EmbeddedServer create(Routes routeMatcher, StaticFilesConfiguration staticFilesConfiguration, boolean hasMultipleHandler) {
- return create(routeMatcher, staticFilesConfiguration, ExceptionMapper.getServletInstance(), hasMultipleHandler);
- }
-
- /**
- * Creates an embedded server instance.
- *
- * @param routeMatcher The route matcher
- * @param staticFilesConfiguration The static files configuration object
- * @param hasMultipleHandler true if other handlers exist
- * @return the created instance
- */
- public EmbeddedServer create(Routes routeMatcher, StaticFilesConfiguration staticFilesConfiguration, ExceptionMapper exceptionMapper, boolean hasMultipleHandler);
-}
diff --git a/src/main/java/spark/embeddedserver/EmbeddedServers.java b/src/main/java/spark/embeddedserver/EmbeddedServers.java
deleted file mode 100644
index 9e09d98..0000000
--- a/src/main/java/spark/embeddedserver/EmbeddedServers.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright 2016 - Per Wendel
- *
- * 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 spark.embeddedserver;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import spark.ExceptionMapper;
-import spark.embeddedserver.jetty.EmbeddedJettyFactory;
-import spark.route.Routes;
-import spark.staticfiles.StaticFilesConfiguration;
-
-/**
- * Holds and uses the factories for creating different Embedded servers.
- */
-public class EmbeddedServers {
-
- // Default alternatives.
- public enum Identifiers {
- JETTY
- }
-
- private static Map<Object, EmbeddedServerFactory> factories = new HashMap<>();
-
- public static void initialize() {
- if (!factories.containsKey(Identifiers.JETTY)) {
- add(Identifiers.JETTY, new EmbeddedJettyFactory());
- }
- }
-
- public static Identifiers defaultIdentifier() {
- return Identifiers.JETTY;
- }
-
- @Deprecated
- public static EmbeddedServer create(Object identifier,
- Routes routeMatcher,
- StaticFilesConfiguration staticFilesConfiguration,
- boolean multipleHandlers) {
-
- return create(identifier,
- routeMatcher,
- ExceptionMapper.getServletInstance(),
- staticFilesConfiguration,
- multipleHandlers);
- }
-
- /**
- * Creates an embedded server of type corresponding to the provided identifier.
- *
- * @param identifier the identifier
- * @param routeMatcher the route matcher
- * @param staticFilesConfiguration the static files configuration object
- * @param multipleHandlers true if other handlers exist
- * @return the created EmbeddedServer object
- */
- public static EmbeddedServer create(Object identifier,
- Routes routeMatcher,
- ExceptionMapper exceptionMapper,
- StaticFilesConfiguration staticFilesConfiguration,
- boolean multipleHandlers) {
-
- EmbeddedServerFactory factory = factories.get(identifier);
-
- if (factory != null) {
- return factory.create(routeMatcher, staticFilesConfiguration, exceptionMapper, multipleHandlers);
- } else {
- throw new RuntimeException("No embedded server matching the identifier");
- }
- }
-
- /**
- * Adds an Embedded server factory for the provided identifier.
- *
- * @param identifier the identifier
- * @param factory the factory
- */
- public static void add(Object identifier, EmbeddedServerFactory factory) {
- factories.put(identifier, factory);
- }
-
-}
diff --git a/src/main/java/spark/embeddedserver/NotSupportedException.java b/src/main/java/spark/embeddedserver/NotSupportedException.java
deleted file mode 100644
index 8c6ff30..0000000
--- a/src/main/java/spark/embeddedserver/NotSupportedException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2016 - Per Wendel
- *
- * 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 spark.embeddedserver;
-
-/**
- * Used to indicate that a feature is not supported for the specific embedded server.
- */
-public class NotSupportedException extends RuntimeException {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * Raises a NotSupportedException for the provided class name and feature name.
- *
- * @param clazz the class name
- * @param feature the feature name
- */
- public static void raise(String clazz, String feature) {
- throw new NotSupportedException(clazz, feature);
- }
-
- private NotSupportedException(String clazz, String feature) {
- super("'" + clazz + "' doesn't support '" + feature + "'");
-
- }
-
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/EmbeddedJettyFactory.java b/src/main/java/spark/embeddedserver/jetty/EmbeddedJettyFactory.java
deleted file mode 100644
index d51332b..0000000
--- a/src/main/java/spark/embeddedserver/jetty/EmbeddedJettyFactory.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2016 - Per Wendel
- *
- * 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 spark.embeddedserver.jetty;
-
-import org.eclipse.jetty.util.thread.ThreadPool;
-
-import spark.ExceptionMapper;
-import spark.embeddedserver.EmbeddedServer;
-import spark.embeddedserver.EmbeddedServerFactory;
-import spark.http.matching.MatcherFilter;
-import spark.route.Routes;
-import spark.staticfiles.StaticFilesConfiguration;
-
-/**
- * Creates instances of embedded jetty containers.
- */
-public class EmbeddedJettyFactory implements EmbeddedServerFactory {
- private final JettyServerFactory serverFactory;
- private ThreadPool threadPool;
- private boolean httpOnly = true;
-
- public EmbeddedJettyFactory() {
- this.serverFactory = new JettyServer();
- }
-
- public EmbeddedJettyFactory(JettyServerFactory serverFactory) {
- this.serverFactory = serverFactory;
- }
-
- public EmbeddedServer create(Routes routeMatcher,
- StaticFilesConfiguration staticFilesConfiguration,
- ExceptionMapper exceptionMapper,
- boolean hasMultipleHandler) {
- MatcherFilter matcherFilter = new MatcherFilter(routeMatcher, staticFilesConfiguration, exceptionMapper, false, hasMultipleHandler);
- matcherFilter.init(null);
-
- JettyHandler handler = new JettyHandler(matcherFilter);
- handler.getSessionCookieConfig().setHttpOnly(httpOnly);
- return new EmbeddedJettyServer(serverFactory, handler).withThreadPool(threadPool);
- }
-
- /**
- * Sets optional thread pool for jetty server. This is useful for overriding the default thread pool
- * behaviour for example io.dropwizard.metrics.jetty9.InstrumentedQueuedThreadPool.
- *
- * @param threadPool thread pool
- * @return Builder pattern - returns this instance
- */
- public EmbeddedJettyFactory withThreadPool(ThreadPool threadPool) {
- this.threadPool = threadPool;
- return this;
- }
-
- public EmbeddedJettyFactory withHttpOnly(boolean httpOnly) {
- this.httpOnly = httpOnly;
- return this;
- }
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/EmbeddedJettyServer.java b/src/main/java/spark/embeddedserver/jetty/EmbeddedJettyServer.java
deleted file mode 100644
index 200765d..0000000
--- a/src/main/java/spark/embeddedserver/jetty/EmbeddedJettyServer.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright 2011- Per Wendel
- *
- * 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 spark.embeddedserver.jetty;
-
-import java.io.IOException;
-import java.net.ServerSocket;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-
-import org.eclipse.jetty.server.Connector;
-import org.eclipse.jetty.server.Handler;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.handler.HandlerList;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.util.thread.ThreadPool;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import spark.embeddedserver.EmbeddedServer;
-import spark.embeddedserver.jetty.websocket.WebSocketHandlerWrapper;
-import spark.embeddedserver.jetty.websocket.WebSocketServletContextHandlerFactory;
-import spark.ssl.SslStores;
-
-/**
- * Spark server implementation
- *
- * @author Per Wendel
- */
-public class EmbeddedJettyServer implements EmbeddedServer {
-
- private static final int SPARK_DEFAULT_PORT = 4567;
- private static final String NAME = "Spark";
-
- private final JettyServerFactory serverFactory;
- private final Handler handler;
- private Server server;
-
- private final Logger logger = LoggerFactory.getLogger(this.getClass());
-
- private Map<String, WebSocketHandlerWrapper> webSocketHandlers;
- private Optional<Integer> webSocketIdleTimeoutMillis;
-
- private ThreadPool threadPool = null;
-
- public EmbeddedJettyServer(JettyServerFactory serverFactory, Handler handler) {
- this.serverFactory = serverFactory;
- this.handler = handler;
- }
-
- @Override
- public void configureWebSockets(Map<String, WebSocketHandlerWrapper> webSocketHandlers,
- Optional<Integer> webSocketIdleTimeoutMillis) {
-
- this.webSocketHandlers = webSocketHandlers;
- this.webSocketIdleTimeoutMillis = webSocketIdleTimeoutMillis;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
-
- public int ignite(String host,
- int port,
- SslStores sslStores,
- int maxThreads,
- int minThreads,
- int threadIdleTimeoutMillis) throws Exception {
-
- boolean hasCustomizedConnectors = false;
-
- if (port == 0) {
- try (ServerSocket s = new ServerSocket(0)) {
- port = s.getLocalPort();
- } catch (IOException e) {
- logger.error("Could not get first available port (port set to 0), using default: {}", SPARK_DEFAULT_PORT);
- port = SPARK_DEFAULT_PORT;
- }
- }
-
- // Create instance of jetty server with either default or supplied queued thread pool
- if(threadPool == null) {
- server = serverFactory.create(maxThreads, minThreads, threadIdleTimeoutMillis);
- } else {
- server = serverFactory.create(threadPool);
- }
-
- ServerConnector connector;
-
- if (sslStores == null) {
- connector = SocketConnectorFactory.createSocketConnector(server, host, port);
- } else {
- connector = SocketConnectorFactory.createSecureSocketConnector(server, host, port, sslStores);
- }
-
- Connector previousConnectors[] = server.getConnectors();
- server = connector.getServer();
- if (previousConnectors.length != 0) {
- server.setConnectors(previousConnectors);
- hasCustomizedConnectors = true;
- } else {
- server.setConnectors(new Connector[] {connector});
- }
-
- ServletContextHandler webSocketServletContextHandler =
- WebSocketServletContextHandlerFactory.create(webSocketHandlers, webSocketIdleTimeoutMillis);
-
- // Handle web socket routes
- if (webSocketServletContextHandler == null) {
- server.setHandler(handler);
- } else {
- List<Handler> handlersInList = new ArrayList<>();
- handlersInList.add(handler);
-
- // WebSocket handler must be the last one
- if (webSocketServletContextHandler != null) {
- handlersInList.add(webSocketServletContextHandler);
- }
-
- HandlerList handlers = new HandlerList();
- handlers.setHandlers(handlersInList.toArray(new Handler[handlersInList.size()]));
- server.setHandler(handlers);
- }
-
- logger.info("== {} has ignited ...", NAME);
- if (hasCustomizedConnectors) {
- logger.info(">> Listening on Custom Server ports!");
- } else {
- logger.info(">> Listening on {}:{}", host, port);
- }
-
- server.start();
- return port;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void join() throws InterruptedException {
- server.join();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void extinguish() {
- logger.info(">>> {} shutting down ...", NAME);
- try {
- if (server != null) {
- server.stop();
- }
- } catch (Exception e) {
- logger.error("stop failed", e);
- System.exit(100); // NOSONAR
- }
- logger.info("done");
- }
-
- @Override
- public int activeThreadCount() {
- if (server == null) {
- return 0;
- }
- return server.getThreadPool().getThreads() - server.getThreadPool().getIdleThreads();
- }
-
- /**
- * Sets optional thread pool for jetty server. This is useful for overriding the default thread pool
- * behaviour for example io.dropwizard.metrics.jetty9.InstrumentedQueuedThreadPool.
- * @param threadPool thread pool
- * @return Builder pattern - returns this instance
- */
- public EmbeddedJettyServer withThreadPool(ThreadPool threadPool) {
- this.threadPool = threadPool;
- return this;
- }
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/HttpRequestWrapper.java b/src/main/java/spark/embeddedserver/jetty/HttpRequestWrapper.java
deleted file mode 100644
index 23198d9..0000000
--- a/src/main/java/spark/embeddedserver/jetty/HttpRequestWrapper.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright 2015 - Per Wendel
- *
- * 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 spark.embeddedserver.jetty;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-
-import javax.servlet.ReadListener;
-import javax.servlet.ServletInputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-
-import spark.utils.IOUtils;
-
-/**
- * Http request wrapper. Wraps the request so 'getInputStream()' can be called multiple times.
- * Also has methods for checking if request has been consumed.
- */
-public class HttpRequestWrapper extends HttpServletRequestWrapper {
- private byte[] cachedBytes;
- private boolean notConsumed = false;
-
- public HttpRequestWrapper(HttpServletRequest request) {
- super(request);
- }
-
- public boolean notConsumed() {
- return notConsumed;
- }
-
- public void notConsumed(boolean notConsumed) {
- this.notConsumed = notConsumed;
- }
-
- @Override
- public ServletInputStream getInputStream() throws IOException {
- HttpServletRequest request = (HttpServletRequest) super.getRequest();
-
- // disable stream cache for chunked transfer encoding
- String transferEncoding = request.getHeader("Transfer-Encoding");
- if ("chunked".equals(transferEncoding)) {
- return super.getInputStream();
- }
-
- // disable stream cache for multipart/form-data file upload
- // -> upload might be very large and might lead to out-of-memory error if we try to cache the bytes
- String contentType = request.getHeader("Content-Type");
- if (contentType != null && contentType.startsWith("multipart/form-data")) {
- return super.getInputStream();
- }
-
- if (cachedBytes == null) {
- cacheInputStream();
- }
- return new CachedServletInputStream();
- }
-
- private void cacheInputStream() throws IOException {
- cachedBytes = IOUtils.toByteArray(super.getInputStream());
- }
-
- private class CachedServletInputStream extends ServletInputStream {
- private ByteArrayInputStream byteArrayInputStream;
-
- public CachedServletInputStream() {
- byteArrayInputStream = new ByteArrayInputStream(cachedBytes);
- }
-
- @Override
- public int read() {
- return byteArrayInputStream.read();
- }
-
- @Override
- public int available() {
- return byteArrayInputStream.available();
- }
-
- @Override
- public boolean isFinished() {
- return available() <= 0;
- }
-
- @Override
- public boolean isReady() {
- return available() >= 0;
- }
-
- @Override
- public void setReadListener(ReadListener readListener) {
- }
- }
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/JettyHandler.java b/src/main/java/spark/embeddedserver/jetty/JettyHandler.java
deleted file mode 100644
index ef0c432..0000000
--- a/src/main/java/spark/embeddedserver/jetty/JettyHandler.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright 2011- Per Wendel
- *
- * 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 spark.embeddedserver.jetty;
-
-import java.io.IOException;
-
-import javax.servlet.Filter;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.eclipse.jetty.server.Request;
-import org.eclipse.jetty.server.session.SessionHandler;
-
-/**
- * Simple Jetty Handler
- *
- * @author Per Wendel
- */
-public class JettyHandler extends SessionHandler {
-
- private Filter filter;
-
- public JettyHandler(Filter filter) {
- this.filter = filter;
- }
-
- @Override
- public void doHandle(
- String target,
- Request baseRequest,
- HttpServletRequest request,
- HttpServletResponse response) throws IOException, ServletException {
-
- HttpRequestWrapper wrapper = new HttpRequestWrapper(request);
- filter.doFilter(wrapper, response, null);
-
- if (wrapper.notConsumed()) {
- baseRequest.setHandled(false);
- } else {
- baseRequest.setHandled(true);
- }
-
- }
-
-}
\ No newline at end of file
diff --git a/src/main/java/spark/embeddedserver/jetty/JettyServer.java b/src/main/java/spark/embeddedserver/jetty/JettyServer.java
deleted file mode 100644
index 45ac18c..0000000
--- a/src/main/java/spark/embeddedserver/jetty/JettyServer.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright 2015 - Per Wendel
- *
- * 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 spark.embeddedserver.jetty;
-
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.util.thread.QueuedThreadPool;
-import org.eclipse.jetty.util.thread.ThreadPool;
-
-/**
- * Creates Jetty Server instances.
- */
-class JettyServer implements JettyServerFactory {
-
- /**
- * Creates a Jetty server.
- *
- * @param maxThreads maxThreads
- * @param minThreads minThreads
- * @param threadTimeoutMillis threadTimeoutMillis
- * @return a new jetty server instance
- */
- public Server create(int maxThreads, int minThreads, int threadTimeoutMillis) {
- Server server;
-
- if (maxThreads > 0) {
- int max = maxThreads;
- int min = (minThreads > 0) ? minThreads : 8;
- int idleTimeout = (threadTimeoutMillis > 0) ? threadTimeoutMillis : 60000;
-
- server = new Server(new QueuedThreadPool(max, min, idleTimeout));
- } else {
- server = new Server();
- }
-
- return server;
- }
-
- /**
- * Creates a Jetty server with supplied thread pool
- * @param threadPool thread pool
- * @return a new jetty server instance
- */
- @Override
- public Server create(ThreadPool threadPool) {
- return threadPool != null ? new Server(threadPool) : new Server();
- }
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/JettyServerFactory.java b/src/main/java/spark/embeddedserver/jetty/JettyServerFactory.java
deleted file mode 100644
index 8d3c408..0000000
--- a/src/main/java/spark/embeddedserver/jetty/JettyServerFactory.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package spark.embeddedserver.jetty;
-
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.util.thread.ThreadPool;
-
-/**
- * This interface can be implemented to provide custom Jetty server instances
- * with specific settings or features.
- */
-public interface JettyServerFactory {
- /**
- * Creates a Jetty server.
- *
- * @param maxThreads maxThreads
- * @param minThreads minThreads
- * @param threadTimeoutMillis threadTimeoutMillis
- * @return a new jetty server instance
- */
- Server create(int maxThreads, int minThreads, int threadTimeoutMillis);
-
- Server create(ThreadPool threadPool);
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/SocketConnectorFactory.java b/src/main/java/spark/embeddedserver/jetty/SocketConnectorFactory.java
deleted file mode 100644
index 11f5f45..0000000
--- a/src/main/java/spark/embeddedserver/jetty/SocketConnectorFactory.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright 2015 - Per Wendel
- *
- * 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 spark.embeddedserver.jetty;
-
-import java.util.concurrent.TimeUnit;
-
-import org.eclipse.jetty.server.ForwardedRequestCustomizer;
-import org.eclipse.jetty.server.HttpConfiguration;
-import org.eclipse.jetty.server.HttpConnectionFactory;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.util.ssl.SslContextFactory;
-
-import spark.ssl.SslStores;
-import spark.utils.Assert;
-
-/**
- * Creates socket connectors.
- */
-public class SocketConnectorFactory {
-
- /**
- * Creates an ordinary, non-secured Jetty server jetty.
- *
- * @param server Jetty server
- * @param host host
- * @param port port
- * @return - a server jetty
- */
- public static ServerConnector createSocketConnector(Server server, String host, int port) {
- Assert.notNull(server, "'server' must not be null");
- Assert.notNull(host, "'host' must not be null");
-
- HttpConnectionFactory httpConnectionFactory = createHttpConnectionFactory();
- ServerConnector connector = new ServerConnector(server, httpConnectionFactory);
- initializeConnector(connector, host, port);
- return connector;
- }
-
- /**
- * Creates a ssl jetty socket jetty. Keystore required, truststore
- * optional. If truststore not specified keystore will be reused.
- *
- * @param server Jetty server
- * @param sslStores the security sslStores.
- * @param host host
- * @param port port
- * @return a ssl socket jetty
- */
- public static ServerConnector createSecureSocketConnector(Server server,
- String host,
- int port,
- SslStores sslStores) {
- Assert.notNull(server, "'server' must not be null");
- Assert.notNull(host, "'host' must not be null");
- Assert.notNull(sslStores, "'sslStores' must not be null");
-
- SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
- sslContextFactory.setKeyStorePath(sslStores.keystoreFile());
-
- if (sslStores.keystorePassword() != null) {
- sslContextFactory.setKeyStorePassword(sslStores.keystorePassword());
- }
-
- if (sslStores.certAlias() != null) {
- sslContextFactory.setCertAlias(sslStores.certAlias());
- }
-
- if (sslStores.trustStoreFile() != null) {
- sslContextFactory.setTrustStorePath(sslStores.trustStoreFile());
- }
-
- if (sslStores.trustStorePassword() != null) {
- sslContextFactory.setTrustStorePassword(sslStores.trustStorePassword());
- }
-
- if (sslStores.needsClientCert()) {
- sslContextFactory.setNeedClientAuth(true);
- sslContextFactory.setWantClientAuth(true);
- }
-
- HttpConnectionFactory httpConnectionFactory = createHttpConnectionFactory();
-
- ServerConnector connector = new ServerConnector(server, sslContextFactory, httpConnectionFactory);
- initializeConnector(connector, host, port);
- return connector;
- }
-
- private static void initializeConnector(ServerConnector connector, String host, int port) {
- // Set some timeout options to make debugging easier.
- connector.setIdleTimeout(TimeUnit.HOURS.toMillis(1));
- connector.setHost(host);
- connector.setPort(port);
- }
-
- private static HttpConnectionFactory createHttpConnectionFactory() {
- HttpConfiguration httpConfig = new HttpConfiguration();
- httpConfig.setSecureScheme("https");
- httpConfig.addCustomizer(new ForwardedRequestCustomizer());
- return new HttpConnectionFactory(httpConfig);
- }
-
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketCreatorFactory.java b/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketCreatorFactory.java
deleted file mode 100644
index fae3580..0000000
--- a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketCreatorFactory.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright 2011- Per Wendel
- *
- * 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 spark.embeddedserver.jetty.websocket;
-
-import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
-import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
-import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
-
-import static java.util.Objects.requireNonNull;
-
-/**
- * Factory class to create {@link WebSocketCreator} implementations that
- * delegate to the given handler class.
- *
- * @author Ignasi Barrera
- */
-public class WebSocketCreatorFactory {
-
- /**
- * Creates a {@link WebSocketCreator} that uses the given handler class/instance for
- * the WebSocket connections.
- *
- * @param handlerWrapper The wrapped handler to use to manage WebSocket connections.
- * @return The WebSocketCreator.
- */
- public static WebSocketCreator create(WebSocketHandlerWrapper handlerWrapper) {
- return new SparkWebSocketCreator(handlerWrapper.getHandler());
- }
-
- // Package protected to be visible to the unit tests
- static class SparkWebSocketCreator implements WebSocketCreator {
- private final Object handler;
-
- private SparkWebSocketCreator(Object handler) {
- this.handler = requireNonNull(handler, "handler cannot be null");
- }
-
- @Override
- public Object createWebSocket(ServletUpgradeRequest request,
- ServletUpgradeResponse response) {
- return handler;
- }
-
- Object getHandler() {
- return handler;
- }
- }
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketHandlerClassWrapper.java b/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketHandlerClassWrapper.java
deleted file mode 100644
index 4264f55..0000000
--- a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketHandlerClassWrapper.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package spark.embeddedserver.jetty.websocket;
-
-import static java.util.Objects.requireNonNull;
-
-public class WebSocketHandlerClassWrapper implements WebSocketHandlerWrapper {
-
- private final Class<?> handlerClass;
-
- public WebSocketHandlerClassWrapper(Class<?> handlerClass) {
- requireNonNull(handlerClass, "WebSocket handler class cannot be null");
- WebSocketHandlerWrapper.validateHandlerClass(handlerClass);
- this.handlerClass = handlerClass;
- }
- @Override
- public Object getHandler() {
- try {
- return handlerClass.newInstance();
- } catch (InstantiationException | IllegalAccessException ex) {
- throw new RuntimeException("Could not instantiate websocket handler", ex);
- }
- }
-
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketHandlerInstanceWrapper.java b/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketHandlerInstanceWrapper.java
deleted file mode 100644
index ef0f82e..0000000
--- a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketHandlerInstanceWrapper.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package spark.embeddedserver.jetty.websocket;
-
-import static java.util.Objects.requireNonNull;
-
-public class WebSocketHandlerInstanceWrapper implements WebSocketHandlerWrapper {
-
- private final Object handler;
-
- public WebSocketHandlerInstanceWrapper(Object handler) {
- requireNonNull(handler, "WebSocket handler cannot be null");
- WebSocketHandlerWrapper.validateHandlerClass(handler.getClass());
- this.handler = handler;
- }
-
- @Override
- public Object getHandler() {
- return handler;
- }
-
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketHandlerWrapper.java b/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketHandlerWrapper.java
deleted file mode 100644
index 6b2c0de..0000000
--- a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketHandlerWrapper.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package spark.embeddedserver.jetty.websocket;
-
-import org.eclipse.jetty.websocket.api.WebSocketListener;
-import org.eclipse.jetty.websocket.api.annotations.WebSocket;
-
-/**
- * A wrapper for web socket handler classes/instances.
- */
-public interface WebSocketHandlerWrapper {
-
- /**
- * Gets the actual handler - if necessary, instantiating an object.
- *
- * @return The handler instance.
- */
- Object getHandler();
-
- static void validateHandlerClass(Class<?> handlerClass) {
- boolean valid = WebSocketListener.class.isAssignableFrom(handlerClass)
- || handlerClass.isAnnotationPresent(WebSocket.class);
- if (!valid) {
- throw new IllegalArgumentException(
- "WebSocket handler must implement 'WebSocketListener' or be annotated as '@WebSocket'");
- }
- }
-
-}
diff --git a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketServletContextHandlerFactory.java b/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketServletContextHandlerFactory.java
deleted file mode 100644
index 3d56659..0000000
--- a/src/main/java/spark/embeddedserver/jetty/websocket/WebSocketServletContextHandlerFactory.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright 2015 - Per Wendel
- *
- * 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 spark.embeddedserver.jetty.websocket;
-
-import java.util.Map;
-import java.util.Optional;
-
-import org.eclipse.jetty.http.pathmap.ServletPathSpec;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.websocket.server.NativeWebSocketConfiguration;
-import org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter;
-import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Creates websocket servlet context handlers.
- */
-public class WebSocketServletContextHandlerFactory {
-
- private static final Logger logger = LoggerFactory.getLogger(WebSocketServletContextHandlerFactory.class);
-
- /**
- * Creates a new websocket servlet context handler.
- *
- * @param webSocketHandlers webSocketHandlers
- * @param webSocketIdleTimeoutMillis webSocketIdleTimeoutMillis
- * @return a new websocket servlet context handler or 'null' if creation failed.
- */
- public static ServletContextHandler create(Map<String, WebSocketHandlerWrapper> webSocketHandlers,
- Optional<Integer> webSocketIdleTimeoutMillis) {
- ServletContextHandler webSocketServletContextHandler = null;
- if (webSocketHandlers != null) {
- try {
- webSocketServletContextHandler = new ServletContextHandler(null, "/", true, false);
- WebSocketUpgradeFilter webSocketUpgradeFilter = WebSocketUpgradeFilter.configureContext(webSocketServletContextHandler);
- if (webSocketIdleTimeoutMillis.isPresent()) {
- webSocketUpgradeFilter.getFactory().getPolicy().setIdleTimeout(webSocketIdleTimeoutMillis.get());
- }
- // Since we are configuring WebSockets before the ServletContextHandler and WebSocketUpgradeFilter is
- // even initialized / started, then we have to pre-populate the configuration that will eventually
- // be used by Jetty's WebSocketUpgradeFilter.
- NativeWebSocketConfiguration webSocketConfiguration = (NativeWebSocketConfiguration) webSocketServletContextHandler
- .getServletContext().getAttribute(NativeWebSocketConfiguration.class.getName());
- for (String path : webSocketHandlers.keySet()) {
- WebSocketCreator webSocketCreator = WebSocketCreatorFactory.create(webSocketHandlers.get(path));
- webSocketConfiguration.addMapping(new ServletPathSpec(path), webSocketCreator);
- }
- } catch (Exception ex) {
- logger.error("creation of websocket context handler failed.", ex);
- webSocketServletContextHandler = null;
- }
- }
- return webSocketServletContextHandler;
- }
-
-}
diff --git a/src/main/java/spark/http/matching/MatcherFilter.java b/src/main/java/spark/http/matching/MatcherFilter.java
index 3fa05be..482c9bf 100644
--- a/src/main/java/spark/http/matching/MatcherFilter.java
+++ b/src/main/java/spark/http/matching/MatcherFilter.java
@@ -32,7 +32,6 @@ import spark.ExceptionMapper;
import spark.HaltException;
import spark.RequestResponseFactory;
import spark.Response;
-import spark.embeddedserver.jetty.HttpRequestWrapper;
import spark.route.HttpMethod;
import spark.serialization.SerializerChain;
import spark.staticfiles.StaticFilesConfiguration;
@@ -156,13 +155,6 @@ public class MatcherFilter implements Filter {
body.set("");
}
- if (body.notSet() && hasOtherHandlers) {
- if (servletRequest instanceof HttpRequestWrapper) {
- ((HttpRequestWrapper) servletRequest).notConsumed(true);
- return;
- }
- }
-
if (body.notSet()) {
LOG.info("The requested route [{}] has not been mapped in Spark for {}: [{}]",
uri, ACCEPT_TYPE_REQUEST_MIME_HEADER, acceptType);
diff --git a/src/main/java/spark/utils/urldecoding/Utf8Appendable.java b/src/main/java/spark/utils/urldecoding/Utf8Appendable.java
index 359b822..485dc60 100644
--- a/src/main/java/spark/utils/urldecoding/Utf8Appendable.java
+++ b/src/main/java/spark/utils/urldecoding/Utf8Appendable.java
@@ -88,7 +88,7 @@ public abstract class Utf8Appendable {
_appendable.append(REPLACEMENT);
int state = _state;
_state = UTF8_ACCEPT;
- throw new org.eclipse.jetty.util.Utf8Appendable.NotUtf8Exception("char appended in state " + state);
+ throw new IOException("char appended in state " + state);
}
}
@@ -145,7 +145,7 @@ public abstract class Utf8Appendable {
_codep = 0;
_state = UTF8_ACCEPT;
_appendable.append(REPLACEMENT);
- throw new org.eclipse.jetty.util.Utf8Appendable.NotUtf8Exception(reason);
+ throw new IOException(reason);
default:
_state = next;
@@ -174,7 +174,6 @@ public abstract class Utf8Appendable {
} catch (IOException e) {
throw new RuntimeException(e);
}
- throw new org.eclipse.jetty.util.Utf8Appendable.NotUtf8Exception("incomplete UTF8 sequence");
}
}
diff --git a/src/test/java/spark/BodyAvailabilityTest.java b/src/test/java/spark/BodyAvailabilityTest.java
deleted file mode 100644
index dfc112a..0000000
--- a/src/test/java/spark/BodyAvailabilityTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-package spark;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import spark.util.SparkTestUtil;
-
-import static spark.Spark.after;
-import static spark.Spark.before;
-import static spark.Spark.post;
-
-public class BodyAvailabilityTest {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(BodyAvailabilityTest.class);
-
- private static final String BODY_CONTENT = "the body content";
-
- private static SparkTestUtil testUtil;
-
- private final int HTTP_OK = 200;
-
- private static String beforeBody = null;
- private static String routeBody = null;
- private static String afterBody = null;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
-
- beforeBody = null;
- routeBody = null;
- afterBody = null;
- }
-
- @BeforeClass
- public static void setup() {
- LOGGER.debug("setup()");
-
- testUtil = new SparkTestUtil(4567);
-
- beforeBody = null;
- routeBody = null;
- afterBody = null;
-
- before("/hello", (req, res) -> {
- LOGGER.debug("before-req.body() = " + req.body());
- beforeBody = req.body();
- });
-
- post("/hello", (req, res) -> {
- LOGGER.debug("get-req.body() = " + req.body());
- routeBody = req.body();
- return req.body();
- });
-
- after("/hello", (req, res) -> {
- LOGGER.debug("after-before-req.body() = " + req.body());
- afterBody = req.body();
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void testPost() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("POST", "/hello", BODY_CONTENT);
- LOGGER.info(response.body);
- Assert.assertEquals(HTTP_OK, response.status);
- Assert.assertTrue(response.body.contains(BODY_CONTENT));
-
- Assert.assertEquals(BODY_CONTENT, beforeBody);
- Assert.assertEquals(BODY_CONTENT, routeBody);
- Assert.assertEquals(BODY_CONTENT, afterBody);
- }
-}
\ No newline at end of file
diff --git a/src/test/java/spark/BooksIntegrationTest.java b/src/test/java/spark/BooksIntegrationTest.java
deleted file mode 100644
index 31278a8..0000000
--- a/src/test/java/spark/BooksIntegrationTest.java
+++ /dev/null
@@ -1,194 +0,0 @@
-package spark;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static spark.Spark.after;
-import static spark.Spark.before;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.net.MalformedURLException;
-import java.net.ProtocolException;
-import java.net.URL;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import spark.examples.books.Books;
-import spark.utils.IOUtils;
-
-public class BooksIntegrationTest {
-
- private static int PORT = 4567;
-
- private static String AUTHOR = "FOO";
- private static String TITLE = "BAR";
- private static String NEW_TITLE = "SPARK";
-
- private String bookId;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- }
-
- @After
- public void clearBooks() {
- Books.books.clear();
- }
-
- @BeforeClass
- public static void setup() {
- before((request, response) -> {
- response.header("FOZ", "BAZ");
- });
-
- Books.main(null);
-
- after((request, response) -> {
- response.header("FOO", "BAR");
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void canCreateBook() {
- UrlResponse response = createBookViaPOST();
-
- assertNotNull(response);
- assertNotNull(response.body);
- assertTrue(Integer.valueOf(response.body) > 0);
- assertEquals(201, response.status);
- }
-
- @Test
- public void canListBooks() {
- bookId = createBookViaPOST().body.trim();
-
- UrlResponse response = doMethod("GET", "/books", null);
-
- assertNotNull(response);
- String body = response.body.trim();
- assertNotNull(body);
- assertTrue(Integer.valueOf(body) > 0);
- assertEquals(200, response.status);
- assertTrue(response.body.contains(bookId));
- }
-
- @Test
- public void canGetBook() {
- bookId = createBookViaPOST().body.trim();
-
- UrlResponse response = doMethod("GET", "/books/" + bookId, null);
-
- String result = response.body;
- assertNotNull(response);
- assertNotNull(response.body);
- assertEquals(200, response.status);
- assertTrue(result.contains(AUTHOR));
- assertTrue(result.contains(TITLE));
- assertTrue(beforeFilterIsSet(response));
- assertTrue(afterFilterIsSet(response));
- }
-
- @Test
- public void canUpdateBook() {
- bookId = createBookViaPOST().body.trim();
-
- UrlResponse response = updateBook();
-
- String result = response.body;
- assertNotNull(response);
- assertNotNull(response.body);
- assertEquals(200, response.status);
- assertTrue(result.contains(bookId));
- assertTrue(result.contains("updated"));
- }
-
- @Test
- public void canGetUpdatedBook() {
- bookId = createBookViaPOST().body.trim();
- updateBook();
-
- UrlResponse response = doMethod("GET", "/books/" + bookId, null);
-
- String result = response.body;
- assertNotNull(response);
- assertNotNull(response.body);
- assertEquals(200, response.status);
- assertTrue(result.contains(AUTHOR));
- assertTrue(result.contains(NEW_TITLE));
- }
-
- @Test
- public void canDeleteBook() {
- bookId = createBookViaPOST().body.trim();
-
- UrlResponse response = doMethod("DELETE", "/books/" + bookId, null);
-
- String result = response.body;
- assertNotNull(response);
- assertNotNull(response.body);
- assertEquals(200, response.status);
- assertTrue(result.contains(bookId));
- assertTrue(result.contains("deleted"));
- }
-
- @Test(expected = FileNotFoundException.class)
- public void wontFindBook() throws IOException {
- getResponse("GET", "/books/" + bookId, null);
- }
-
- private static UrlResponse doMethod(String requestMethod, String path, String body) {
- UrlResponse response = new UrlResponse();
-
- try {
- getResponse(requestMethod, path, response);
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return response;
- }
-
- private static void getResponse(String requestMethod, String path, UrlResponse response)
- throws MalformedURLException, IOException, ProtocolException {
- URL url = new URL("http://localhost:" + PORT + path);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setRequestMethod(requestMethod);
- connection.connect();
- String res = IOUtils.toString(connection.getInputStream());
- response.body = res;
- response.status = connection.getResponseCode();
- response.headers = connection.getHeaderFields();
- }
-
- private static class UrlResponse {
- public Map<String, List<String>> headers;
- private String body;
- private int status;
- }
-
- private UrlResponse createBookViaPOST() {
- return doMethod("POST", "/books?author=" + AUTHOR + "&title=" + TITLE, null);
- }
-
- private UrlResponse updateBook() {
- return doMethod("PUT", "/books/" + bookId + "?title=" + NEW_TITLE, null);
- }
-
- private boolean afterFilterIsSet(UrlResponse response) {
- return response.headers.get("FOO").get(0).equals("BAR");
- }
-
- private boolean beforeFilterIsSet(UrlResponse response) {
- return response.headers.get("FOZ").get(0).equals("BAZ");
- }
-}
diff --git a/src/test/java/spark/CookiesIntegrationTest.java b/src/test/java/spark/CookiesIntegrationTest.java
deleted file mode 100644
index 333fb03..0000000
--- a/src/test/java/spark/CookiesIntegrationTest.java
+++ /dev/null
@@ -1,135 +0,0 @@
-package spark;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static spark.Spark.*;
-
-import org.apache.http.HttpResponse;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-/**
- * System tests for the Cookies support.
- *
- * @author dreambrother
- */
-public class CookiesIntegrationTest {
-
- private static final String DEFAULT_HOST_URL = "http://localhost:4567";
- private HttpClient httpClient = HttpClientBuilder.create().build();
-
- @BeforeClass
- public static void initRoutes() throws InterruptedException {
- post("/assertNoCookies", (request, response) -> {
- if (!request.cookies().isEmpty()) {
- halt(500);
- }
- return "";
- });
-
- post("/setCookie", (request, response) -> {
- response.cookie(request.queryParams("cookieName"), request.queryParams("cookieValue"));
- return "";
- });
-
- post("/assertHasCookie", (request, response) -> {
- String cookieValue = request.cookie(request.queryParams("cookieName"));
- if (!request.queryParams("cookieValue").equals(cookieValue)) {
- halt(500);
- }
- return "";
- });
-
- post("/removeCookie", (request, response) -> {
- String cookieName = request.queryParams("cookieName");
- String cookieValue = request.cookie(cookieName);
- if (!request.queryParams("cookieValue").equals(cookieValue)) {
- halt(500);
- }
- response.removeCookie(cookieName);
- return "";
- });
-
- post("/path/setCookieWithPath", (request, response) -> {
- String cookieName = request.queryParams("cookieName");
- String cookieValue = request.queryParams("cookieValue");
- response.cookie("/path", cookieName, cookieValue, -1, false);
- return "";
- }) ;
-
- post("/path/removeCookieWithPath", (request, response) -> {
- String cookieName = request.queryParams("cookieName");
- String cookieValue = request.cookie(cookieName);
- if (!request.queryParams("cookieValue").equals(cookieValue)) {
- halt(500);
- }
- response.removeCookie("/path", cookieName);
- return "";
- }) ;
-
- post("/path/assertNoCookies", (request, response) -> {
- if (!request.cookies().isEmpty()) {
- halt(500);
- }
- return "";
- });
-
- }
-
- @AfterClass
- public static void stopServer() {
- Spark.stop();
- }
-
- @Test
- public void testEmptyCookies() {
- httpPost("/assertNoCookies");
- }
-
- @Test
- public void testCreateCookie() {
- String cookieName = "testCookie";
- String cookieValue = "testCookieValue";
- httpPost("/setCookie?cookieName=" + cookieName + "&cookieValue=" + cookieValue);
- httpPost("/assertHasCookie?cookieName=" + cookieName + "&cookieValue=" + cookieValue);
- }
-
- @Test
- public void testRemoveCookie() {
- String cookieName = "testCookie";
- String cookieValue = "testCookieValue";
- httpPost("/setCookie?cookieName=" + cookieName + "&cookieValue=" + cookieValue);
- httpPost("/removeCookie?cookieName=" + cookieName + "&cookieValue=" + cookieValue);
- httpPost("/assertNoCookies");
- }
-
- @Test
- public void testRemoveCookieWithPath() {
- String cookieName = "testCookie";
- String cookieValue = "testCookieValue";
- httpPost("/path/setCookieWithPath?cookieName=" + cookieName + "&cookieValue=" + cookieValue);
-
- // for sanity, check that cookie is not sent with request if path doesn't match
- httpPost("/assertNoCookies");
-
- // now remove cookie with matching path
- httpPost("/path/removeCookieWithPath?cookieName=" + cookieName + "&cookieValue=" + cookieValue);
- httpPost("/path/assertNoCookies");
- }
-
- private void httpPost(String relativePath) {
- HttpPost request = new HttpPost(DEFAULT_HOST_URL + relativePath);
- try {
- HttpResponse response = httpClient.execute(request);
- assertEquals(200, response.getStatusLine().getStatusCode());
- } catch (Exception ex) {
- fail(ex.toString());
- } finally {
- request.releaseConnection();
- }
- }
-}
diff --git a/src/test/java/spark/FilterTest.java b/src/test/java/spark/FilterTest.java
deleted file mode 100644
index d2bba7a..0000000
--- a/src/test/java/spark/FilterTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package spark;
-
-import java.io.IOException;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import spark.util.SparkTestUtil;
-import spark.util.SparkTestUtil.UrlResponse;
-
-import static spark.Spark.awaitInitialization;
-import static spark.Spark.before;
-import static spark.Spark.stop;
-
-public class FilterTest {
- static SparkTestUtil testUtil;
-
- @AfterClass
- public static void tearDown() {
- stop();
- }
-
- @BeforeClass
- public static void setup() throws IOException {
- testUtil = new SparkTestUtil(4567);
-
- before("/justfilter", (q, a) -> System.out.println("Filter matched"));
- awaitInitialization();
- }
-
- @Test
- public void testJustFilter() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/justfilter", null);
-
- System.out.println("response.status = " + response.status);
- Assert.assertEquals(404, response.status);
- }
-
-}
diff --git a/src/test/java/spark/GenericIntegrationTest.java b/src/test/java/spark/GenericIntegrationTest.java
deleted file mode 100644
index 3936eb0..0000000
--- a/src/test/java/spark/GenericIntegrationTest.java
+++ /dev/null
@@ -1,559 +0,0 @@
-package spark;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URLEncoder;
-import java.nio.ByteBuffer;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
-import org.eclipse.jetty.util.URIUtil;
-import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
-import org.eclipse.jetty.websocket.client.WebSocketClient;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import spark.embeddedserver.jetty.websocket.WebSocketTestClient;
-import spark.embeddedserver.jetty.websocket.WebSocketTestHandler;
-import spark.examples.exception.BaseException;
-import spark.examples.exception.JWGmeligMeylingException;
-import spark.examples.exception.NotFoundException;
-import spark.examples.exception.SubclassOfBaseException;
-import spark.util.SparkTestUtil;
-import spark.util.SparkTestUtil.UrlResponse;
-
-import static spark.Spark.after;
-import static spark.Spark.afterAfter;
-import static spark.Spark.before;
-import static spark.Spark.exception;
-import static spark.Spark.externalStaticFileLocation;
-import static spark.Spark.get;
-import static spark.Spark.halt;
-import static spark.Spark.patch;
-import static spark.Spark.path;
-import static spark.Spark.post;
-import static spark.Spark.staticFileLocation;
-import static spark.Spark.webSocket;
-
-public class GenericIntegrationTest {
-
- private static final String NOT_FOUND_BRO = "Not found bro";
-
- private static final Logger LOGGER = LoggerFactory.getLogger(GenericIntegrationTest.class);
-
- static SparkTestUtil testUtil;
- static File tmpExternalFile;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- if (tmpExternalFile != null) {
- tmpExternalFile.delete();
- }
- }
-
- @BeforeClass
- public static void setup() throws IOException {
- testUtil = new SparkTestUtil(4567);
-
- tmpExternalFile = new File(System.getProperty("java.io.tmpdir"), "externalFile.html");
-
- FileWriter writer = new FileWriter(tmpExternalFile);
- writer.write("Content of external file");
- writer.flush();
- writer.close();
-
- staticFileLocation("/public");
- externalStaticFileLocation(System.getProperty("java.io.tmpdir"));
- webSocket("/ws", WebSocketTestHandler.class);
-
- before("/secretcontent/*", (q, a) -> {
- halt(401, "Go Away!");
- });
-
- before("/protected/*", "application/xml", (q, a) -> {
- halt(401, "Go Away!");
- });
-
- before("/protected/*", "application/json", (q, a) -> {
- halt(401, "{\"message\": \"Go Away!\"}");
- });
-
- get("/hi", "application/json", (q, a) -> "{\"message\": \"Hello World\"}");
- get("/hi", (q, a) -> "Hello World!");
- get("/binaryhi", (q, a) -> "Hello World!".getBytes());
- get("/bytebufferhi", (q, a) -> ByteBuffer.wrap("Hello World!".getBytes()));
- get("/inputstreamhi", (q, a) -> new ByteArrayInputStream("Hello World!".getBytes("utf-8")));
- get("/param/:param", (q, a) -> "echo: " + q.params(":param"));
-
- path("/firstPath", () -> {
- before("/*", (q, a) -> a.header("before-filter-ran", "true"));
- get("/test", (q, a) -> "Single path-prefix works");
- path("/secondPath", () -> {
- get("/test", (q, a) -> "Nested path-prefix works");
- path("/thirdPath", () -> {
- get("/test", (q, a) -> "Very nested path-prefix works");
- });
- });
- });
-
- get("/paramandwild/:param/stuff/*", (q, a) -> "paramandwild: " + q.params(":param") + q.splat()[0]);
- get("/paramwithmaj/:paramWithMaj", (q, a) -> "echo: " + q.params(":paramWithMaj"));
-
- get("/templateView", (q, a) -> new ModelAndView("Hello", "my view"), new TemplateEngine() {
- @Override
- public String render(ModelAndView modelAndView) {
- return modelAndView.getModel() + " from " + modelAndView.getViewName();
- }
- });
-
- get("/", (q, a) -> "Hello Root!");
-
- post("/poster", (q, a) -> {
- String body = q.body();
- a.status(201); // created
- return "Body was: " + body;
- });
-
- post("/post_via_get", (q, a) -> {
- a.status(201); // created
- return "Method Override Worked";
- });
-
- get("/post_via_get", (q, a) -> "Method Override Did Not Work");
-
- patch("/patcher", (q, a) -> {
- String body = q.body();
- a.status(200);
- return "Body was: " + body;
- });
-
- get("/session_reset", (q, a) -> {
- String key = "session_reset";
- Session session = q.session();
- session.attribute(key, "11111");
- session.invalidate();
- session = q.session();
- session.attribute(key, "22222");
- return session.attribute(key);
- });
-
- get("/ip", (request, response) -> request.ip());
-
- after("/hi", (q, a) -> {
-
- if (q.requestMethod().equalsIgnoreCase("get")) {
- Assert.assertNotNull(a.body());
- }
-
- a.header("after", "foobar");
- });
-
- get("/throwexception", (q, a) -> {
- throw new UnsupportedOperationException();
- });
-
- get("/throwsubclassofbaseexception", (q, a) -> {
- throw new SubclassOfBaseException();
- });
-
- get("/thrownotfound", (q, a) -> {
- throw new NotFoundException();
- });
-
- get("/throwmeyling", (q, a) -> {
- throw new JWGmeligMeylingException();
- });
-
- exception(JWGmeligMeylingException.class, (meylingException, q, a) -> {
- a.body(meylingException.trustButVerify());
- });
-
- exception(UnsupportedOperationException.class, (exception, q, a) -> {
- a.body("Exception handled");
- });
-
- exception(BaseException.class, (exception, q, a) -> {
- a.body("Exception handled");
- });
-
- exception(NotFoundException.class, (exception, q, a) -> {
- a.status(404);
- a.body(NOT_FOUND_BRO);
- });
-
- get("/exception", (request, response) -> {
- throw new RuntimeException();
- });
-
- afterAfter("/exception", (request, response) -> {
- response.body("done executed for exception");
- });
-
- post("/nice", (request, response) -> "nice response");
-
- afterAfter("/nice", (request, response) -> {
- response.header("post-process", "nice done response");
- });
-
- afterAfter((request, response) -> {
- response.header("post-process-all", "nice done response after all");
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void filters_should_be_accept_type_aware() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/protected/resource", null, "application/json");
- Assert.assertTrue(response.status == 401);
- Assert.assertEquals("{\"message\": \"Go Away!\"}", response.body);
- }
-
- @Test
- public void routes_should_be_accept_type_aware() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/hi", null, "application/json");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("{\"message\": \"Hello World\"}", response.body);
- }
-
- @Test
- public void template_view_should_be_rendered_with_given_model_view_object() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/templateView", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello from my view", response.body);
- }
-
- @Test
- public void testGetHi() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello World!", response.body);
- }
-
- @Test
- public void testGetBinaryHi() {
- try {
- UrlResponse response = testUtil.doMethod("GET", "/binaryhi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello World!", response.body);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test
- public void testGetByteBufferHi() {
- try {
- UrlResponse response = testUtil.doMethod("GET", "/bytebufferhi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello World!", response.body);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test
- public void testGetInputStreamHi() {
- try {
- UrlResponse response = testUtil.doMethod("GET", "/inputstreamhi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello World!", response.body);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test
- public void testHiHead() throws Exception {
- UrlResponse response = testUtil.doMethod("HEAD", "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("", response.body);
- }
-
- @Test
- public void testGetHiAfterFilter() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/hi", null);
- Assert.assertTrue(response.headers.get("after").contains("foobar"));
- }
-
- @Test
- public void testXForwardedFor() throws Exception {
- final String xForwardedFor = "XXX.XXX.XXX.XXX";
- Map<String, String> headers = new HashMap<>();
- headers.put("X-Forwarded-For", xForwardedFor);
-
- UrlResponse response = testUtil.doMethod("GET", "/ip", null, false, "text/html", headers);
- Assert.assertEquals(xForwardedFor, response.body);
-
- response = testUtil.doMethod("GET", "/ip", null, false, "text/html", null);
- Assert.assertNotEquals(xForwardedFor, response.body);
- }
-
- @Test
- public void testGetRoot() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello Root!", response.body);
- }
-
- @Test
- public void testParamAndWild() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/paramandwild/thedude/stuff/andits", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("paramandwild: thedudeandits", response.body);
- }
-
- @Test
- public void testEchoParam1() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/param/shizzy", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: shizzy", response.body);
- }
-
- @Test
- public void testEchoParam2() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/param/gunit", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: gunit", response.body);
- }
-
- @Test
- public void testEchoParam3() throws Exception {
- String polyglot = "жξ Ä 聊";
- String encoded = URIUtil.encodePath(polyglot);
- UrlResponse response = testUtil.doMethod("GET", "/param/" + encoded, null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: " + polyglot, response.body);
- }
-
- @Test
- public void testPathParamsWithPlusSign() throws Exception {
- String pathParamWithPlusSign = "not+broken+path+param";
- UrlResponse response = testUtil.doMethod("GET", "/param/" + pathParamWithPlusSign, null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: " + pathParamWithPlusSign, response.body);
- }
-
- @Test
- public void testParamWithEncodedSlash() throws Exception {
- String polyglot = "te/st";
- String encoded = URLEncoder.encode(polyglot, "UTF-8");
- UrlResponse response = testUtil.doMethod("GET", "/param/" + encoded, null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: " + polyglot, response.body);
- }
-
- @Test
- public void testSplatWithEncodedSlash() throws Exception {
- String param = "fo/shizzle";
- String encodedParam = URLEncoder.encode(param, "UTF-8");
- String splat = "mah/FRIEND";
- String encodedSplat = URLEncoder.encode(splat, "UTF-8");
- UrlResponse response = testUtil.doMethod("GET",
- "/paramandwild/" + encodedParam + "/stuff/" + encodedSplat, null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("paramandwild: " + param + splat, response.body);
- }
-
- @Test
- public void testEchoParamWithUpperCaseInValue() throws Exception {
- final String camelCased = "ThisIsAValueAndSparkShouldRetainItsUpperCasedCharacters";
- UrlResponse response = testUtil.doMethod("GET", "/param/" + camelCased, null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: " + camelCased, response.body);
- }
-
- @Test
- public void testTwoRoutesWithDifferentCaseButSameName() throws Exception {
- String lowerCasedRoutePart = "param";
- String upperCasedRoutePart = "PARAM";
-
- registerEchoRoute(lowerCasedRoutePart);
- registerEchoRoute(upperCasedRoutePart);
- assertEchoRoute(lowerCasedRoutePart);
- assertEchoRoute(upperCasedRoutePart);
- }
-
- private static void registerEchoRoute(final String routePart) {
- get("/tworoutes/" + routePart + "/:param", (q, a) -> {
- return routePart + " route: " + q.params(":param");
- });
- }
-
- private static void assertEchoRoute(String routePart) throws Exception {
- final String expected = "expected";
- UrlResponse response = testUtil.doMethod("GET", "/tworoutes/" + routePart + "/" + expected, null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(routePart + " route: " + expected, response.body);
- }
-
- @Test
- public void testEchoParamWithMaj() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/paramwithmaj/plop", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: plop", response.body);
- }
-
- @Test
- public void testUnauthorized() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/secretcontent/whateva", null);
- Assert.assertTrue(response.status == 401);
- }
-
- @Test
- public void testNotFound() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/no/resource", null);
- Assert.assertTrue(response.status == 404);
- }
-
- @Test
- public void testPost() throws Exception {
- UrlResponse response = testUtil.doMethod("POST", "/poster", "Fo shizzy");
- LOGGER.info(response.body);
- Assert.assertEquals(201, response.status);
- Assert.assertTrue(response.body.contains("Fo shizzy"));
- }
-
- @Test
- public void testPostViaGetWithMethodOverrideHeader() throws IOException {
- Map<String, String> map = new HashMap<>();
- map.put("X-HTTP-Method-Override", "POST");
- UrlResponse response = testUtil.doMethod("GET", "/post_via_get", "Fo shizzy", false, "*/*", map);
- System.out.println(response.body);
- Assert.assertEquals(201, response.status);
- Assert.assertTrue(response.body.contains("Method Override Worked"));
- }
-
- @Test
- public void testPatch() throws Exception {
- UrlResponse response = testUtil.doMethod("PATCH", "/patcher", "Fo shizzy");
- LOGGER.info(response.body);
- Assert.assertEquals(200, response.status);
- Assert.assertTrue(response.body.contains("Fo shizzy"));
- }
-
- @Test
- public void testSessionReset() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/session_reset", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("22222", response.body);
- }
-
- @Test
- public void testStaticFile() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/css/style.css", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Content of css file", response.body);
- }
-
- @Test
- public void testExternalStaticFile() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/externalFile.html", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Content of external file", response.body);
- }
-
- @Test
- public void testExceptionMapper() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/throwexception", null);
- Assert.assertEquals("Exception handled", response.body);
- }
-
- @Test
- public void testInheritanceExceptionMapper() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/throwsubclassofbaseexception", null);
- Assert.assertEquals("Exception handled", response.body);
- }
-
- @Test
- public void testNotFoundExceptionMapper() throws Exception {
- // thrownotfound
- UrlResponse response = testUtil.doMethod("GET", "/thrownotfound", null);
- Assert.assertEquals(NOT_FOUND_BRO, response.body);
- Assert.assertEquals(404, response.status);
- }
-
- @Test
- public void testTypedExceptionMapper() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/throwmeyling", null);
- Assert.assertEquals(new JWGmeligMeylingException().trustButVerify(), response.body);
- }
-
- @Test
- public void testWebSocketConversation() throws Exception {
- String uri = "ws://localhost:4567/ws";
- WebSocketClient client = new WebSocketClient();
- WebSocketTestClient ws = new WebSocketTestClient();
-
- try {
- client.start();
- client.connect(ws, URI.create(uri), new ClientUpgradeRequest());
- ws.awaitClose(30, TimeUnit.SECONDS);
- } finally {
- client.stop();
- }
-
- List<String> events = WebSocketTestHandler.events;
- Assert.assertEquals(3, events.size(), 3);
- Assert.assertEquals("onConnect", events.get(0));
- Assert.assertEquals("onMessage: Hi Spark!", events.get(1));
- Assert.assertEquals("onClose: 1000 Bye!", events.get(2));
- }
-
- @Test
- public void path_should_prefix_routes() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/firstPath/test", null, "application/json");
- Assert.assertTrue(response.status == 200);
- Assert.assertEquals("Single path-prefix works", response.body);
- Assert.assertEquals("true", response.headers.get("before-filter-ran"));
- }
-
- @Test
- public void paths_should_be_nestable() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/firstPath/secondPath/test", null, "application/json");
- Assert.assertTrue(response.status == 200);
- Assert.assertEquals("Nested path-prefix works", response.body);
- Assert.assertEquals("true", response.headers.get("before-filter-ran"));
- }
-
- @Test
- public void paths_should_be_very_nestable() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/firstPath/secondPath/thirdPath/test", null, "application/json");
- Assert.assertTrue(response.status == 200);
- Assert.assertEquals("Very nested path-prefix works", response.body);
- Assert.assertEquals("true", response.headers.get("before-filter-ran"));
- }
-
- @Test
- public void testRuntimeExceptionForDone() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/exception", null);
- Assert.assertEquals("done executed for exception", response.body);
- Assert.assertEquals(500, response.status);
- }
-
- @Test
- public void testRuntimeExceptionForAllRoutesFinally() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/hi", null);
- Assert.assertEquals("foobar", response.headers.get("after"));
- Assert.assertEquals("nice done response after all", response.headers.get("post-process-all"));
- Assert.assertEquals(200, response.status);
- }
-
- @Test
- public void testPostProcessBodyForFinally() throws Exception {
- UrlResponse response = testUtil.doMethod("POST", "/nice", "");
- Assert.assertEquals("nice response", response.body);
- Assert.assertEquals("nice done response", response.headers.get("post-process"));
- Assert.assertEquals(200, response.status);
- }
-}
diff --git a/src/test/java/spark/GenericSecureIntegrationTest.java b/src/test/java/spark/GenericSecureIntegrationTest.java
deleted file mode 100644
index 1d96c88..0000000
--- a/src/test/java/spark/GenericSecureIntegrationTest.java
+++ /dev/null
@@ -1,165 +0,0 @@
-package spark;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import spark.util.SparkTestUtil;
-import spark.util.SparkTestUtil.UrlResponse;
-
-import static spark.Spark.after;
-import static spark.Spark.before;
-import static spark.Spark.get;
-import static spark.Spark.halt;
-import static spark.Spark.patch;
-import static spark.Spark.post;
-
-public class GenericSecureIntegrationTest {
-
- static SparkTestUtil testUtil;
-
- private static final Logger LOGGER = LoggerFactory.getLogger(GenericSecureIntegrationTest.class);
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- }
-
- @BeforeClass
- public static void setup() {
- testUtil = new SparkTestUtil(4567);
-
- // note that the keystore stuff is retrieved from SparkTestUtil which
- // respects JVM params for keystore, password
- // but offers a default included store if not.
- Spark.secure(SparkTestUtil.getKeyStoreLocation(),
- SparkTestUtil.getKeystorePassword(), null, null);
-
- before("/protected/*", (request, response) -> {
- halt(401, "Go Away!");
- });
-
- get("/hi", (request, response) -> "Hello World!");
-
- get("/ip", (request, response) -> request.ip());
-
- get("/:param", (request, response) -> "echo: " + request.params(":param"));
-
- get("/paramwithmaj/:paramWithMaj", (request, response) -> "echo: " + request.params(":paramWithMaj"));
-
- get("/", (request, response) -> "Hello Root!");
-
- post("/poster", (request, response) -> {
- String body = request.body();
- response.status(201); // created
- return "Body was: " + body;
- });
-
- patch("/patcher", (request, response) -> {
- String body = request.body();
- response.status(200);
- return "Body was: " + body;
- });
-
- after("/hi", (request, response) -> {
- response.header("after", "foobar");
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void testGetHi() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethodSecure("GET", "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello World!", response.body);
- }
-
- @Test
- public void testXForwardedFor() throws Exception {
- final String xForwardedFor = "XXX.XXX.XXX.XXX";
- Map<String, String> headers = new HashMap<>();
- headers.put("X-Forwarded-For", xForwardedFor);
-
- UrlResponse response = testUtil.doMethod("GET", "/ip", null, true, "text/html", headers);
- Assert.assertEquals(xForwardedFor, response.body);
-
- response = testUtil.doMethod("GET", "/ip", null, true, "text/html", null);
- Assert.assertNotEquals(xForwardedFor, response.body);
- }
-
- @Test
- public void testHiHead() throws Exception {
- UrlResponse response = testUtil.doMethodSecure("HEAD", "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("", response.body);
- }
-
- @Test
- public void testGetHiAfterFilter() throws Exception {
- UrlResponse response = testUtil.doMethodSecure("GET", "/hi", null);
- Assert.assertTrue(response.headers.get("after").contains("foobar"));
- }
-
- @Test
- public void testGetRoot() throws Exception {
- UrlResponse response = testUtil.doMethodSecure("GET", "/", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello Root!", response.body);
- }
-
- @Test
- public void testEchoParam1() throws Exception {
- UrlResponse response = testUtil.doMethodSecure("GET", "/shizzy", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: shizzy", response.body);
- }
-
- @Test
- public void testEchoParam2() throws Exception {
- UrlResponse response = testUtil.doMethodSecure("GET", "/gunit", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: gunit", response.body);
- }
-
- @Test
- public void testEchoParamWithMaj() throws Exception {
- UrlResponse response = testUtil.doMethodSecure("GET", "/paramwithmaj/plop", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: plop", response.body);
- }
-
- @Test
- public void testUnauthorized() throws Exception {
- UrlResponse urlResponse = testUtil.doMethodSecure("GET", "/protected/resource", null);
- Assert.assertTrue(urlResponse.status == 401);
- }
-
- @Test
- public void testNotFound() throws Exception {
- UrlResponse urlResponse = testUtil.doMethodSecure("GET", "/no/resource", null);
- Assert.assertTrue(urlResponse.status == 404);
- }
-
- @Test
- public void testPost() throws Exception {
- UrlResponse response = testUtil.doMethodSecure("POST", "/poster", "Fo shizzy");
- LOGGER.info(response.body);
- Assert.assertEquals(201, response.status);
- Assert.assertTrue(response.body.contains("Fo shizzy"));
- }
-
- @Test
- public void testPatch() throws Exception {
- UrlResponse response = testUtil.doMethodSecure("PATCH", "/patcher", "Fo shizzy");
- LOGGER.info(response.body);
- Assert.assertEquals(200, response.status);
- Assert.assertTrue(response.body.contains("Fo shizzy"));
- }
-}
diff --git a/src/test/java/spark/GzipTest.java b/src/test/java/spark/GzipTest.java
deleted file mode 100644
index faddee9..0000000
--- a/src/test/java/spark/GzipTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright 2015 - Per Wendel
- *
- * 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 spark;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import spark.examples.gzip.GzipClient;
-import spark.examples.gzip.GzipExample;
-import spark.util.SparkTestUtil;
-
-import static org.junit.Assert.assertEquals;
-import static spark.Spark.awaitInitialization;
-import static spark.Spark.stop;
-
-/**
- * Tests the GZIP compression support in Spark.
- */
-public class GzipTest {
-
- @BeforeClass
- public static void setup() {
- GzipExample.addStaticFileLocation();
- GzipExample.addRoutes();
- awaitInitialization();
- }
-
- @AfterClass
- public static void tearDown() {
- stop();
- }
-
- @Test
- public void checkGzipCompression() throws Exception {
- String decompressed = GzipExample.getAndDecompress();
- assertEquals(GzipExample.CONTENT, decompressed);
- }
-
- @Test
- public void testStaticFileCssStyleCss() throws Exception {
- String decompressed = GzipClient.getAndDecompress("http://localhost:4567/css/style.css");
- Assert.assertEquals("Content of css file", decompressed);
- testGet();
- }
-
- /**
- * Used to verify that "normal" functionality works after static files mapping
- */
- private static void testGet() throws Exception {
- SparkTestUtil testUtil = new SparkTestUtil(4567);
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/hello", "");
-
- Assert.assertEquals(200, response.status);
- Assert.assertTrue(response.body.contains(GzipExample.FO_SHIZZY));
- }
-
-}
diff --git a/src/test/java/spark/InitExceptionHandlerTest.java b/src/test/java/spark/InitExceptionHandlerTest.java
deleted file mode 100644
index 0623b44..0000000
--- a/src/test/java/spark/InitExceptionHandlerTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package spark;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import static spark.Service.ignite;
-
-public class InitExceptionHandlerTest {
-
- private static int NON_VALID_PORT = Integer.MAX_VALUE;
- private static Service service;
- private static String errorMessage = "";
-
- @BeforeClass
- public static void setUpClass() throws Exception {
- service = ignite();
- service.port(NON_VALID_PORT);
- service.initExceptionHandler((e) -> errorMessage = "Custom init error");
- service.init();
- service.awaitInitialization();
- }
-
- @Test
- public void testInitExceptionHandler() throws Exception {
- Assert.assertEquals("Custom init error", errorMessage);
- }
-
- @AfterClass
- public static void tearDown() throws Exception {
- service.stop();
- }
-
-}
diff --git a/src/test/java/spark/MultipleFiltersTest.java b/src/test/java/spark/MultipleFiltersTest.java
deleted file mode 100644
index be7629f..0000000
--- a/src/test/java/spark/MultipleFiltersTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package spark;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import spark.util.SparkTestUtil;
-
-import static spark.Spark.after;
-import static spark.Spark.awaitInitialization;
-import static spark.Spark.before;
-import static spark.Spark.get;
-import static spark.Spark.stop;
-
-/**
- * Basic test to ensure that multiple before and after filters can be mapped to a route.
- */
-public class MultipleFiltersTest {
-
- private static SparkTestUtil http;
-
-
- @BeforeClass
- public static void setup() {
- http = new SparkTestUtil(4567);
-
- before("/user", initializeCounter, incrementCounter, loadUser);
-
- after("/user", incrementCounter, (req, res) -> {
- int counter = req.attribute("counter");
- Assert.assertEquals(counter, 2);
- });
-
- get("/user", (request, response) -> {
- Assert.assertEquals((int) request.attribute("counter"), 1);
- return ((User) request.attribute("user")).name();
- });
-
- awaitInitialization();
- }
-
- @AfterClass
- public static void stopServer() {
- stop();
- }
-
- @Test
- public void testMultipleFilters() {
- try {
- SparkTestUtil.UrlResponse response = http.get("/user");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Kevin", response.body);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- private static Filter loadUser = (request, response) -> {
- User u = new User();
- u.name("Kevin");
- request.attribute("user", u);
- };
-
- private static Filter initializeCounter = (request, response) -> request.attribute("counter", 0);
-
- private static Filter incrementCounter = (request, response) -> {
- int counter = request.attribute("counter");
- counter++;
- request.attribute("counter", counter);
- };
-
- private static class User {
-
- private String name;
-
- public String name() {
- return name;
- }
-
- public void name(String name) {
- this.name = name;
- }
- }
-}
diff --git a/src/test/java/spark/MultipleServicesTest.java b/src/test/java/spark/MultipleServicesTest.java
deleted file mode 100644
index 788a97f..0000000
--- a/src/test/java/spark/MultipleServicesTest.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright 2016 - Per Wendel
- *
- * 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 spark;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import spark.route.HttpMethod;
-import spark.routematch.RouteMatch;
-import spark.util.SparkTestUtil;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.is;
-import static spark.Service.ignite;
-
-/**
- * Created by Per Wendel on 2016-02-18.
- */
-public class MultipleServicesTest {
-
- private static Service first;
- private static Service second;
-
- private static SparkTestUtil firstClient;
- private static SparkTestUtil secondClient;
-
- @BeforeClass
- public static void setup() throws Exception {
- firstClient = new SparkTestUtil(4567);
- secondClient = new SparkTestUtil(1234);
-
- first = igniteFirstService();
- second = igniteSecondService();
-
- first.awaitInitialization();
- second.awaitInitialization();
- }
-
- @AfterClass
- public static void tearDown() {
- first.stop();
- second.stop();
- }
-
- @Test
- public void testGetHello() throws Exception {
- SparkTestUtil.UrlResponse response = firstClient.doMethod("GET", "/hello", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello World!", response.body);
- }
-
- @Test
- public void testGetRedirectedHi() throws Exception {
- SparkTestUtil.UrlResponse response = secondClient.doMethod("GET", "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello World!", response.body);
- }
-
- @Test
- public void testGetUniqueForSecondWithFirst() throws Exception {
- SparkTestUtil.UrlResponse response = firstClient.doMethod("GET", "/uniqueforsecond", null);
- Assert.assertEquals(404, response.status);
- }
-
- @Test
- public void testGetUniqueForSecondWithSecond() throws Exception {
- SparkTestUtil.UrlResponse response = secondClient.doMethod("GET", "/uniqueforsecond", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Bompton", response.body);
- }
-
- @Test
- public void testStaticFileCssStyleCssWithFirst() throws Exception {
- SparkTestUtil.UrlResponse response = firstClient.doMethod("GET", "/css/style.css", null);
- Assert.assertEquals(404, response.status);
- }
-
- @Test
- public void testStaticFileCssStyleCssWithSecond() throws Exception {
- SparkTestUtil.UrlResponse response = secondClient.doMethod("GET", "/css/style.css", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Content of css file", response.body);
- }
-
- @Test
- public void testGetAllRoutesFromBothServices(){
- for(RouteMatch routeMatch : first.routes()){
- Assert.assertEquals(routeMatch.getAcceptType(), "*/*");
- Assert.assertEquals(routeMatch.getHttpMethod(), HttpMethod.get);
- Assert.assertEquals(routeMatch.getMatchUri(), "/hello");
- Assert.assertEquals(routeMatch.getRequestURI(), "ALL_ROUTES");
- Assert.assertThat(routeMatch.getTarget(), instanceOf(RouteImpl.class));
- }
-
- for(RouteMatch routeMatch : second.routes()){
- Assert.assertEquals(routeMatch.getAcceptType(), "*/*");
- Assert.assertThat(routeMatch.getHttpMethod(), instanceOf(HttpMethod.class));
- boolean isUriOnList = ("/hello/hi/uniqueforsecond").contains(routeMatch.getMatchUri());
- Assert.assertTrue(isUriOnList);
- Assert.assertEquals(routeMatch.getRequestURI(), "ALL_ROUTES");
- Assert.assertThat(routeMatch.getTarget(), instanceOf(RouteImpl.class));
- }
- }
-
- private static Service igniteFirstService() {
-
- Service http = ignite(); // I give the variable the name 'http' for the code to make sense when adding routes.
-
- http.get("/hello", (q, a) -> "Hello World!");
-
- return http;
- }
-
- private static Service igniteSecondService() {
-
- Service http = ignite()
- .port(1234)
- .staticFileLocation("/public")
- .threadPool(40);
-
- http.get("/hello", (q, a) -> "Hello World!");
- http.get("/uniqueforsecond", (q, a) -> "Bompton");
-
- http.redirect.any("/hi", "/hello");
-
- return http;
- }
-
-
-}
diff --git a/src/test/java/spark/RedirectTest.java b/src/test/java/spark/RedirectTest.java
deleted file mode 100644
index 2d7769b..0000000
--- a/src/test/java/spark/RedirectTest.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright 2016 - Per Wendel
- *
- * 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 spark;
-
-import java.io.IOException;
-
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import spark.util.SparkTestUtil;
-
-import static spark.Spark.get;
-import static spark.Spark.redirect;
-
-/**
- * Tests the redirect utility methods in {@link spark.Redirect}
- */
-public class RedirectTest {
-
- private static final String REDIRECTED = "Redirected";
-
- private static SparkTestUtil testUtil;
-
- @BeforeClass
- public static void setup() throws IOException {
- testUtil = new SparkTestUtil(4567);
- testUtil.setFollowRedirectStrategy(301, 302); // don't set the others to be able to verify affect of Redirect.Status
-
- get("/hello", (request, response) -> REDIRECTED);
-
- redirect.get("/hi", "/hello");
- redirect.post("/hi", "/hello");
- redirect.put("/hi", "/hello");
- redirect.delete("/hi", "/hello");
- redirect.any("/any", "/hello");
-
- redirect.get("/hiagain", "/hello", Redirect.Status.USE_PROXY);
- redirect.post("/hiagain", "/hello", Redirect.Status.USE_PROXY);
- redirect.put("/hiagain", "/hello", Redirect.Status.USE_PROXY);
- redirect.delete("/hiagain", "/hello", Redirect.Status.USE_PROXY);
- redirect.any("/anyagain", "/hello", Redirect.Status.USE_PROXY);
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void testRedirectGet() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(REDIRECTED, response.body);
- }
-
- @Test
- public void testRedirectPost() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("POST", "/hi", "");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(REDIRECTED, response.body);
- }
-
- @Test
- public void testRedirectPut() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("PUT", "/hi", "");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(REDIRECTED, response.body);
- }
-
- @Test
- public void testRedirectDelete() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("DELETE", "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(REDIRECTED, response.body);
- }
-
- @Test
- public void testRedirectAnyGet() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/any", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(REDIRECTED, response.body);
- }
-
- @Test
- public void testRedirectAnyPut() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("PUT", "/any", "");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(REDIRECTED, response.body);
- }
-
- @Test
- public void testRedirectAnyPost() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("POST", "/any", "");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(REDIRECTED, response.body);
- }
-
- @Test
- public void testRedirectAnyDelete() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("DELETE", "/any", "");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(REDIRECTED, response.body);
- }
-
- @Test
- public void testRedirectGetWithSpecificCode() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/hiagain", null);
- Assert.assertEquals(Redirect.Status.USE_PROXY.intValue(), response.status);
- }
-
- @Test
- public void testRedirectPostWithSpecificCode() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("POST", "/hiagain", "");
- Assert.assertEquals(Redirect.Status.USE_PROXY.intValue(), response.status);
- }
-
- @Test
- public void testRedirectPutWithSpecificCode() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("PUT", "/hiagain", "");
- Assert.assertEquals(Redirect.Status.USE_PROXY.intValue(), response.status);
- }
-
- @Test
- public void testRedirectDeleteWithSpecificCode() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("DELETE", "/hiagain", null);
- Assert.assertEquals(Redirect.Status.USE_PROXY.intValue(), response.status);
- }
-
- @Test
- public void testRedirectAnyGetWithSpecificCode() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/anyagain", null);
- Assert.assertEquals(Redirect.Status.USE_PROXY.intValue(), response.status);
- }
-
- @Test
- public void testRedirectAnyPostWithSpecificCode() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("POST", "/anyagain", "");
- Assert.assertEquals(Redirect.Status.USE_PROXY.intValue(), response.status);
- }
-
- @Test
- public void testRedirectAnyPutWithSpecificCode() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("PUT", "/anyagain", "");
- Assert.assertEquals(Redirect.Status.USE_PROXY.intValue(), response.status);
- }
-
- @Test
- public void testRedirectAnyDeleteWithSpecificCode() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("DELETE", "/anyagain", null);
- Assert.assertEquals(Redirect.Status.USE_PROXY.intValue(), response.status);
- }
-
-}
diff --git a/src/test/java/spark/RequestTest.java b/src/test/java/spark/RequestTest.java
deleted file mode 100644
index dc9dfa8..0000000
--- a/src/test/java/spark/RequestTest.java
+++ /dev/null
@@ -1,506 +0,0 @@
-package spark;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import spark.routematch.RouteMatch;
-import spark.util.SparkTestUtil;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import java.util.*;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static spark.Spark.*;
-
-public class RequestTest {
-
- private static final String THE_SERVLET_PATH = "/the/servlet/path";
- private static final String THE_CONTEXT_PATH = "/the/context/path";
- private static final String THE_MATCHED_ROUTE = "/users/:username";
- private static final String BEFORE_MATCHED_ROUTE = "/users/:before";
- private static final String AFTER_MATCHED_ROUTE = "/users/:after";
- private static final String AFTERAFTER_MATCHED_ROUTE = "/users/:afterafter";
-
- private static SparkTestUtil http;
-
- HttpServletRequest servletRequest;
- HttpSession httpSession;
- Request request;
-
- RouteMatch match = new RouteMatch(null, "/hi", "/hi", "text/html", null);
- RouteMatch matchWithParams = new RouteMatch(null, "/users/:username", "/users/bob", "text/html", null);
-
- @Before
- public void setup() {
- http = new SparkTestUtil(4567);
-
- before(BEFORE_MATCHED_ROUTE, (q, a) -> {
- System.out.println("before filter matched");
- shouldBeAbleToGetTheMatchedPathInBeforeFilter(q);
- });
- get(THE_MATCHED_ROUTE, (q,a)-> "Get filter matched");
- after(AFTER_MATCHED_ROUTE, (q, a) -> {
- System.out.println("after filter matched");
- shouldBeAbleToGetTheMatchedPathInAfterFilter(q);
- });
- afterAfter(AFTERAFTER_MATCHED_ROUTE, (q, a) -> {
- System.out.println("afterafter filter matched");
- shouldBeAbleToGetTheMatchedPathInAfterAfterFilter(q);
- });
-
- awaitInitialization();
-
-
- servletRequest = mock(HttpServletRequest.class);
- httpSession = mock(HttpSession.class);
-
- request = new Request(match, servletRequest);
-
- }
-
- @Test
- public void queryParamShouldReturnsParametersFromQueryString() {
-
- when(servletRequest.getParameter("name")).thenReturn("Federico");
-
- String name = request.queryParams("name");
- assertEquals("Invalid name in query string", "Federico", name);
- }
-
- @Test
- public void queryParamOrDefault_shouldReturnQueryParam_whenQueryParamExists() {
-
- when(servletRequest.getParameter("name")).thenReturn("Federico");
-
- String name = request.queryParamOrDefault("name", "David");
- assertEquals("Invalid name in query string", "Federico", name);
- }
-
- @Test
- public void queryParamOrDefault_shouldReturnDefault_whenQueryParamIsNull() {
-
- when(servletRequest.getParameter("name")).thenReturn(null);
-
- String name = request.queryParamOrDefault("name", "David");
- assertEquals("Invalid name in default value", "David", name);
- }
-
- @Test
- public void queryParamShouldBeParsedAsHashMap() {
- Map<String, String[]> params = new HashMap<>();
- params.put("user[name]", new String[] {"Federico"});
-
- when(servletRequest.getParameterMap()).thenReturn(params);
-
- String name = request.queryMap("user").value("name");
- assertEquals("Invalid name in query string", "Federico", name);
- }
-
- @Test
- public void shouldBeAbleToGetTheServletPath() {
-
- when(servletRequest.getServletPath()).thenReturn(THE_SERVLET_PATH);
-
- Request request = new Request(match, servletRequest);
- assertEquals("Should have delegated getting the servlet path", THE_SERVLET_PATH, request.servletPath());
- }
-
- @Test
- public void shouldBeAbleToGetTheContextPath() {
-
- when(servletRequest.getContextPath()).thenReturn(THE_CONTEXT_PATH);
-
- Request request = new Request(match, servletRequest);
- assertEquals("Should have delegated getting the context path", THE_CONTEXT_PATH, request.contextPath());
- }
-
- @Test
- public void shouldBeAbleToGetTheMatchedPath() {
- Request request = new Request(matchWithParams, servletRequest);
- assertEquals("Should have returned the matched route", THE_MATCHED_ROUTE, request.matchedPath());
- try {
- http.get("/users/bob");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- public void shouldBeAbleToGetTheMatchedPathInBeforeFilter(Request q) {
- assertEquals("Should have returned the matched route from the before filter", BEFORE_MATCHED_ROUTE, q.matchedPath());
- }
-
- public void shouldBeAbleToGetTheMatchedPathInAfterFilter(Request q) {
- assertEquals("Should have returned the matched route from the after filter", AFTER_MATCHED_ROUTE, q.matchedPath());
- }
-
- public void shouldBeAbleToGetTheMatchedPathInAfterAfterFilter(Request q) {
- assertEquals("Should have returned the matched route from the afterafter filter", AFTERAFTER_MATCHED_ROUTE, q.matchedPath());
- }
-
- @Test
- public void testSessionNoParams_whenSessionIsNull() {
-
- when(servletRequest.getSession()).thenReturn(httpSession);
-
- assertEquals("A Session with an HTTPSession from the Request should have been created",
- httpSession, request.session().raw());
- }
-
- @Test
- public void testSession_whenCreateIsTrue() {
-
- when(servletRequest.getSession(true)).thenReturn(httpSession);
-
- assertEquals("A Session with an HTTPSession from the Request should have been created because create parameter " +
- "was set to true",
- httpSession, request.session(true).raw());
-
- }
-
- @Test
- public void testSession_whenCreateIsFalse() {
-
- when(servletRequest.getSession(true)).thenReturn(httpSession);
-
- assertEquals("A Session should not have been created because create parameter was set to false",
- null, request.session(false));
-
- }
-
- @Test
- public void testSessionNpParams_afterSessionInvalidate() {
- when(servletRequest.getSession()).thenReturn(httpSession);
-
- Session session = request.session();
- session.invalidate();
- request.session();
-
- verify(servletRequest, times(2)).getSession();
- }
-
- @Test
- public void testSession_whenCreateIsTrue_afterSessionInvalidate() {
- when(servletRequest.getSession(true)).thenReturn(httpSession);
-
- Session session = request.session(true);
- session.invalidate();
- request.session(true);
-
- verify(servletRequest, times(2)).getSession(true);
- }
-
- @Test
- public void testSession_whenCreateIsFalse_afterSessionInvalidate() {
- when(servletRequest.getSession()).thenReturn(httpSession);
- when(servletRequest.getSession(false)).thenReturn(null);
-
- Session session = request.session();
- session.invalidate();
- request.session(false);
-
- verify(servletRequest, times(1)).getSession(false);
- }
-
- @Test
- public void testSession_2times() {
- when(servletRequest.getSession(true)).thenReturn(httpSession);
-
- Session session = request.session(true);
- session = request.session(true);
-
- assertNotNull(session);
- verify(servletRequest, times(1)).getSession(true);
- }
-
- @Test
- public void testCookies_whenCookiesArePresent() {
-
- Collection<Cookie> cookies = new ArrayList<>();
- cookies.add(new Cookie("cookie1", "cookie1value"));
- cookies.add(new Cookie("cookie2", "cookie2value"));
-
- Map<String, String> expected = new HashMap<>();
- for(Cookie cookie : cookies) {
- expected.put(cookie.getName(), cookie.getValue());
- }
-
- Cookie[] cookieArray = cookies.toArray(new Cookie[cookies.size()]);
-
- when(servletRequest.getCookies()).thenReturn(cookieArray);
-
- assertTrue("The count of cookies returned should be the same as those in the request",
- request.cookies().size() == 2);
-
- assertEquals("A Map of Cookies should have been returned because they exist", expected, request.cookies());
-
- }
-
- @Test
- public void testCookies_whenCookiesAreNotPresent() {
-
- when(servletRequest.getCookies()).thenReturn(null);
-
- assertNotNull("A Map of Cookies should have been instantiated even if cookies are not present in the request",
- request.cookies());
-
- assertTrue("The Map of cookies should be empty because cookies are not present in the request",
- request.cookies().size() == 0);
-
- }
-
- @Test
- public void testCookie_whenCookiesArePresent() {
-
- final String cookieKey = "cookie1";
- final String cookieValue = "cookie1value";
-
- Collection<Cookie> cookies = new ArrayList<>();
- cookies.add(new Cookie(cookieKey, cookieValue));
-
- Cookie[] cookieArray = cookies.toArray(new Cookie[cookies.size()]);
- when(servletRequest.getCookies()).thenReturn(cookieArray);
-
- assertNotNull("A value for the key provided should exist because a cookie with the same key is present",
- request.cookie(cookieKey));
-
- assertEquals("The correct value for the cookie key supplied should be returned",
- cookieValue, request.cookie(cookieKey));
-
- }
-
- @Test
- public void testCookie_whenCookiesAreNotPresent() {
-
- final String cookieKey = "nonExistentCookie";
-
- when(servletRequest.getCookies()).thenReturn(null);
-
- assertNull("A null value should have been returned because the cookie with that key does not exist",
- request.cookie(cookieKey));
-
- }
-
- @Test
- public void testRequestMethod() {
-
- final String requestMethod = "GET";
-
- when(servletRequest.getMethod()).thenReturn(requestMethod);
-
- assertEquals("The request method of the underlying servlet request should be returned",
- requestMethod, request.requestMethod());
-
- }
-
- @Test
- public void testScheme() {
-
- final String scheme = "http";
-
- when(servletRequest.getScheme()).thenReturn(scheme);
-
- assertEquals("The scheme of the underlying servlet request should be returned",
- scheme, request.scheme());
-
- }
-
- @Test
- public void testHost() {
-
- final String host = "www.google.com";
-
- when(servletRequest.getHeader("host")).thenReturn(host);
-
- assertEquals("The value of the host header of the underlying servlet request should be returned",
- host, request.host());
-
- }
-
- @Test
- public void testUserAgent() {
-
- final String userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36";
-
- when(servletRequest.getHeader("user-agent")).thenReturn(userAgent);
-
- assertEquals("The value of the user agent header of the underlying servlet request should be returned",
- userAgent, request.userAgent());
-
- }
-
- @Test
- public void testPort() {
-
- final int port = 80;
-
- when(servletRequest.getServerPort()).thenReturn(80);
-
- assertEquals("The server port of the the underlying servlet request should be returned",
- port, request.port());
-
- }
-
- @Test
- public void testPathInfo() {
-
- final String pathInfo = "/path/to/resource";
-
- when(servletRequest.getPathInfo()).thenReturn(pathInfo);
-
- assertEquals("The path info of the underlying servlet request should be returned",
- pathInfo, request.pathInfo());
-
- }
-
- @Test
- public void testServletPath() {
-
- final String servletPath = "/api";
-
- when(servletRequest.getServletPath()).thenReturn(servletPath);
-
- assertEquals("The servlet path of the underlying servlet request should be returned",
- servletPath, request.servletPath());
-
- }
-
- @Test
- public void testContextPath() {
-
- final String contextPath = "/my-app";
-
- when(servletRequest.getContextPath()).thenReturn(contextPath);
-
- assertEquals("The context path of the underlying servlet request should be returned",
- contextPath, request.contextPath());
-
- }
-
- @Test
- public void testUrl() {
-
- final String url = "http://www.myapp.com/myapp/a";
-
- when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url));
-
- assertEquals("The request url of the underlying servlet request should be returned",
- url, request.url());
-
- }
-
- @Test
- public void testContentType() {
-
- final String contentType = "image/jpeg";
-
- when(servletRequest.getContentType()).thenReturn(contentType);
-
- assertEquals("The content type of the underlying servlet request should be returned",
- contentType, request.contentType());
-
- }
-
- @Test
- public void testIp() {
-
- final String ip = "216.58.197.106:80";
-
- when(servletRequest.getRemoteAddr()).thenReturn(ip);
-
- assertEquals("The remote IP of the underlying servlet request should be returned",
- ip, request.ip());
-
- }
-
- @Test
- public void testContentLength() {
-
- final int contentLength = 500;
-
- when(servletRequest.getContentLength()).thenReturn(contentLength);
-
- assertEquals("The content length the underlying servlet request should be returned",
- contentLength, request.contentLength());
-
- }
-
- @Test
- public void testHeaders() {
-
- final String headerKey = "host";
- final String host = "www.google.com";
-
- when(servletRequest.getHeader(headerKey)).thenReturn(host);
-
- assertEquals("The value of the header specified should be returned",
- host, request.headers(headerKey));
-
- }
-
- @Test
- public void testQueryParamsValues_whenParamExists() {
-
- final String[] paramValues = {"foo", "bar"};
-
- when(servletRequest.getParameterValues("id")).thenReturn(paramValues);
-
- assertArrayEquals("An array of Strings for a parameter with multiple values should be returned",
- paramValues, request.queryParamsValues("id"));
-
- }
-
- @Test
- public void testQueryParamsValues_whenParamDoesNotExists() {
-
- when(servletRequest.getParameterValues("id")).thenReturn(null);
-
- assertNull("Null should be returned because the parameter specified does not exist in the request",
- request.queryParamsValues("id"));
-
- }
-
- @Test
- public void testQueryParams() {
-
- Map<String, String[]> params = new HashMap<>();
- params.put("sort", new String[]{"asc"});
- params.put("items", new String[]{"10"});
-
- when(servletRequest.getParameterMap()).thenReturn(params);
-
- Set<String> result = request.queryParams();
-
- assertArrayEquals("Should return the query parameter names", params.keySet().toArray(), result.toArray());
-
- }
-
- @Test
- public void testURI() {
-
- final String requestURI = "http://localhost:8080/myapp/";
-
- when(servletRequest.getRequestURI()).thenReturn(requestURI);
-
- assertEquals("The request URI should be returned",
- requestURI, request.uri());
-
- }
-
- @Test
- public void testProtocol() {
-
- final String protocol = "HTTP/1.1";
-
- when(servletRequest.getProtocol()).thenReturn(protocol);
-
- assertEquals("The underlying request protocol should be returned",
- protocol, request.protocol());
-
- }
-}
diff --git a/src/test/java/spark/ResponseBodyTest.java b/src/test/java/spark/ResponseBodyTest.java
deleted file mode 100644
index f8cf36d..0000000
--- a/src/test/java/spark/ResponseBodyTest.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright 2016 - Per Wendel
- *
- * 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 spark;
-
-import java.io.IOException;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import spark.util.SparkTestUtil;
-
-import static org.junit.Assert.assertEquals;
-import static spark.Spark.after;
-import static spark.Spark.get;
-
-/**
- * Validates and shows the "rules" for how response "body" is set.
- */
-public class ResponseBodyTest {
-
- public static final String HELLO = "/hello";
- public static final String SPECIAL = "/special";
- public static final String PORAKATIKAOKAO = "/porakatikaokao";
- public static final String MAXIME = "/maxime";
-
- public static final String HELLO_WORLD = "Hello World!";
- public static final String XIDXUS = "xidxus";
- public static final String $11AB = "$11ab";
- public static final String GALLUS_SCANDALUM = "gallus scandalum";
-
- private static SparkTestUtil http;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- }
-
- @BeforeClass
- public static void setup() throws IOException {
- http = new SparkTestUtil(4567);
-
- get(HELLO, (q, a) -> HELLO_WORLD);
-
- after(HELLO, (q, a) -> {
- String body = a.body();
- assertEquals(HELLO_WORLD, body);
- });
-
- get(SPECIAL, (q, a) -> {
- a.body(XIDXUS);
- return "";
- });
-
- after(SPECIAL, (q, a) -> {
- String body = a.body();
- assertEquals(XIDXUS, body);
- });
-
- get(PORAKATIKAOKAO, (q, a) -> {
- a.body(GALLUS_SCANDALUM);
- return null;
- });
-
- after(PORAKATIKAOKAO, (q, a) -> {
- String body = a.body();
- assertEquals(GALLUS_SCANDALUM, body);
- });
-
- get(MAXIME, (q, a) -> {
- a.body(XIDXUS);
- return $11AB;
- });
-
- after(MAXIME, (q, a) -> {
- String body = a.body();
- assertEquals($11AB, body);
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void testHELLO() {
- try {
- SparkTestUtil.UrlResponse response = http.get(HELLO);
- assertEquals(200, response.status);
- assertEquals(HELLO_WORLD, response.body);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test
- public void testSPECIAL() {
- try {
- SparkTestUtil.UrlResponse response = http.get(SPECIAL);
- assertEquals(200, response.status);
- assertEquals(XIDXUS, response.body);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test
- public void testPORAKATIKAOKAO() {
- try {
- SparkTestUtil.UrlResponse response = http.get(PORAKATIKAOKAO);
- assertEquals(200, response.status);
- assertEquals(GALLUS_SCANDALUM, response.body);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test
- public void testMAXIME() {
- try {
- SparkTestUtil.UrlResponse response = http.get(MAXIME);
- assertEquals(200, response.status);
- assertEquals($11AB, response.body);
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
-
-}
diff --git a/src/test/java/spark/ResponseTest.java b/src/test/java/spark/ResponseTest.java
deleted file mode 100644
index 8a55ed2..0000000
--- a/src/test/java/spark/ResponseTest.java
+++ /dev/null
@@ -1,292 +0,0 @@
-package spark;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-import org.powermock.reflect.Whitebox;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletResponse;
-import java.util.Date;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.mockito.Mockito.*;
-
-public class ResponseTest {
-
- private Response response;
- private HttpServletResponse httpServletResponse;
-
- private ArgumentCaptor<Cookie> cookieArgumentCaptor;
-
- @Before
- public void setup() {
- httpServletResponse = mock(HttpServletResponse.class);
- response = new Response(httpServletResponse);
- cookieArgumentCaptor = ArgumentCaptor.forClass(Cookie.class);
- }
-
- @Test
- public void testConstructor_whenHttpServletResponseParameter() {
- HttpServletResponse returnResponse = Whitebox.getInternalState(response, "response");
- assertSame("Should be the same the HttpServletResponse object for httpServletResponse and returnResponse", httpServletResponse, returnResponse);
- }
-
- @Test
- public void testSetStatus() {
- final int finalStatusCode = HttpServletResponse.SC_OK;
-
- response.status(finalStatusCode);
- verify(httpServletResponse).setStatus(finalStatusCode);
- }
-
- @Test
- public void testGetStatus() {
- response.status();
- verify(httpServletResponse).getStatus();
- }
-
- @Test
- public void testSetType() {
- final String finalType = "text/html";
-
- response.type(finalType);
- verify(httpServletResponse).setContentType(finalType);
- }
-
- @Test
- public void testGetType() {
- response.type();
- verify(httpServletResponse).getContentType();
- }
-
- @Test
- public void testSetBody() {
- final String finalBody = "Hello world!";
-
- response.body(finalBody);
- String returnBody = Whitebox.getInternalState(response, "body");
- assertEquals("Should return body specified", finalBody, returnBody);
- }
-
- @Test
- public void testGetBody() {
- final String finalBody = "Hello world!";
-
- Whitebox.setInternalState(response, "body", finalBody);
- String returnBody = response.body();
- assertEquals("Should return body specified", finalBody, returnBody);
- }
-
- @Test
- public void testRaw() {
- HttpServletResponse returnResponse = response.raw();
- assertSame("Should be the same the HttpServletResponse object for httpServletResponse and returnResponse", httpServletResponse, returnResponse);
- }
-
- @Test
- public void testHeader() {
- final String finalHeaderKey = "Content-Length";
- final String finalHeaderValue = "32";
-
- response.header(finalHeaderKey, finalHeaderValue);
- verify(httpServletResponse).addHeader(finalHeaderKey, finalHeaderValue);
- }
-
- @Test
- public void testIntHeader() {
- response.header("X-Processing-Time", 10);
- verify(httpServletResponse).addIntHeader("X-Processing-Time", 10);
- }
-
- @Test
- public void testJavaUtilDateHeader() {
- Date now = new Date();
- response.header("X-Processing-Since", now);
- verify(httpServletResponse).addDateHeader("X-Processing-Since", now.getTime());
- }
-
- @Test
- public void testJavaSqlDateHeader() {
- Date now = new Date();
- response.header("X-Processing-Since", new java.sql.Date(now.getTime()));
- verify(httpServletResponse).addDateHeader("X-Processing-Since", now.getTime());
- }
-
- @Test
- public void testInstantDateHeader() {
- Date now = new Date();
- response.header("X-Processing-Since", now.toInstant());
- verify(httpServletResponse).addDateHeader("X-Processing-Since", now.getTime());
- }
-
- private void validateCookieContent(Cookie cookie,
- String domain,
- String path,
- String value,
- int maxAge,
- boolean secured,
- boolean httpOnly) {
- assertEquals("Should return cookie domain specified", domain, cookie.getDomain());
- assertEquals("Should return cookie path specified", path, cookie.getPath());
- assertEquals("Should return cookie value specified", value, cookie.getValue());
- assertEquals("Should return cookie max age specified", maxAge, cookie.getMaxAge());
- assertEquals("Should return cookie secure specified", secured, cookie.getSecure());
- assertEquals("Should return cookie http only specified", httpOnly, cookie.isHttpOnly());
- }
-
- @Test
- public void testCookie_whenNameAndValueParameters_shouldAddCookieSuccessfully() {
-
- final String finalDomain = "";
- final String finalPath = "";
- final String finalName = "cookie_name";
- final String finalValue = "Test Cookie";
- final int finalMaxAge = -1;
- final boolean finalSecured = false;
- final boolean finalHttpOnly = false;
-
- response.cookie(finalName, finalValue);
-
- verify(httpServletResponse).addCookie(cookieArgumentCaptor.capture());
- validateCookieContent(cookieArgumentCaptor.getValue(), finalDomain, finalPath, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
- }
-
- @Test
- public void testCookie_whenNameValueAndMaxAgeParameters_shouldAddCookieSuccessfully() {
-
- final String finalDomain = "";
- final String finalPath = "";
- final String finalName = "cookie_name";
- final String finalValue = "Test Cookie";
- final int finalMaxAge = 86400;
- final boolean finalSecured = false;
- final boolean finalHttpOnly = false;
-
- response.cookie(finalName, finalValue, finalMaxAge);
-
- verify(httpServletResponse).addCookie(cookieArgumentCaptor.capture());
- validateCookieContent(cookieArgumentCaptor.getValue(), finalDomain, finalPath, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
- }
-
- @Test
- public void testCookie_whenNameValueMaxAgeAndSecuredParameters_shouldAddCookieSuccessfully() {
- final String finalDomain = "";
- final String finalPath = "";
- final String finalName = "cookie_name";
- final String finalValue = "Test Cookie";
- final int finalMaxAge = 86400;
- final boolean finalSecured = true;
- final boolean finalHttpOnly = false;
-
- response.cookie(finalName, finalValue, finalMaxAge, finalSecured);
-
- verify(httpServletResponse).addCookie(cookieArgumentCaptor.capture());
- validateCookieContent(cookieArgumentCaptor.getValue(), finalDomain, finalPath, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
- }
-
- @Test
- public void testCookie_whenNameValueMaxAgeSecuredAndHttpOnlyParameters_shouldAddCookieSuccessfully() {
- final String finalDomain = "";
- final String finalPath = "";
- final String finalName = "cookie_name";
- final String finalValue = "Test Cookie";
- final int finalMaxAge = 86400;
- final boolean finalSecured = true;
- final boolean finalHttpOnly = true;
-
- response.cookie(finalName, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
-
- verify(httpServletResponse).addCookie(cookieArgumentCaptor.capture());
- validateCookieContent(cookieArgumentCaptor.getValue(), finalDomain, finalPath, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
- }
-
- @Test
- public void testCookie_whenPathNameValueMaxAgeAndSecuredParameters_shouldAddCookieSuccessfully() {
- final String finalDomain = "";
- final String finalPath = "/cookie/SetCookie";
- final String finalName = "cookie_name";
- final String finalValue = "Test Cookie";
- final int finalMaxAge = 86400;
- final boolean finalSecured = true;
- final boolean finalHttpOnly = false;
-
- response.cookie(finalPath, finalName, finalValue, finalMaxAge, finalSecured);
-
- verify(httpServletResponse).addCookie(cookieArgumentCaptor.capture());
- validateCookieContent(cookieArgumentCaptor.getValue(), finalDomain, finalPath, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
- }
-
- @Test
- public void testCookie_whenPathNameValueMaxAgeSecuredAndHttpOnlyParameters_shouldAddCookieSuccessfully() {
- final String finalDomain = "";
- final String finalPath = "/cookie/SetCookie";
- final String finalName = "cookie_name";
- final String finalValue = "Test Cookie";
- final int finalMaxAge = 86400;
- final boolean finalSecured = true;
- final boolean finalHttpOnly = true;
-
- response.cookie(finalPath, finalName, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
-
- verify(httpServletResponse).addCookie(cookieArgumentCaptor.capture());
- validateCookieContent(cookieArgumentCaptor.getValue(), finalDomain, finalPath, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
- }
-
- @Test
- public void testCookie_whenDomainPathNameValueMaxAgeSecuredAndHttpOnlyParameters_shouldAddCookieSuccessfully() {
- final String finalDomain = "example.com";
- final String finalPath = "/cookie/SetCookie";
- final String finalName = "cookie_name";
- final String finalValue = "Test Cookie";
- final int finalMaxAge = 86400;
- final boolean finalSecured = true;
- final boolean finalHttpOnly = true;
-
- response.cookie(finalDomain, finalPath, finalName, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
-
- verify(httpServletResponse).addCookie(cookieArgumentCaptor.capture());
- validateCookieContent(cookieArgumentCaptor.getValue(), finalDomain, finalPath, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
- }
-
- @Test
- public void testRemoveCookie_shouldModifyPropertiesFromCookieSuccessfully() {
- final String finalPath = "/cookie/SetCookie";
- final String finalName = "cookie_name";
- final String finalValue = "Test Cookie";
- final int finalMaxAge = 86400;
- final boolean finalSecured = true;
- final boolean finalHttpOnly = true;
-
- response.cookie(finalPath, finalName, finalValue, finalMaxAge, finalSecured, finalHttpOnly);
-
- response.removeCookie(finalName);
- verify(httpServletResponse, times(2)).addCookie(cookieArgumentCaptor.capture());
-
- assertEquals("Should return empty value for the given cookie name", "", cookieArgumentCaptor.getValue().getValue());
- assertEquals("Should return an 0 for maximum cookie age", 0, cookieArgumentCaptor.getValue().getMaxAge());
- }
-
- @Test
- public void testRedirect_whenLocationParameter_shouldModifyStatusCodeSuccessfully() throws Exception { // NOSONAR
- final String finalLocation = "/test";
-
- response.redirect(finalLocation);
- verify(httpServletResponse).sendRedirect(finalLocation);
- }
-
- @Test
- public void testRedirect_whenLocationAndHttpStatusCodeParameters_shouldModifyStatusCodeSuccessfully() throws
- Exception { // NOSONAR
- final String finalLocation = "/test";
- int finalStatusCode = HttpServletResponse.SC_BAD_GATEWAY;
-
- response.redirect(finalLocation, finalStatusCode);
-
- verify(httpServletResponse).setStatus(finalStatusCode);
- verify(httpServletResponse).setHeader("Location", finalLocation);
- verify(httpServletResponse).setHeader("Connection", "close");
- verify(httpServletResponse).sendError(finalStatusCode);
- }
-}
diff --git a/src/test/java/spark/ResponseWrapperDelegationTest.java b/src/test/java/spark/ResponseWrapperDelegationTest.java
deleted file mode 100644
index f8c59b1..0000000
--- a/src/test/java/spark/ResponseWrapperDelegationTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package spark;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import spark.util.SparkTestUtil;
-import spark.util.SparkTestUtil.UrlResponse;
-
-import java.io.IOException;
-
-import static spark.Spark.*;
-
-public class ResponseWrapperDelegationTest {
-
- static SparkTestUtil testUtil;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- }
-
- @BeforeClass
- public static void setup() throws IOException {
- testUtil = new SparkTestUtil(4567);
-
- get("/204", (q, a) -> {
- a.status(204);
- return "";
- });
-
- after("/204", (q, a) -> {
- if (a.status() == 204) {
- a.status(200);
- a.body("ok");
- }
- });
-
- get("/json", (q, a) -> {
- a.type("application/json");
- return "{\"status\": \"ok\"}";
- });
-
- after("/json", (q, a) -> {
- if ("application/json".equalsIgnoreCase(a.type())) {
- a.type("text/plain");
- }
- });
-
- exception(Exception.class, (exception, q, a) -> {
- exception.printStackTrace();
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void filters_can_detect_response_status() throws Exception {
- UrlResponse response = testUtil.get("/204");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("ok", response.body);
- }
-
- @Test
- public void filters_can_detect_content_type() throws Exception {
- UrlResponse response = testUtil.get("/json");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("{\"status\": \"ok\"}", response.body);
- Assert.assertEquals("text/plain", response.headers.get("Content-Type"));
- }
-}
diff --git a/src/test/java/spark/RouteImplTest.java b/src/test/java/spark/RouteImplTest.java
deleted file mode 100644
index 88cd5cd..0000000
--- a/src/test/java/spark/RouteImplTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package spark;
-
-import org.junit.Test;
-
-import static junit.framework.TestCase.assertNull;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-public class RouteImplTest {
-
- private final static String PATH_TEST = "/opt/test";
- private final static String ACCEPT_TYPE_TEST = "*/test";
-
- private RouteImpl route;
-
- @Test
- public void testConstructor(){
- route = new RouteImpl(PATH_TEST) {
- @Override
- public Object handle(Request request, Response response) throws Exception {
- return null;
- }
- };
- assertEquals("Should return path specified", PATH_TEST, route.getPath());
- }
-
- @Test
- public void testGets_thenReturnGetPathAndGetAcceptTypeSuccessfully() throws Exception {
- route = RouteImpl.create(PATH_TEST, ACCEPT_TYPE_TEST, null);
- assertEquals("Should return path specified", PATH_TEST, route.getPath());
- assertEquals("Should return accept type specified", ACCEPT_TYPE_TEST, route.getAcceptType());
- }
-
- @Test
- public void testCreate_whenOutAssignAcceptTypeInTheParameters_thenReturnPathAndAcceptTypeSuccessfully(){
- route = RouteImpl.create(PATH_TEST, null);
- assertEquals("Should return path specified", PATH_TEST, route.getPath());
- assertEquals("Should return the default accept type", RouteImpl.DEFAULT_ACCEPT_TYPE, route.getAcceptType());
- }
-
- @Test
- public void testCreate_whenAcceptTypeNullValueInTheParameters_thenReturnPathAndAcceptTypeSuccessfully(){
- route = RouteImpl.create(PATH_TEST, null, null);
- assertEquals("Should return path specified", PATH_TEST, route.getPath());
- assertEquals("Should return the default accept type", RouteImpl.DEFAULT_ACCEPT_TYPE, route.getAcceptType());
- }
-
- @Test
- public void testRender_whenElementParameterValid_thenReturnValidObject() throws Exception {
- String finalObjValue = "object_value";
- route = RouteImpl.create(PATH_TEST, null);
- Object value = route.render(finalObjValue);
- assertNotNull("Should return an Object because we configured it to have one", value);
- assertEquals("Should return a string object specified", finalObjValue, value.toString());
- }
-
- @Test
- public void testRender_whenElementParameterIsNull_thenReturnNull() throws Exception {
- route = RouteImpl.create(PATH_TEST, null);
- Object value = route.render(null);
- assertNull("Should return null because the element from render is null", value);
- }
-}
\ No newline at end of file
diff --git a/src/test/java/spark/ServicePortIntegrationTest.java b/src/test/java/spark/ServicePortIntegrationTest.java
deleted file mode 100644
index aa81645..0000000
--- a/src/test/java/spark/ServicePortIntegrationTest.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package spark;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import spark.util.SparkTestUtil;
-
-import static spark.Service.ignite;
-
-/**
- * Created by Tom on 08/02/2017.
- */
-public class ServicePortIntegrationTest {
-
- private static Service service;
- private static final Logger LOGGER = LoggerFactory.getLogger(ServicePortIntegrationTest.class);
-
- @BeforeClass
- public static void setUpClass() throws Exception {
- service = ignite();
- service.port(0);
-
- service.get("/hi", (q, a) -> "Hello World!");
-
- service.awaitInitialization();
- }
-
- @Test
- public void testGetPort_withRandomPort() throws Exception {
- int actualPort = service.port();
-
- LOGGER.info("got port ");
-
- SparkTestUtil testUtil = new SparkTestUtil(actualPort);
-
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello World!", response.body);
- }
-
- @AfterClass
- public static void tearDown() throws Exception {
- service.stop();
- }
-}
\ No newline at end of file
diff --git a/src/test/java/spark/ServiceTest.java b/src/test/java/spark/ServiceTest.java
deleted file mode 100644
index d011976..0000000
--- a/src/test/java/spark/ServiceTest.java
+++ /dev/null
@@ -1,310 +0,0 @@
-package spark;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.eclipse.jetty.websocket.api.annotations.WebSocket;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.mockito.Mockito;
-import org.powermock.reflect.Whitebox;
-
-import spark.embeddedserver.EmbeddedServer;
-import spark.embeddedserver.EmbeddedServers;
-import spark.route.Routes;
-import spark.ssl.SslStores;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static spark.Service.ignite;
-
-public class ServiceTest {
-
- private static final String IP_ADDRESS = "127.0.0.1";
- private static final int NOT_FOUND_STATUS_CODE = HttpServletResponse.SC_NOT_FOUND;
-
- private Service service;
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Before
- public void test() {
- service = ignite();
- }
-
- @Test
- public void testEmbeddedServerIdentifier_defaultAndSet() {
- assertEquals("Should return defaultIdentifier()",
- EmbeddedServers.defaultIdentifier(),
- service.embeddedServerIdentifier());
-
- Object obj = new Object();
-
- service.embeddedServerIdentifier(obj);
-
- assertEquals("Should return expected obj",
- obj,
- service.embeddedServerIdentifier());
- }
-
- @Test
- public void testEmbeddedServerIdentifier_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done before route mapping has begun");
-
- Object obj = new Object();
-
- Whitebox.setInternalState(service, "initialized", true);
- service.embeddedServerIdentifier(obj);
- }
-
- @Test(expected = HaltException.class)
- public void testHalt_whenOutParameters_thenThrowHaltException() {
- service.halt();
- }
-
- @Test(expected = HaltException.class)
- public void testHalt_whenStatusCode_thenThrowHaltException() {
- service.halt(NOT_FOUND_STATUS_CODE);
- }
-
- @Test(expected = HaltException.class)
- public void testHalt_whenBodyContent_thenThrowHaltException() {
- service.halt("error");
- }
-
- @Test(expected = HaltException.class)
- public void testHalt_whenStatusCodeAndBodyContent_thenThrowHaltException() {
- service.halt(NOT_FOUND_STATUS_CODE, "error");
- }
-
- @Test
- public void testIpAddress_whenInitializedFalse() {
- service.ipAddress(IP_ADDRESS);
-
- String ipAddress = Whitebox.getInternalState(service, "ipAddress");
- assertEquals("IP address should be set to the IP address that was specified", IP_ADDRESS, ipAddress);
- }
-
- @Test
- public void testIpAddress_whenInitializedTrue_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done before route mapping has begun");
-
- Whitebox.setInternalState(service, "initialized", true);
- service.ipAddress(IP_ADDRESS);
- }
-
- @Test
- public void testSetIpAddress_whenInitializedFalse() {
- service.ipAddress(IP_ADDRESS);
-
- String ipAddress = Whitebox.getInternalState(service, "ipAddress");
- assertEquals("IP address should be set to the IP address that was specified", IP_ADDRESS, ipAddress);
- }
-
- @Test
- public void testSetIpAddress_whenInitializedTrue_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done before route mapping has begun");
-
- Whitebox.setInternalState(service, "initialized", true);
- service.ipAddress(IP_ADDRESS);
- }
-
- @Test
- public void testPort_whenInitializedFalse() {
- service.port(8080);
-
- int port = Whitebox.getInternalState(service, "port");
- assertEquals("Port should be set to the Port that was specified", 8080, port);
- }
-
- @Test
- public void testPort_whenInitializedTrue_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done before route mapping has begun");
-
- Whitebox.setInternalState(service, "initialized", true);
- service.port(8080);
- }
-
- @Test
- public void testSetPort_whenInitializedFalse() {
- service.port(8080);
-
- int port = Whitebox.getInternalState(service, "port");
- assertEquals("Port should be set to the Port that was specified", 8080, port);
- }
-
- @Test
- public void testSetPort_whenInitializedTrue_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done before route mapping has begun");
-
- Whitebox.setInternalState(service, "initialized", true);
- service.port(8080);
- }
-
- @Test
- public void testGetPort_whenInitializedFalse_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done after route mapping has begun");
-
- Whitebox.setInternalState(service, "initialized", false);
- service.port();
- }
-
- @Test
- public void testGetPort_whenInitializedTrue() {
- int expectedPort = 8080;
- Whitebox.setInternalState(service, "initialized", true);
- Whitebox.setInternalState(service, "port", expectedPort);
-
- int actualPort = service.port();
-
- assertEquals("Port retrieved should be the port setted", expectedPort, actualPort);
- }
-
- @Test
- public void testGetPort_whenInitializedTrue_Default() {
- int expectedPort = Service.SPARK_DEFAULT_PORT;
- Whitebox.setInternalState(service, "initialized", true);
-
- int actualPort = service.port();
-
- assertEquals("Port retrieved should be the port setted", expectedPort, actualPort);
- }
-
- @Test
- public void testThreadPool_whenOnlyMaxThreads() {
- service.threadPool(100);
- int maxThreads = Whitebox.getInternalState(service, "maxThreads");
- int minThreads = Whitebox.getInternalState(service, "minThreads");
- int threadIdleTimeoutMillis = Whitebox.getInternalState(service, "threadIdleTimeoutMillis");
- assertEquals("Should return maxThreads specified", 100, maxThreads);
- assertEquals("Should return minThreads specified", -1, minThreads);
- assertEquals("Should return threadIdleTimeoutMillis specified", -1, threadIdleTimeoutMillis);
- }
-
- @Test
- public void testThreadPool_whenMaxMinAndTimeoutParameters() {
- service.threadPool(100, 50, 75);
- int maxThreads = Whitebox.getInternalState(service, "maxThreads");
- int minThreads = Whitebox.getInternalState(service, "minThreads");
- int threadIdleTimeoutMillis = Whitebox.getInternalState(service, "threadIdleTimeoutMillis");
- assertEquals("Should return maxThreads specified", 100, maxThreads);
- assertEquals("Should return minThreads specified", 50, minThreads);
- assertEquals("Should return threadIdleTimeoutMillis specified", 75, threadIdleTimeoutMillis);
- }
-
- @Test
- public void testThreadPool_whenMaxMinAndTimeoutParameters_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done before route mapping has begun");
-
- Whitebox.setInternalState(service, "initialized", true);
- service.threadPool(100, 50, 75);
- }
-
- @Test
- public void testSecure_thenReturnNewSslStores() {
- service.secure("keyfile", "keypassword", "truststorefile", "truststorepassword");
- SslStores sslStores = Whitebox.getInternalState(service, "sslStores");
- assertNotNull("Should return a SslStores because we configured it to have one", sslStores);
- assertEquals("Should return keystoreFile from SslStores", "keyfile", sslStores.keystoreFile());
- assertEquals("Should return keystorePassword from SslStores", "keypassword", sslStores.keystorePassword());
- assertEquals("Should return trustStoreFile from SslStores", "truststorefile", sslStores.trustStoreFile());
- assertEquals("Should return trustStorePassword from SslStores", "truststorepassword", sslStores.trustStorePassword());
- }
-
- @Test
- public void testSecure_whenInitializedTrue_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done before route mapping has begun");
-
- Whitebox.setInternalState(service, "initialized", true);
- service.secure(null, null, null, null);
- }
-
- @Test
- public void testSecure_whenInitializedFalse_thenThrowIllegalArgumentException() {
- thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Must provide a keystore file to run secured");
-
- service.secure(null, null, null, null);
- }
-
- @Test
- public void testWebSocketIdleTimeoutMillis_whenInitializedTrue_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done before route mapping has begun");
-
- Whitebox.setInternalState(service, "initialized", true);
- service.webSocketIdleTimeoutMillis(100);
- }
-
- @Test
- public void testWebSocket_whenInitializedTrue_thenThrowIllegalStateException() {
- thrown.expect(IllegalStateException.class);
- thrown.expectMessage("This must be done before route mapping has begun");
-
- Whitebox.setInternalState(service, "initialized", true);
- service.webSocket("/", DummyWebSocketListener.class);
- }
-
- @Test
- public void testWebSocket_whenPathNull_thenThrowNullPointerException() {
- thrown.expect(NullPointerException.class);
- thrown.expectMessage("WebSocket path cannot be null");
- service.webSocket(null, new DummyWebSocketListener());
- }
-
- @Test
- public void testWebSocket_whenHandlerNull_thenThrowNullPointerException() {
- thrown.expect(NullPointerException.class);
- thrown.expectMessage("WebSocket handler class cannot be null");
- service.webSocket("/", null);
- }
-
- @Test(timeout = 300)
- public void stopExtinguishesServer() {
- Service service = Service.ignite();
- Routes routes = Mockito.mock(Routes.class);
- EmbeddedServer server = Mockito.mock(EmbeddedServer.class);
- service.routes = routes;
- service.server = server;
- service.initialized = true;
- service.stop();
- try {
- // yes, this is ugly and forces to set a test timeout as a precaution :(
- while (service.initialized) {
- Thread.sleep(20);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- Mockito.verify(server).extinguish();
- }
-
- @Test
- public void awaitStopBlocksUntilExtinguished() {
- Service service = Service.ignite();
- Routes routes = Mockito.mock(Routes.class);
- EmbeddedServer server = Mockito.mock(EmbeddedServer.class);
- service.routes = routes;
- service.server = server;
- service.initialized = true;
- service.stop();
- service.awaitStop();
- Mockito.verify(server).extinguish();
- assertFalse(service.initialized);
- }
-
- @WebSocket
- protected static class DummyWebSocketListener {
- }
-}
diff --git a/src/test/java/spark/SessionTest.java b/src/test/java/spark/SessionTest.java
deleted file mode 100644
index 2cf3abd..0000000
--- a/src/test/java/spark/SessionTest.java
+++ /dev/null
@@ -1,164 +0,0 @@
-package spark;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.powermock.reflect.Whitebox;
-
-import javax.servlet.http.HttpSession;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.*;
-
-public class SessionTest {
-
- Request request;
- HttpSession httpSession;
- Session session;
-
- @Before
- public void setup() {
-
- httpSession = mock(HttpSession.class);
- request = mock(Request.class);
- session = new Session(httpSession, request);
- }
-
- @Test
- public void testSession_whenHttpSessionIsNull_thenThrowException() {
-
- try {
-
- new Session(null, request);
- fail("Session instantiation with a null HttpSession should throw an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
-
- assertEquals("session cannot be null", ex.getMessage());
- }
- }
-
- @Test
- public void testSession_whenRequestIsNull_thenThrowException() {
-
- try {
-
- new Session(httpSession, null);
- fail("Session instantiation with a null Request should throw an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
-
- assertEquals("request cannot be null", ex.getMessage());
- }
- }
-
- @Test
- public void testSession() {
-
- HttpSession internalSession = Whitebox.getInternalState(session, "session");
- assertEquals("Internal session should be set to the http session provided during instantiation",
- httpSession, internalSession);
- }
-
- @Test
- public void testRaw() {
-
- assertEquals("Should return the HttpSession provided during instantiation",
- httpSession, session.raw());
- }
-
- @Test
- public void testAttribute_whenAttributeIsRetrieved() {
-
- when(httpSession.getAttribute("name")).thenReturn("Jett");
-
- assertEquals("Should return attribute from HttpSession", "Jett", session.attribute("name"));
-
- }
-
- @Test
- public void testAttribute_whenAttributeIsSet() {
-
- session.attribute("name", "Jett");
-
- verify(httpSession).setAttribute("name", "Jett");
- }
-
- @Test
- public void testAttributes() {
-
- Set<String> attributes = new HashSet<>(Arrays.asList("name", "location"));
-
- when(httpSession.getAttributeNames()).thenReturn(Collections.enumeration(attributes));
-
- assertEquals("Should return attributes from the HttpSession", attributes, session.attributes());
- }
-
- @Test
- public void testCreationTime() {
-
- when(httpSession.getCreationTime()).thenReturn(10000000l);
-
- assertEquals("Should return creationTime from HttpSession", 10000000l, session.creationTime());
- }
-
- @Test
- public void testId() {
-
- when(httpSession.getId()).thenReturn("id");
-
- assertEquals("Should return session id from HttpSession", "id", session.id());
- }
-
- @Test
- public void testLastAccessedTime() {
-
- when(httpSession.getLastAccessedTime()).thenReturn(20000000l);
-
- assertEquals("Should return lastAccessedTime from HttpSession", 20000000l, session.lastAccessedTime());
- }
-
- @Test
- public void testMaxInactiveInterval_whenRetrieved() {
-
- when(httpSession.getMaxInactiveInterval()).thenReturn(100);
-
- assertEquals("Should return maxInactiveInterval from HttpSession", 100, session.maxInactiveInterval());
- }
-
- @Test
- public void testMaxInactiveInterval_whenSet() {
-
- session.maxInactiveInterval(200);
-
- verify(httpSession).setMaxInactiveInterval(200);
- }
-
- @Test
- public void testInvalidate() {
-
- session.invalidate();
-
- verify(httpSession).invalidate();
- }
-
- @Test
- public void testIsNew() {
-
- when(httpSession.isNew()).thenReturn(true);
-
- assertEquals("Should return isNew status from HttpSession", true, session.isNew());
- }
-
- @Test
- public void testRemoveAttribute() {
-
- session.removeAttribute("name");
-
- verify(httpSession).removeAttribute("name");
- }
-}
\ No newline at end of file
diff --git a/src/test/java/spark/StaticFilesFromArchiveTest.java b/src/test/java/spark/StaticFilesFromArchiveTest.java
deleted file mode 100644
index 55f204d..0000000
--- a/src/test/java/spark/StaticFilesFromArchiveTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright 2016 - Per Wendel
- *
- * 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 spark;
-
-import static java.lang.ClassLoader.getSystemClassLoader;
-import static java.lang.System.arraycopy;
-import static org.junit.Assert.assertEquals;
-
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.net.URLClassLoader;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import spark.util.SparkTestUtil;
-import spark.util.SparkTestUtil.UrlResponse;
-
-public class StaticFilesFromArchiveTest {
-
- private static SparkTestUtil testUtil;
- private static ClassLoader classLoader;
- private static ClassLoader initialClassLoader;
-
- @BeforeClass
- public static void setup() throws Exception {
- setupClassLoader();
- testUtil = new SparkTestUtil(4567);
-
- Class<?> sparkClass = classLoader.loadClass("spark.Spark");
-
- Method staticFileLocationMethod = sparkClass.getMethod("staticFileLocation", String.class);
- staticFileLocationMethod.invoke(null, "/public-jar");
-
- Method initMethod = sparkClass.getMethod("init");
- initMethod.invoke(null);
-
- Method awaitInitializationMethod = sparkClass.getMethod("awaitInitialization");
- awaitInitializationMethod.invoke(null);
- }
-
- @AfterClass
- public static void resetClassLoader() {
- Thread.currentThread().setContextClassLoader(initialClassLoader);
- }
-
- private static void setupClassLoader() throws Exception {
- ClassLoader extendedClassLoader = createExtendedClassLoader();
- initialClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader(extendedClassLoader);
- classLoader = extendedClassLoader;
- }
-
- private static URLClassLoader createExtendedClassLoader() {
- URL[] parentURLs = ((URLClassLoader) getSystemClassLoader()).getURLs();
- URL[] urls = new URL[parentURLs.length + 1];
- arraycopy(parentURLs, 0, urls, 0, parentURLs.length);
-
- URL publicJar = StaticFilesFromArchiveTest.class.getResource("/public-jar.zip");
- urls[urls.length - 1] = publicJar;
-
- // no parent classLoader because Spark and the static resources need to be loaded from the same classloader
- return new URLClassLoader(urls, null);
- }
-
- @Test
- public void testCss() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", "/css/style.css", null);
-
- String expectedContentType = response.headers.get("Content-Type");
- assertEquals(expectedContentType, "text/css");
-
- String body = response.body;
- assertEquals("Content of css file", body);
- }
-}
diff --git a/src/test/java/spark/StaticFilesMemberTest.java b/src/test/java/spark/StaticFilesMemberTest.java
deleted file mode 100644
index a55e578..0000000
--- a/src/test/java/spark/StaticFilesMemberTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright 2015 - Per Wendel
- *
- * 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 spark;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.HashMap;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import spark.examples.exception.NotFoundException;
-import spark.util.SparkTestUtil;
-
-import static spark.Spark.exception;
-import static spark.Spark.get;
-import static spark.Spark.staticFiles;
-
-/**
- * Test static files
- */
-public class StaticFilesMemberTest {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(StaticFilesMemberTest.class);
-
- private static final String FO_SHIZZY = "Fo shizzy";
- private static final String NOT_FOUND_BRO = "Not found bro";
-
- private static final String EXTERNAL_FILE_NAME_HTML = "externalFile.html";
-
- private static final String CONTENT_OF_EXTERNAL_FILE = "Content of external file";
-
- private static SparkTestUtil testUtil;
-
- private static File tmpExternalFile;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- if (tmpExternalFile != null) {
- LOGGER.debug("tearDown().deleting: " + tmpExternalFile);
- tmpExternalFile.delete();
- }
- }
-
- @BeforeClass
- public static void setup() throws IOException {
- testUtil = new SparkTestUtil(4567);
-
- tmpExternalFile = new File(System.getProperty("java.io.tmpdir"), EXTERNAL_FILE_NAME_HTML);
-
- FileWriter writer = new FileWriter(tmpExternalFile);
- writer.write(CONTENT_OF_EXTERNAL_FILE);
- writer.flush();
- writer.close();
-
- staticFiles.location("/public");
- staticFiles.externalLocation(System.getProperty("java.io.tmpdir"));
-
- get("/hello", (q, a) -> FO_SHIZZY);
-
- get("/*", (q, a) -> {
- throw new NotFoundException();
- });
-
- exception(NotFoundException.class, (e, request, response) -> {
- response.status(404);
- response.body(NOT_FOUND_BRO);
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void testStaticFileCssStyleCss() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/css/style.css", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Content of css file", response.body);
-
- testGet();
- }
-
- @Test
- public void testStaticFileMjs() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/js/module.mjs", null);
-
- String expectedContentType = response.headers.get("Content-Type");
- Assert.assertEquals(expectedContentType, "application/javascript");
-
- String body = response.body;
- Assert.assertEquals("export default function () { console.log(\"Hello, I'm a .mjs file\"); }\n", body);
- }
-
- @Test
- public void testStaticFilePagesIndexHtml() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/pages/index.html", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("<html><body>Hello Static World!</body></html>", response.body);
-
- testGet();
- }
-
- @Test
- public void testStaticFilePageHtml() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/page.html", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("<html><body>Hello Static Files World!</body></html>", response.body);
-
- testGet();
- }
-
- @Test
- public void testExternalStaticFile() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/externalFile.html", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Content of external file", response.body);
-
- testGet();
- }
-
- @Test
- public void testStaticFileHeaders() throws Exception {
- staticFiles.headers(new HashMap() {
- {
- put("Server", "Microsoft Word");
- put("Cache-Control", "private, max-age=600");
- }
- });
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/pages/index.html", null);
- Assert.assertEquals("Microsoft Word", response.headers.get("Server"));
- Assert.assertEquals("private, max-age=600", response.headers.get("Cache-Control"));
-
- testGet();
- }
-
- @Test
- public void testStaticFileExpireTime() throws Exception {
- staticFiles.expireTime(600);
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/pages/index.html", null);
- Assert.assertEquals("private, max-age=600", response.headers.get("Cache-Control"));
-
- testGet();
- }
-
- /**
- * Used to verify that "normal" functionality works after static files mapping
- */
- private static void testGet() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/hello", "");
-
- Assert.assertEquals(200, response.status);
- Assert.assertTrue(response.body.contains(FO_SHIZZY));
- }
-
- @Test
- public void testExceptionMapping404() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/filethatdoesntexist.html", null);
-
- Assert.assertEquals(404, response.status);
- Assert.assertEquals(NOT_FOUND_BRO, response.body);
- }
-}
diff --git a/src/test/java/spark/UnmapTest.java b/src/test/java/spark/UnmapTest.java
deleted file mode 100644
index 132e4a1..0000000
--- a/src/test/java/spark/UnmapTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package spark;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-import spark.util.SparkTestUtil;
-
-import static spark.Spark.awaitInitialization;
-import static spark.Spark.get;
-import static spark.Spark.unmap;
-
-public class UnmapTest {
-
- SparkTestUtil testUtil = new SparkTestUtil(4567);
-
- @Test
- public void testUnmap() throws Exception {
- get("/tobeunmapped", (q, a) -> "tobeunmapped");
- awaitInitialization();
-
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/tobeunmapped", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("tobeunmapped", response.body);
-
- unmap("/tobeunmapped");
-
- response = testUtil.doMethod("GET", "/tobeunmapped", null);
- Assert.assertEquals(404, response.status);
-
- get("/tobeunmapped", (q, a) -> "tobeunmapped");
-
- response = testUtil.doMethod("GET", "/tobeunmapped", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("tobeunmapped", response.body);
-
- unmap("/tobeunmapped", "get");
-
- response = testUtil.doMethod("GET", "/tobeunmapped", null);
- Assert.assertEquals(404, response.status);
- }
-}
diff --git a/src/test/java/spark/customerrorpages/CustomErrorPagesTest.java b/src/test/java/spark/customerrorpages/CustomErrorPagesTest.java
deleted file mode 100644
index f7efe72..0000000
--- a/src/test/java/spark/customerrorpages/CustomErrorPagesTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package spark.customerrorpages;
-
-import java.io.IOException;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import spark.CustomErrorPages;
-import spark.Spark;
-import spark.util.SparkTestUtil;
-
-import static spark.Spark.get;
-import static spark.Spark.internalServerError;
-import static spark.Spark.notFound;
-
-public class CustomErrorPagesTest {
-
- private static final String CUSTOM_NOT_FOUND = "custom not found 404";
- private static final String CUSTOM_INTERNAL = "custom internal 500";
- private static final String HELLO_WORLD = "hello world!";
- public static final String APPLICATION_JSON = "application/json";
- private static final String QUERY_PARAM_KEY = "qparkey";
-
- static SparkTestUtil testUtil;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- }
-
- @BeforeClass
- public static void setup() throws IOException {
- testUtil = new SparkTestUtil(4567);
-
- get("/hello", (q, a) -> HELLO_WORLD);
-
- get("/raiseinternal", (q, a) -> {
- throw new Exception("");
- });
-
- notFound(CUSTOM_NOT_FOUND);
-
- internalServerError((request, response) -> {
- if (request.queryParams(QUERY_PARAM_KEY) != null) {
- throw new Exception();
- }
- response.type(APPLICATION_JSON);
- return CUSTOM_INTERNAL;
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void testGetHi() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/hello", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(HELLO_WORLD, response.body);
- }
-
- @Test
- public void testCustomNotFound() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/othernotmapped", null);
- Assert.assertEquals(404, response.status);
- Assert.assertEquals(CUSTOM_NOT_FOUND, response.body);
- }
-
- @Test
- public void testCustomInternal() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/raiseinternal", null);
- Assert.assertEquals(500, response.status);
- Assert.assertEquals(APPLICATION_JSON, response.headers.get("Content-Type"));
- Assert.assertEquals(CUSTOM_INTERNAL, response.body);
- }
-
- @Test
- public void testCustomInternalFailingRoute() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/raiseinternal?" + QUERY_PARAM_KEY + "=sumthin", null);
- Assert.assertEquals(500, response.status);
- Assert.assertEquals(CustomErrorPages.INTERNAL_ERROR, response.body);
- }
-
-}
diff --git a/src/test/java/spark/embeddedserver/EmbeddedServersTest.java b/src/test/java/spark/embeddedserver/EmbeddedServersTest.java
deleted file mode 100644
index eada4c4..0000000
--- a/src/test/java/spark/embeddedserver/EmbeddedServersTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package spark.embeddedserver;
-
-import java.io.File;
-
-import org.eclipse.jetty.server.NCSARequestLog;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.util.thread.ThreadPool;
-import org.junit.AfterClass;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-
-import spark.Spark;
-import spark.embeddedserver.jetty.EmbeddedJettyFactory;
-import spark.embeddedserver.jetty.JettyServerFactory;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class EmbeddedServersTest {
-
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
-
- @Test
- public void testAddAndCreate_whenCreate_createsCustomServer() throws Exception {
- // Create custom Server
- Server server = new Server();
- File requestLogDir = temporaryFolder.newFolder();
- File requestLogFile = new File(requestLogDir, "request.log");
- server.setRequestLog(new NCSARequestLog(requestLogFile.getAbsolutePath()));
- JettyServerFactory serverFactory = mock(JettyServerFactory.class);
- when(serverFactory.create(0, 0, 0)).thenReturn(server);
-
- String id = "custom";
-
- // Register custom server
- EmbeddedServers.add(id, new EmbeddedJettyFactory(serverFactory));
- EmbeddedServer embeddedServer = EmbeddedServers.create(id, null, null, null, false);
- assertNotNull(embeddedServer);
- embeddedServer.ignite("localhost", 0, null, 0, 0, 0);
-
- assertTrue(requestLogFile.exists());
- embeddedServer.extinguish();
- verify(serverFactory).create(0, 0, 0);
- }
-
- @Test
- public void testAdd_whenConfigureRoutes_createsCustomServer() throws Exception {
- File requestLogDir = temporaryFolder.newFolder();
- File requestLogFile = new File(requestLogDir, "request.log");
- // Register custom server
- EmbeddedServers.add(EmbeddedServers.Identifiers.JETTY, new EmbeddedJettyFactory(new JettyServerFactory() {
- @Override
- public Server create(int maxThreads, int minThreads, int threadTimeoutMillis) {
- Server server = new Server();
- server.setRequestLog(new NCSARequestLog(requestLogFile.getAbsolutePath()));
- return server;
- }
-
- @Override
- public Server create(ThreadPool threadPool) {
- return null;
- }
- }));
- Spark.get("/", (request, response) -> "OK");
- Spark.awaitInitialization();
-
- assertTrue(requestLogFile.exists());
- }
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- }
-
-}
diff --git a/src/test/java/spark/embeddedserver/jetty/EmbeddedJettyFactoryTest.java b/src/test/java/spark/embeddedserver/jetty/EmbeddedJettyFactoryTest.java
deleted file mode 100644
index ba8cea3..0000000
--- a/src/test/java/spark/embeddedserver/jetty/EmbeddedJettyFactoryTest.java
+++ /dev/null
@@ -1,104 +0,0 @@
-package spark.embeddedserver.jetty;
-
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.util.thread.QueuedThreadPool;
-import org.junit.After;
-import org.junit.Test;
-
-import spark.ExceptionMapper;
-import spark.embeddedserver.EmbeddedServer;
-import spark.route.Routes;
-import spark.staticfiles.StaticFilesConfiguration;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
-public class EmbeddedJettyFactoryTest {
-
- private EmbeddedServer embeddedServer;
-
- @Test
- public void create() throws Exception {
- final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
- final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
- final ExceptionMapper exceptionMapper = mock(ExceptionMapper.class);
- final Routes routes = mock(Routes.class);
-
- Server server = new Server();
- when(jettyServerFactory.create(100, 10, 10000)).thenReturn(server);
-
- final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory);
- embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, exceptionMapper, false);
-
- embeddedServer.ignite("localhost", 6757, null, 100, 10, 10000);
-
- verify(jettyServerFactory, times(1)).create(100, 10, 10000);
- verifyNoMoreInteractions(jettyServerFactory);
- assertTrue(((JettyHandler) server.getHandler()).getSessionCookieConfig().isHttpOnly());
- }
-
- @Test
- public void create_withThreadPool() throws Exception {
- final QueuedThreadPool threadPool = new QueuedThreadPool(100);
- final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
- final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
- final ExceptionMapper exceptionMapper = mock(ExceptionMapper.class);
- final Routes routes = mock(Routes.class);
-
- when(jettyServerFactory.create(threadPool)).thenReturn(new Server(threadPool));
-
- final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(threadPool);
- embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, exceptionMapper, false);
-
- embeddedServer.ignite("localhost", 6758, null, 0, 0, 0);
-
- verify(jettyServerFactory, times(1)).create(threadPool);
- verifyNoMoreInteractions(jettyServerFactory);
- }
-
- @Test
- public void create_withNullThreadPool() throws Exception {
- final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
- final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
- final ExceptionMapper exceptionMapper = mock(ExceptionMapper.class);
- final Routes routes = mock(Routes.class);
-
- when(jettyServerFactory.create(100, 10, 10000)).thenReturn(new Server());
-
- final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withThreadPool(null);
- embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, exceptionMapper, false);
-
- embeddedServer.ignite("localhost", 6759, null, 100, 10, 10000);
-
- verify(jettyServerFactory, times(1)).create(100, 10, 10000);
- verifyNoMoreInteractions(jettyServerFactory);
- }
-
- @Test
- public void create_withoutHttpOnly() throws Exception {
- final JettyServerFactory jettyServerFactory = mock(JettyServerFactory.class);
- final StaticFilesConfiguration staticFilesConfiguration = mock(StaticFilesConfiguration.class);
- final Routes routes = mock(Routes.class);
-
- Server server = new Server();
- when(jettyServerFactory.create(100, 10, 10000)).thenReturn(server);
-
- final EmbeddedJettyFactory embeddedJettyFactory = new EmbeddedJettyFactory(jettyServerFactory).withHttpOnly(false);
- embeddedServer = embeddedJettyFactory.create(routes, staticFilesConfiguration, false);
- embeddedServer.ignite("localhost", 6759, null, 100, 10, 10000);
-
- assertFalse(((JettyHandler) server.getHandler()).getSessionCookieConfig().isHttpOnly());
- }
-
- @After
- public void tearDown() {
- if (embeddedServer != null) {
- embeddedServer.extinguish();
- }
- }
-}
diff --git a/src/test/java/spark/embeddedserver/jetty/JettyServerTest.java b/src/test/java/spark/embeddedserver/jetty/JettyServerTest.java
deleted file mode 100644
index 1a34a03..0000000
--- a/src/test/java/spark/embeddedserver/jetty/JettyServerTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package spark.embeddedserver.jetty;
-
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.util.thread.QueuedThreadPool;
-import org.junit.Test;
-import org.powermock.reflect.Whitebox;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-public class JettyServerTest {
- @Test
- public void testCreateServer_useDefaults() {
- Server server = new JettyServer().create(0, 0, 0);
-
- QueuedThreadPool threadPool = (QueuedThreadPool) server.getThreadPool();
-
- int minThreads = Whitebox.getInternalState(threadPool, "_minThreads");
- int maxThreads = Whitebox.getInternalState(threadPool, "_maxThreads");
- int idleTimeout = Whitebox.getInternalState(threadPool, "_idleTimeout");
-
- assertEquals("Server thread pool default minThreads should be 8", 8, minThreads);
- assertEquals("Server thread pool default maxThreads should be 200", 200, maxThreads);
- assertEquals("Server thread pool default idleTimeout should be 60000", 60000, idleTimeout);
- }
-
- @Test
- public void testCreateServer_whenNonDefaultMaxThreadsOnly_thenUseDefaultMinThreadsAndTimeout() {
- Server server = new JettyServer().create(9, 0, 0);
-
- QueuedThreadPool threadPool = (QueuedThreadPool) server.getThreadPool();
-
- int minThreads = Whitebox.getInternalState(threadPool, "_minThreads");
- int maxThreads = Whitebox.getInternalState(threadPool, "_maxThreads");
- int idleTimeout = Whitebox.getInternalState(threadPool, "_idleTimeout");
-
- assertEquals("Server thread pool default minThreads should be 8", 8, minThreads);
- assertEquals("Server thread pool default maxThreads should be the same as specified", 9, maxThreads);
- assertEquals("Server thread pool default idleTimeout should be 60000", 60000, idleTimeout);
-
- }
-
- @Test
- public void testCreateServer_whenNonDefaultMaxThreads_isLessThanDefaultMinThreads() {
- try {
- new JettyServer().create(2, 0, 0);
- fail("expected IllegalArgumentException");
- }
- catch (IllegalArgumentException expected) {
- assertEquals("max threads (2) less than min threads (8)", expected.getMessage());
- }
- }
-}
diff --git a/src/test/java/spark/embeddedserver/jetty/SocketConnectorFactoryTest.java b/src/test/java/spark/embeddedserver/jetty/SocketConnectorFactoryTest.java
deleted file mode 100644
index dea1b6f..0000000
--- a/src/test/java/spark/embeddedserver/jetty/SocketConnectorFactoryTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-package spark.embeddedserver.jetty;
-
-import org.eclipse.jetty.server.ConnectionFactory;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.SslConnectionFactory;
-import org.eclipse.jetty.util.ssl.SslContextFactory;
-import org.junit.Test;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.reflect.Whitebox;
-import spark.ssl.SslStores;
-
-import java.util.Map;
-
-import static org.junit.Assert.*;
-
-public class SocketConnectorFactoryTest {
-
- @Test
- public void testCreateSocketConnector_whenServerIsNull_thenThrowException() {
-
- try {
- SocketConnectorFactory.createSocketConnector(null, "host", 80);
- fail("SocketConnector creation should have thrown an IllegalArgumentException");
- } catch(IllegalArgumentException ex) {
- assertEquals("'server' must not be null", ex.getMessage());
- }
- }
-
-
- @Test
- public void testCreateSocketConnector_whenHostIsNull_thenThrowException() {
-
- Server server = new Server();
-
- try {
- SocketConnectorFactory.createSocketConnector(server, null, 80);
- fail("SocketConnector creation should have thrown an IllegalArgumentException");
- } catch(IllegalArgumentException ex) {
- assertEquals("'host' must not be null", ex.getMessage());
- }
- }
-
- @Test
- public void testCreateSocketConnector() {
-
- final String host = "localhost";
- final int port = 8888;
-
- Server server = new Server();
- ServerConnector serverConnector = SocketConnectorFactory.createSocketConnector(server, "localhost", 8888);
-
- String internalHost = Whitebox.getInternalState(serverConnector, "_host");
- int internalPort = Whitebox.getInternalState(serverConnector, "_port");
- Server internalServerConnector = Whitebox.getInternalState(serverConnector, "_server");
-
- assertEquals("Server Connector Host should be set to the specified server", host, internalHost);
- assertEquals("Server Connector Port should be set to the specified port", port, internalPort);
- assertEquals("Server Connector Server should be set to the specified server", internalServerConnector, server);
- }
-
- @Test
- public void testCreateSecureSocketConnector_whenServerIsNull() {
-
- try {
- SocketConnectorFactory.createSecureSocketConnector(null, "localhost", 80, null);
- fail("SocketConnector creation should have thrown an IllegalArgumentException");
- } catch(IllegalArgumentException ex) {
- assertEquals("'server' must not be null", ex.getMessage());
- }
- }
-
- @Test
- public void testCreateSecureSocketConnector_whenHostIsNull() {
-
- Server server = new Server();
-
- try {
- SocketConnectorFactory.createSecureSocketConnector(server, null, 80, null);
- fail("SocketConnector creation should have thrown an IllegalArgumentException");
- } catch(IllegalArgumentException ex) {
- assertEquals("'host' must not be null", ex.getMessage());
- }
- }
-
- @Test
- public void testCreateSecureSocketConnector_whenSslStoresIsNull() {
-
- Server server = new Server();
-
- try {
- SocketConnectorFactory.createSecureSocketConnector(server, "localhost", 80, null);
- fail("SocketConnector creation should have thrown an IllegalArgumentException");
- } catch(IllegalArgumentException ex) {
- assertEquals("'sslStores' must not be null", ex.getMessage());
- }
- }
-
-
- @Test
- @PrepareForTest({ServerConnector.class})
- public void testCreateSecureSocketConnector() throws Exception {
-
- final String host = "localhost";
- final int port = 8888;
-
- final String keystoreFile = "keystoreFile.jks";
- final String keystorePassword = "keystorePassword";
- final String truststoreFile = "truststoreFile.jks";
- final String trustStorePassword = "trustStorePassword";
-
- SslStores sslStores = SslStores.create(keystoreFile, keystorePassword, truststoreFile, trustStorePassword);
-
- Server server = new Server();
-
- ServerConnector serverConnector = SocketConnectorFactory.createSecureSocketConnector(server, host, port, sslStores);
-
- String internalHost = Whitebox.getInternalState(serverConnector, "_host");
- int internalPort = Whitebox.getInternalState(serverConnector, "_port");
-
- assertEquals("Server Connector Host should be set to the specified server", host, internalHost);
- assertEquals("Server Connector Port should be set to the specified port", port, internalPort);
-
- Map<String, ConnectionFactory> factories = Whitebox.getInternalState(serverConnector, "_factories");
-
- assertTrue("Should return true because factory for SSL should have been set",
- factories.containsKey("ssl") && factories.get("ssl") != null);
-
- SslConnectionFactory sslConnectionFactory = (SslConnectionFactory) factories.get("ssl");
- SslContextFactory sslContextFactory = sslConnectionFactory.getSslContextFactory();
-
- assertEquals("Should return the Keystore file specified", keystoreFile,
- sslContextFactory.getKeyStoreResource().getFile().getName());
-
- assertEquals("Should return the Truststore file specified", truststoreFile,
- sslContextFactory.getTrustStoreResource().getFile().getName());
-
- }
-
-}
\ No newline at end of file
diff --git a/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketCreatorFactoryTest.java b/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketCreatorFactoryTest.java
deleted file mode 100644
index 4b671fe..0000000
--- a/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketCreatorFactoryTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package spark.embeddedserver.jetty.websocket;
-
-import org.eclipse.jetty.websocket.api.WebSocketAdapter;
-import org.eclipse.jetty.websocket.api.annotations.WebSocket;
-import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
-import org.junit.Test;
-
-import spark.embeddedserver.jetty.websocket.WebSocketCreatorFactory.SparkWebSocketCreator;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-public class WebSocketCreatorFactoryTest {
-
- @Test
- public void testCreateWebSocketHandler() {
- WebSocketCreator annotated =
- WebSocketCreatorFactory.create(new WebSocketHandlerClassWrapper(AnnotatedHandler.class));
- assertTrue(annotated instanceof SparkWebSocketCreator);
- assertTrue(SparkWebSocketCreator.class.cast(annotated).getHandler() instanceof AnnotatedHandler);
-
- WebSocketCreator listener =
- WebSocketCreatorFactory.create(new WebSocketHandlerClassWrapper(ListenerHandler.class));
- assertTrue(listener instanceof SparkWebSocketCreator);
- assertTrue(SparkWebSocketCreator.class.cast(listener).getHandler() instanceof ListenerHandler);
- }
-
- @Test
- public void testCannotCreateInvalidHandlers() {
- try {
- WebSocketCreatorFactory.create(new WebSocketHandlerClassWrapper(InvalidHandler.class));
- fail("Handler creation should have thrown an IllegalArgumentException");
- } catch (IllegalArgumentException ex) {
- assertEquals(
- "WebSocket handler must implement 'WebSocketListener' or be annotated as '@WebSocket'",
- ex.getMessage());
- }
- }
-
- @Test
- public void testCreate_whenInstantiationException() throws Exception {
- try {
- WebSocketCreatorFactory.create(new WebSocketHandlerClassWrapper(FailingHandler.class));
- fail("Handler creation should have thrown a RunTimeException");
- } catch(RuntimeException ex) {
- assertEquals("Could not instantiate websocket handler", ex.getMessage());
- }
-
- }
-
- @WebSocket
- class FailingHandler {
-
- }
-
- @WebSocket
- static class AnnotatedHandler {
-
- }
-
- static class ListenerHandler extends WebSocketAdapter {
-
- }
-
- static class InvalidHandler {
-
- }
-}
diff --git a/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketServletContextHandlerFactoryTest.java b/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketServletContextHandlerFactoryTest.java
deleted file mode 100644
index b61f277..0000000
--- a/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketServletContextHandlerFactoryTest.java
+++ /dev/null
@@ -1,130 +0,0 @@
-package spark.embeddedserver.jetty.websocket;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
-
-import javax.servlet.ServletContext;
-
-import org.eclipse.jetty.http.pathmap.MappedResource;
-import org.eclipse.jetty.http.pathmap.PathSpec;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.websocket.server.NativeWebSocketConfiguration;
-import org.eclipse.jetty.websocket.server.WebSocketServerFactory;
-import org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter;
-import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.powermock.api.mockito.PowerMockito;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-
-@RunWith(PowerMockRunner.class)
-public class WebSocketServletContextHandlerFactoryTest {
-
- final String webSocketPath = "/websocket";
- private ServletContextHandler servletContextHandler;
-
- @Test
- public void testCreate_whenWebSocketHandlersIsNull_thenReturnNull() throws Exception {
-
- servletContextHandler = WebSocketServletContextHandlerFactory.create(null, Optional.empty());
-
- assertNull("Should return null because no WebSocket Handlers were passed", servletContextHandler);
-
- }
-
- @Test
- public void testCreate_whenNoIdleTimeoutIsPresent() throws Exception {
-
- Map<String, WebSocketHandlerWrapper> webSocketHandlers = new HashMap<>();
-
- webSocketHandlers.put(webSocketPath, new WebSocketHandlerClassWrapper(WebSocketTestHandler.class));
-
- servletContextHandler = WebSocketServletContextHandlerFactory.create(webSocketHandlers, Optional.empty());
-
- ServletContext servletContext = servletContextHandler.getServletContext();
-
- WebSocketUpgradeFilter webSocketUpgradeFilter =
- (WebSocketUpgradeFilter) servletContext.getAttribute("org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter");
-
- assertNotNull("Should return a WebSocketUpgradeFilter because we configured it to have one", webSocketUpgradeFilter);
-
- NativeWebSocketConfiguration webSocketConfiguration =
- (NativeWebSocketConfiguration) servletContext.getAttribute(NativeWebSocketConfiguration.class.getName());
-
- MappedResource<WebSocketCreator> mappedResource = webSocketConfiguration.getMatch("/websocket");
- PathSpec pathSpec = mappedResource.getPathSpec();
-
- assertEquals("Should return the WebSocket path specified when context handler was created",
- webSocketPath, pathSpec.getDeclaration());
-
- // Because spark works on a non-initialized / non-started ServletContextHandler and WebSocketUpgradeFilter
- // the stored WebSocketCreator is wrapped for persistence through the start/stop of those contexts.
- // You cannot unwrap or cast to that WebSocketTestHandler this way.
- // Only websockets that are added during a live context can be cast this way.
- // WebSocketCreator sc = mappedResource.getResource();
- // assertTrue("Should return true because handler should be an instance of the one we passed when it was created",
- // sc.getHandler() instanceof WebSocketTestHandler);
- }
-
- @Test
- public void testCreate_whenTimeoutIsPresent() throws Exception {
-
- final Integer timeout = Integer.valueOf(1000);
-
- Map<String, WebSocketHandlerWrapper> webSocketHandlers = new HashMap<>();
-
- webSocketHandlers.put(webSocketPath, new WebSocketHandlerClassWrapper(WebSocketTestHandler.class));
-
- servletContextHandler = WebSocketServletContextHandlerFactory.create(webSocketHandlers, Optional.of(timeout));
-
- ServletContext servletContext = servletContextHandler.getServletContext();
-
- WebSocketUpgradeFilter webSocketUpgradeFilter =
- (WebSocketUpgradeFilter) servletContext.getAttribute("org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter");
-
- assertNotNull("Should return a WebSocketUpgradeFilter because we configured it to have one", webSocketUpgradeFilter);
-
- NativeWebSocketConfiguration webSocketConfiguration =
- (NativeWebSocketConfiguration) servletContext.getAttribute(NativeWebSocketConfiguration.class.getName());
-
- WebSocketServerFactory webSocketServerFactory = webSocketConfiguration.getFactory();
- assertEquals("Timeout value should be the same as the timeout specified when context handler was created",
- timeout.longValue(), webSocketServerFactory.getPolicy().getIdleTimeout());
-
- MappedResource<WebSocketCreator> mappedResource = webSocketConfiguration.getMatch("/websocket");
- PathSpec pathSpec = mappedResource.getPathSpec();
-
- assertEquals("Should return the WebSocket path specified when context handler was created",
- webSocketPath, pathSpec.getDeclaration());
-
- // Because spark works on a non-initialized / non-started ServletContextHandler and WebSocketUpgradeFilter
- // the stored WebSocketCreator is wrapped for persistence through the start/stop of those contexts.
- // You cannot unwrap or cast to that WebSocketTestHandler this way.
- // Only websockets that are added during a live context can be cast this way.
- // WebSocketCreator sc = mappedResource.getResource();
- // assertTrue("Should return true because handler should be an instance of the one we passed when it was created",
- // sc.getHandler() instanceof WebSocketTestHandler);
- }
-
- @Test
- @PrepareForTest(WebSocketServletContextHandlerFactory.class)
- public void testCreate_whenWebSocketContextHandlerCreationFails_thenThrowException() throws Exception {
-
- PowerMockito.whenNew(ServletContextHandler.class).withAnyArguments().thenThrow(new Exception(""));
-
- Map<String, WebSocketHandlerWrapper> webSocketHandlers = new HashMap<>();
-
- webSocketHandlers.put(webSocketPath, new WebSocketHandlerClassWrapper(WebSocketTestHandler.class));
-
- servletContextHandler = WebSocketServletContextHandlerFactory.create(webSocketHandlers, Optional.empty());
-
- assertNull("Should return null because Websocket context handler was not created", servletContextHandler);
-
- }
-}
diff --git a/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketTestClient.java b/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketTestClient.java
deleted file mode 100644
index 4b1fe5a..0000000
--- a/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketTestClient.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package spark.embeddedserver.jetty.websocket;
-
-import java.io.IOException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import org.eclipse.jetty.websocket.api.Session;
-import org.eclipse.jetty.websocket.api.StatusCode;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
-import org.eclipse.jetty.websocket.api.annotations.WebSocket;
-
-@WebSocket
-public class WebSocketTestClient {
- private final CountDownLatch closeLatch;
-
- public WebSocketTestClient() {
- closeLatch = new CountDownLatch(1);
- }
-
- public boolean awaitClose(int duration, TimeUnit unit) throws InterruptedException {
- return closeLatch.await(duration, unit);
- }
-
- @OnWebSocketClose
- public void onClose(int statusCode, String reason) {
- closeLatch.countDown();
- }
-
- @OnWebSocketConnect
- public void onConnect(Session session) throws IOException{
- session.getRemote().sendString("Hi Spark!");
- session.close(StatusCode.NORMAL, "Bye!");
- }
-}
diff --git a/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketTestHandler.java b/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketTestHandler.java
deleted file mode 100644
index 5295861..0000000
--- a/src/test/java/spark/embeddedserver/jetty/websocket/WebSocketTestHandler.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package spark.embeddedserver.jetty.websocket;
-
-import static java.util.Collections.synchronizedList;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.jetty.websocket.api.Session;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
-import org.eclipse.jetty.websocket.api.annotations.WebSocket;
-
-@WebSocket
-public class WebSocketTestHandler {
- public static final List<String> events = synchronizedList(new ArrayList<>());
-
- @OnWebSocketConnect
- public void connected(Session session) {
- events.add("onConnect");
- }
-
- @OnWebSocketClose
- public void closed(int statusCode, String reason) {
- events.add(String.format("onClose: %s %s", statusCode, reason));
- }
-
- @OnWebSocketMessage
- public void message(String message) {
- events.add("onMessage: " + message);
- }
-
-}
diff --git a/src/test/java/spark/examples/hello/HelloSecureWorld.java b/src/test/java/spark/examples/hello/HelloSecureWorld.java
deleted file mode 100644
index 17d2b56..0000000
--- a/src/test/java/spark/examples/hello/HelloSecureWorld.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package spark.examples.hello;
-
-import static spark.Spark.get;
-import static spark.Spark.secure;
-
-/**
- * You'll need to provide a JKS keystore as arg 0 and its password as arg 1.
- */
-public class HelloSecureWorld {
- public static void main(String[] args) {
-
- secure(args[0], args[1], null, null);
- get("/hello", (request, response) -> {
- return "Hello Secure World!";
- });
-
- }
-}
diff --git a/src/test/java/spark/examples/simple/SimpleSecureExample.java b/src/test/java/spark/examples/simple/SimpleSecureExample.java
deleted file mode 100644
index 207f683..0000000
--- a/src/test/java/spark/examples/simple/SimpleSecureExample.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2011- Per Wendel
- *
- * 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 spark.examples.simple;
-
-import spark.util.SparkTestUtil;
-
-import static spark.Spark.get;
-import static spark.Spark.halt;
-import static spark.Spark.post;
-import static spark.Spark.secure;
-
-/**
- * A simple example just showing some basic functionality.
- *
- * @author Peter Nicholls, based on (practically identical to in fact)
- * {@link spark.examples.simple.SimpleExample} by Per Wendel
- */
-public class SimpleSecureExample {
-
- public static void main(String[] args) {
-
- // port(5678); <- Uncomment this if you want spark to listen on a
- // port different than 4567.
-
- secure(
- SparkTestUtil.getKeyStoreLocation(),
- SparkTestUtil.getKeystorePassword(), null, null);
-
- get("/hello", (request, response) -> "Hello Secure World!");
-
- post("/hello", (request, response) -> "Hello Secure World: " + request.body());
-
- get("/private", (request, response) -> {
- response.status(401);
- return "Go Away!!!";
- });
-
- get("/users/:name", (request, response) -> "Selected user: " + request.params(":name"));
-
- get("/news/:section", (request, response) -> {
- response.type("text/xml");
- return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><news>"
- + request.params("section") + "</news>";
- });
-
- get("/protected", (request, response) -> {
- halt(403, "I don't think so!!!");
- return null;
- });
-
- get("/redirect", (request, response) -> {
- response.redirect("/news/world");
- return null;
- });
-
- get("/", (request, response) -> "root");
- }
-}
diff --git a/src/test/java/spark/examples/websocket/EchoWebSocket.java b/src/test/java/spark/examples/websocket/EchoWebSocket.java
deleted file mode 100644
index ac9f2cd..0000000
--- a/src/test/java/spark/examples/websocket/EchoWebSocket.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright 2011- Per Wendel
- *
- * 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 spark.examples.websocket;
-
-import java.io.IOException;
-
-import org.eclipse.jetty.websocket.api.Session;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
-import org.eclipse.jetty.websocket.api.annotations.WebSocket;
-
-@WebSocket
-public class EchoWebSocket {
- private Session session;
-
- @OnWebSocketConnect
- public void connected(Session session) {
- this.session = session;
- }
-
- @OnWebSocketClose
- public void closed(int statusCode, String reason) {
- this.session = null;
- }
-
- @OnWebSocketMessage
- public void message(String message) throws IOException {
- System.out.println("Got: " + message);
- session.getRemote().sendString(message);
- }
-}
\ No newline at end of file
diff --git a/src/test/java/spark/examples/websocket/PingWebSocket.java b/src/test/java/spark/examples/websocket/PingWebSocket.java
deleted file mode 100644
index 34ff12a..0000000
--- a/src/test/java/spark/examples/websocket/PingWebSocket.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2011- Per Wendel
- *
- * 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 spark.examples.websocket;
-
-import java.io.IOException;
-
-import org.eclipse.jetty.websocket.api.Session;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
-import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
-import org.eclipse.jetty.websocket.api.annotations.WebSocket;
-
-@WebSocket
-public class PingWebSocket {
- private Session session;
-
- @OnWebSocketConnect
- public void connected(Session session) {
- this.session = session;
- }
-
- @OnWebSocketClose
- public void closed(int statusCode, String reason) {
- this.session = null;
- }
-
- @OnWebSocketMessage
- public void message(String message) throws IOException {
- System.out.println("Got: " + message);
- if (message.equals("PING")) {
- session.getRemote().sendString("PONG");
- }
- }
-}
\ No newline at end of file
diff --git a/src/test/java/spark/examples/websocket/WebSocketExample.java b/src/test/java/spark/examples/websocket/WebSocketExample.java
deleted file mode 100644
index 7ab9a8a..0000000
--- a/src/test/java/spark/examples/websocket/WebSocketExample.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright 2011- Per Wendel
- *
- * 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 spark.examples.websocket;
-
-import static spark.Spark.init;
-import static spark.Spark.webSocket;
-
-public class WebSocketExample {
-
- public static void main(String[] args) {
- webSocket("/echo", EchoWebSocket.class);
- webSocket("/ping", PingWebSocket.class);
- init();
- }
-}
diff --git a/src/test/java/spark/globalstate/ServletFlagTest.java b/src/test/java/spark/globalstate/ServletFlagTest.java
deleted file mode 100644
index 3286258..0000000
--- a/src/test/java/spark/globalstate/ServletFlagTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package spark.globalstate;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.powermock.modules.junit4.PowerMockRunner;
-import org.powermock.reflect.Whitebox;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(PowerMockRunner.class)
-public class ServletFlagTest {
-
- @Before
- public void setup() {
-
- Whitebox.setInternalState(ServletFlag.class, "isRunningFromServlet", new AtomicBoolean(false));
- }
-
- @Test
- public void testRunFromServlet_whenDefault() throws Exception {
-
- AtomicBoolean isRunningFromServlet = Whitebox.getInternalState(ServletFlag.class, "isRunningFromServlet");
- assertFalse("Should be false because it is the default value", isRunningFromServlet.get());
- }
-
- @Test
- public void testRunFromServlet_whenExecuted() throws Exception {
-
- ServletFlag.runFromServlet();
- AtomicBoolean isRunningFromServlet = Whitebox.getInternalState(ServletFlag.class, "isRunningFromServlet");
-
- assertTrue("Should be true because it flag has been set after runFromServlet", isRunningFromServlet.get());
- }
-
- @Test
- public void testIsRunningFromServlet_whenDefault() throws Exception {
-
- assertFalse("Should be false because it is the default value", ServletFlag.isRunningFromServlet());
-
- }
-
- @Test
- public void testIsRunningFromServlet_whenRunningFromServlet() throws Exception {
-
- ServletFlag.runFromServlet();
- assertTrue("Should be true because call to runFromServlet has been made", ServletFlag.isRunningFromServlet());
- }
-}
\ No newline at end of file
diff --git a/src/test/java/spark/servlet/ServletTest.java b/src/test/java/spark/servlet/ServletTest.java
deleted file mode 100644
index 2274b49..0000000
--- a/src/test/java/spark/servlet/ServletTest.java
+++ /dev/null
@@ -1,159 +0,0 @@
-package spark.servlet;
-
-import java.util.concurrent.CountDownLatch;
-
-import org.eclipse.jetty.server.Connector;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.webapp.WebAppContext;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import spark.Spark;
-import spark.util.SparkTestUtil;
-import spark.util.SparkTestUtil.UrlResponse;
-
-public class ServletTest {
-
- private static final String SOMEPATH = "/somepath";
- private static final int PORT = 9393;
- private static final Logger LOGGER = LoggerFactory.getLogger(ServletTest.class);
-
- private static SparkTestUtil testUtil;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- if (MyApp.tmpExternalFile != null) {
- LOGGER.debug("tearDown().deleting: " + MyApp.tmpExternalFile);
- MyApp.tmpExternalFile.delete();
- }
- }
-
- @BeforeClass
- public static void setup() throws InterruptedException {
- testUtil = new SparkTestUtil(PORT);
-
- final Server server = new Server();
- ServerConnector connector = new ServerConnector(server);
-
- // Set some timeout options to make debugging easier.
- connector.setIdleTimeout(1000 * 60 * 60);
- connector.setSoLingerTime(-1);
- connector.setPort(PORT);
- server.setConnectors(new Connector[] {connector});
-
- WebAppContext bb = new WebAppContext();
- bb.setServer(server);
- bb.setContextPath(SOMEPATH);
- bb.setWar("src/test/webapp");
-
- server.setHandler(bb);
- CountDownLatch latch = new CountDownLatch(1);
-
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- LOGGER.info(">>> STARTING EMBEDDED JETTY SERVER for jUnit testing of SparkFilter");
- server.start();
- latch.countDown();
- System.in.read();
- LOGGER.info(">>> STOPPING EMBEDDED JETTY SERVER");
- server.stop();
- server.join();
- } catch (Exception e) {
- e.printStackTrace();
- System.exit(100);
- }
- }
- }).start();
-
- latch.await();
- }
-
- @Test
- public void testGetHi() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", SOMEPATH + "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello World!", response.body);
- }
-
- @Test
- public void testHiHead() throws Exception {
- UrlResponse response = testUtil.doMethod("HEAD", SOMEPATH + "/hi", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("", response.body);
- }
-
- @Test
- public void testGetHiAfterFilter() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", SOMEPATH + "/hi", null);
- Assert.assertTrue(response.headers.get("after").contains("foobar"));
- }
-
- @Test
- public void testGetRoot() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", SOMEPATH + "/", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Hello Root!", response.body);
- }
-
- @Test
- public void testEchoParam1() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", SOMEPATH + "/shizzy", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: shizzy", response.body);
- }
-
- @Test
- public void testEchoParam2() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", SOMEPATH + "/gunit", null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("echo: gunit", response.body);
- }
-
- @Test
- public void testUnauthorized() throws Exception {
- UrlResponse urlResponse = testUtil.doMethod("GET", SOMEPATH + "/protected/resource", null);
- Assert.assertTrue(urlResponse.status == 401);
- }
-
- @Test
- public void testNotFound() throws Exception {
- UrlResponse urlResponse = testUtil.doMethod("GET", SOMEPATH + "/no/resource", null);
- Assert.assertTrue(urlResponse.status == 404);
- }
-
- @Test
- public void testPost() throws Exception {
- UrlResponse response = testUtil.doMethod("POST", SOMEPATH + "/poster", "Fo shizzy");
- Assert.assertEquals(201, response.status);
- Assert.assertTrue(response.body.contains("Fo shizzy"));
- }
-
- @Test
- public void testStaticResource() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", SOMEPATH + "/css/style.css", null);
- Assert.assertEquals(200, response.status);
- Assert.assertTrue(response.body.contains("Content of css file"));
- }
-
- @Test
- public void testStaticWelcomeResource() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", SOMEPATH + "/pages/", null);
- Assert.assertEquals(200, response.status);
- Assert.assertTrue(response.body.contains("<html><body>Hello Static World!</body></html>"));
- }
-
- @Test
- public void testExternalStaticFile() throws Exception {
- UrlResponse response = testUtil.doMethod("GET", SOMEPATH + "/" + MyApp.EXTERNAL_FILE, null);
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("Content of external file", response.body);
- }
-}
diff --git a/src/test/java/spark/staticfiles/DisableMimeGuessingTest.java b/src/test/java/spark/staticfiles/DisableMimeGuessingTest.java
deleted file mode 100644
index d88ec54..0000000
--- a/src/test/java/spark/staticfiles/DisableMimeGuessingTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright 2015 - Per Wendel
- *
- * 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 spark.staticfiles;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import spark.Spark;
-import spark.examples.exception.NotFoundException;
-import spark.util.SparkTestUtil;
-
-import static spark.Spark.get;
-import static spark.Spark.staticFiles;
-
-/**
- * Test static files
- */
-public class DisableMimeGuessingTest {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(StaticFilesTest.class);
-
- private static final String FO_SHIZZY = "Fo shizzy";
- private static final String EXTERNAL_FILE_NAME_HTML = "externalFile.html";
- private static final String CONTENT_OF_EXTERNAL_FILE = "Content of external file";
-
- private static SparkTestUtil testUtil;
-
- private static File tmpExternalFile;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- if (tmpExternalFile != null) {
- LOGGER.debug("tearDown().deleting: " + tmpExternalFile);
- tmpExternalFile.delete();
- }
- }
-
- @BeforeClass
- public static void setup() throws IOException {
- testUtil = new SparkTestUtil(4567);
-
- tmpExternalFile = new File(System.getProperty("java.io.tmpdir"), EXTERNAL_FILE_NAME_HTML);
-
- FileWriter writer = new FileWriter(tmpExternalFile);
- writer.write(CONTENT_OF_EXTERNAL_FILE);
- writer.flush();
- writer.close();
-
- staticFiles.location("/public");
- staticFiles.externalLocation(System.getProperty("java.io.tmpdir"));
- staticFiles.disableMimeTypeGuessing();
-
- get("/hello", (q, a) -> FO_SHIZZY);
-
- get("/*", (q, a) -> {
- throw new NotFoundException();
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void testMimeTypes() throws Exception {
- Assert.assertNull(doGet("/pages/index.html").headers.get("Content-Type"));
- Assert.assertNull(doGet("/js/scripts.js").headers.get("Content-Type"));
- Assert.assertNull(doGet("/css/style.css").headers.get("Content-Type"));
- Assert.assertNull(doGet("/img/sparklogo.png").headers.get("Content-Type"));
- Assert.assertNull(doGet("/img/sparklogo.svg").headers.get("Content-Type"));
- Assert.assertNull(doGet("/img/sparklogoPng").headers.get("Content-Type"));
- Assert.assertNull(doGet("/img/sparklogoSvg").headers.get("Content-Type"));
- Assert.assertNull(doGet("/externalFile.html").headers.get("Content-Type"));
- }
-
- @Test
- public void testCustomMimeType() throws Exception {
- staticFiles.registerMimeType("cxt", "custom-extension-type");
- Assert.assertNull(doGet("/img/file.cxt").headers.get("Content-Type"));
- }
-
- private SparkTestUtil.UrlResponse doGet(String fileName) throws Exception {
- return testUtil.doMethod("GET", fileName, null);
- }
-
-}
diff --git a/src/test/java/spark/staticfiles/StaticFilesTest.java b/src/test/java/spark/staticfiles/StaticFilesTest.java
deleted file mode 100644
index d338d2f..0000000
--- a/src/test/java/spark/staticfiles/StaticFilesTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright 2015 - Per Wendel
- *
- * 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 spark.staticfiles;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.net.URLEncoder;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import spark.Spark;
-import spark.examples.exception.NotFoundException;
-import spark.util.SparkTestUtil;
-
-import static spark.Spark.exception;
-import static spark.Spark.get;
-import static spark.Spark.staticFiles;
-
-/**
- * Test static files
- */
-public class StaticFilesTest {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(StaticFilesTest.class);
-
- private static final String FO_SHIZZY = "Fo shizzy";
- private static final String NOT_FOUND_BRO = "Not found bro";
-
- private static final String EXTERNAL_FILE_NAME_HTML = "externalFile.html";
-
- private static final String CONTENT_OF_EXTERNAL_FILE = "Content of external file";
-
- private static SparkTestUtil testUtil;
-
- private static File tmpExternalFile;
-
- @AfterClass
- public static void tearDown() {
- Spark.stop();
- if (tmpExternalFile != null) {
- LOGGER.debug("tearDown().deleting: " + tmpExternalFile);
- tmpExternalFile.delete();
- }
- }
-
- @BeforeClass
- public static void setup() throws IOException {
- testUtil = new SparkTestUtil(4567);
-
- tmpExternalFile = new File(System.getProperty("java.io.tmpdir"), EXTERNAL_FILE_NAME_HTML);
-
- FileWriter writer = new FileWriter(tmpExternalFile);
- writer.write(CONTENT_OF_EXTERNAL_FILE);
- writer.flush();
- writer.close();
-
- staticFiles.location("/public");
- staticFiles.externalLocation(System.getProperty("java.io.tmpdir"));
-
- get("/hello", (q, a) -> FO_SHIZZY);
-
- get("/*", (q, a) -> {
- throw new NotFoundException();
- });
-
- exception(NotFoundException.class, (e, request, response) -> {
- response.status(404);
- response.body(NOT_FOUND_BRO);
- });
-
- Spark.awaitInitialization();
- }
-
- @Test
- public void testMimeTypes() throws Exception {
- Assert.assertEquals("text/html", doGet("/pages/index.html").headers.get("Content-Type"));
- Assert.assertEquals("application/javascript", doGet("/js/scripts.js").headers.get("Content-Type"));
- Assert.assertEquals("text/css", doGet("/css/style.css").headers.get("Content-Type"));
- Assert.assertEquals("image/png", doGet("/img/sparklogo.png").headers.get("Content-Type"));
- Assert.assertEquals("image/svg+xml", doGet("/img/sparklogo.svg").headers.get("Content-Type"));
- Assert.assertEquals("application/octet-stream", doGet("/img/sparklogoPng").headers.get("Content-Type"));
- Assert.assertEquals("application/octet-stream", doGet("/img/sparklogoSvg").headers.get("Content-Type"));
- Assert.assertEquals("text/html", doGet("/externalFile.html").headers.get("Content-Type"));
- }
-
- @Test
- public void testCustomMimeType() throws Exception {
- staticFiles.registerMimeType("cxt", "custom-extension-type");
- Assert.assertEquals("custom-extension-type", doGet("/img/file.cxt").headers.get("Content-Type"));
- }
-
- @Test
- public void testStaticFileCssStyleCss() throws Exception {
- SparkTestUtil.UrlResponse response = doGet("/css/style.css");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("text/css", response.headers.get("Content-Type"));
- Assert.assertEquals("Content of css file", response.body);
-
- testGet();
- }
-
- @Test
- public void testStaticFilePagesIndexHtml() throws Exception {
- SparkTestUtil.UrlResponse response = doGet("/pages/index.html");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("<html><body>Hello Static World!</body></html>", response.body);
-
- testGet();
- }
-
- @Test
- public void testStaticFilePageHtml() throws Exception {
- SparkTestUtil.UrlResponse response = doGet("/page.html");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals("<html><body>Hello Static Files World!</body></html>", response.body);
-
- testGet();
- }
-
- @Test
- public void testDirectoryTraversalProtectionLocal() throws Exception {
- String path = "/" + URLEncoder.encode("..\\spark\\", "UTF-8") + "Spark.class";
- SparkTestUtil.UrlResponse response = doGet(path);
-
- Assert.assertEquals(400, response.status);
-
- testGet();
- }
-
- @Test
- public void testExternalStaticFile() throws Exception {
- SparkTestUtil.UrlResponse response = doGet("/externalFile.html");
- Assert.assertEquals(200, response.status);
- Assert.assertEquals(CONTENT_OF_EXTERNAL_FILE, response.body);
-
- testGet();
- }
-
- /**
- * Used to verify that "normal" functionality works after static files mapping
- */
- private static void testGet() throws Exception {
- SparkTestUtil.UrlResponse response = testUtil.doMethod("GET", "/hello", "");
-
- Assert.assertEquals(200, response.status);
- Assert.assertTrue(response.body.contains(FO_SHIZZY));
- }
-
- @Test
- public void testExceptionMapping404() throws Exception {
- SparkTestUtil.UrlResponse response = doGet("/filethatdoesntexist.html");
-
- Assert.assertEquals(404, response.status);
- Assert.assertEquals(NOT_FOUND_BRO, response.body);
- }
-
- private SparkTestUtil.UrlResponse doGet(String fileName) throws Exception {
- return testUtil.doMethod("GET", fileName, null);
- }
-
-}