Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unit Testing the Embedded Examples #4056

Merged
merged 14 commits into from
Sep 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion examples/embedded/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,12 @@
<dependency>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-test-helper</artifactId>
<!-- scope>test</scope-->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
Expand All @@ -141,8 +146,27 @@
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-distribution</artifactId>
<version>${project.version}</version>
<type>tar.gz</type>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<useManifestOnlyJar>false</useManifestOnlyJar>
</configuration>
</plugin>
</plugins>
</build>

<profiles>
<profile>
<id>jdk9</id>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
Expand All @@ -35,7 +34,7 @@ public class AsyncEchoServlet extends HttpServlet
private static final long serialVersionUID = 1L;

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException
{
AsyncContext asyncContext = request.startAsync(request, response);
asyncContext.setTimeout(0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Expand All @@ -45,12 +47,28 @@ protected void doGet(HttpServletRequest request,
out.println("pathInfo=" + request.getPathInfo());
out.println("session=" + request.getSession(true).getId());

ServletContext servletContext = getServletContext();

String r = request.getParameter("resource");
if (r != null)
{
out.println("resource(" + r + ")=" + getServletContext().getResource(r));
out.println("resource(" + r + ")=" + servletContext.getResource(r));
}

Collections.list(request.getAttributeNames())
.stream()
.filter((name) -> name.startsWith("X-"))
.sorted()
.forEach((name) ->
out.println("request.attribute[" + name + "]=" + request.getAttribute(name)));

Collections.list(servletContext.getAttributeNames())
.stream()
.filter((name) -> name.startsWith("X-"))
.sorted()
.forEach((name) ->
out.println("servletContext.attribute[" + name + "]=" + servletContext.getAttribute(name)));

out.println("</pre>");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@

public class ExampleServer
{
public static void main(String[] args) throws Exception
public static Server createServer(int port)
{
Server server = new Server();

ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
connector.setPort(port);
server.setConnectors(new Connector[]{connector});

ServletContextHandler context = new ServletContextHandler();
Expand All @@ -45,6 +45,13 @@ public static void main(String[] args) throws Exception
handlers.setHandlers(new Handler[]{context, new DefaultHandler()});
server.setHandler(handlers);

return server;
}

public static void main(String[] args) throws Exception
{
int port = ExampleUtil.getPort(args, "jetty.http.port", 8080);
Server server = createServer(port);
server.start();
server.join();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,31 @@

package org.eclipse.jetty.embedded;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.xml.XmlConfiguration;

/**
* Configures and Starts a Jetty server from an XML declaration.
* <p>
* See <a href="https://raw.githubusercontent.com/eclipse/jetty.project/master/examples/embedded/src/main/resources/exampleserver.xml">exampleserver.xml</a>
* </p>
*/
public class ExampleServerXml
{
public static void main(String[] args) throws Exception
public static Server createServer(int port) throws Exception
{
// Find Jetty XML (in classpath) that configures and starts Server.
// See src/main/resources/exampleserver.xml
Resource serverXml = Resource.newSystemResource("exampleserver.xml");
XmlConfiguration.main(serverXml.getFile().getAbsolutePath());
XmlConfiguration xml = new XmlConfiguration(serverXml);
xml.getProperties().put("http.port", Integer.toString(port));
Server server = (Server)xml.configure();
return server;
}

public static void main(String[] args) throws Exception
{
int port = ExampleUtil.getPort(args, "jetty.http.port", 8080);
Server server = createServer(port);
server.start();
server.join();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//

package org.eclipse.jetty.embedded;

import org.eclipse.jetty.util.StringUtil;

public class ExampleUtil
{
/**
* Get a port, possibly configured from Command line or System property.
*
* @param args the command line arguments
* @param propertyName the property name
* @param defValue the default value
* @return the configured port
*/
public static int getPort(String[] args, String propertyName, int defValue)
{
for (String arg : args)
{
if (arg.startsWith(propertyName + "="))
{
String value = arg.substring(propertyName.length() + 2);
int port = toInt(value);
if (isValidPort(port))
return port;
}
}

String value = System.getProperty(propertyName);
int port = toInt(value);
if (isValidPort(port))
return port;

return defValue;
}

/**
* Test if port is in the valid range to be used.
*
* @param port the port to test
* @return true if valid
*/
private static boolean isValidPort(int port)
{
return (port >= 0) && (port <= 65535);
}

/**
* Parse an int, ignoring any {@link NumberFormatException}
*
* @param value the string value to parse
* @return the int (if parsed), or -1 if not parsed.
*/
private static int toInt(String value)
{
if (StringUtil.isBlank(value))
return -1;

try
{
return Integer.parseInt(value);
}
catch (NumberFormatException ignored)
{
// ignored
return -1;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,24 @@
*/
public class FastFileServer
{
public static void main(String[] args) throws Exception
public static Server createServer(int port, File resourceBase)
{
Server server = new Server(8080);
Server server = new Server(port);

HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{
new FastFileHandler(new File(System.getProperty("user.dir"))),
new FastFileHandler(resourceBase),
new DefaultHandler()
});
server.setHandler(handlers);
return server;
}

public static void main(String[] args) throws Exception
{
int port = ExampleUtil.getPort(args, "jetty.http.port", 8080);
File directory = new File(System.getProperty("user.dir"));
Server server = createServer(port, directory);
server.start();
server.join();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,29 @@

package org.eclipse.jetty.embedded;

import java.nio.file.Path;
import java.nio.file.Paths;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.util.resource.PathResource;
import org.eclipse.jetty.util.resource.Resource;

/**
* Simple Jetty FileServer.
* This is a simple example of Jetty configured as a FileServer.
*/
public class FileServer
{
public static void main(String[] args) throws Exception
public static Server createServer(int port, Resource baseResource) throws Exception
{
// Create a basic Jetty server object that will listen on port 8080. Note that if you set this to port 0
// then a randomly available port will be assigned that you can either look in the logs for the port,
// or programmatically obtain it for use in test cases.
Server server = new Server(8080);
Server server = new Server(port);

// Create the ResourceHandler. It is the object that will actually handle the request for a given file. It is
// a Jetty Handler object so it is suitable for chaining with other handlers as you will see in other examples.
Expand All @@ -45,13 +50,24 @@ public static void main(String[] args) throws Exception
// In this example it is the current directory but it can be configured to anything that the jvm has access to.
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resourceHandler.setResourceBase(".");
resourceHandler.setBaseResource(baseResource);

// Add the ResourceHandler to the server.
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{resourceHandler, new DefaultHandler()});
server.setHandler(handlers);

return server;
}

public static void main(String[] args) throws Exception
{
int port = ExampleUtil.getPort(args, "jetty.http.port", 8080);
Path userDir = Paths.get(System.getProperty("user.dir"));
PathResource pathResource = new PathResource(userDir);

Server server = createServer(port, pathResource);

// Start things up! By using the server.join() the server thread will join with the current thread.
// See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details.
server.start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@

package org.eclipse.jetty.embedded;

import java.nio.file.Path;
import java.nio.file.Paths;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.xml.XmlConfiguration;
Expand All @@ -28,17 +31,25 @@
* This server is identical to {@link FileServer}, except that it is configured
* via an {@link XmlConfiguration} config file that does the identical work.
* </p>
* <p>
* See <a href="https://raw.githubusercontent.com/eclipse/jetty.project/master/examples/embedded/src/main/resources/fileserver.xml">fileserver.xml</a>
* </p>
*/
public class FileServerXml
{
public static void main(String[] args) throws Exception
public static Server createServer(int port, Path baseResource) throws Exception
{
// Find Jetty XML (in classpath) that configures and starts Server.
// See src/main/resources/fileserver.xml
Resource fileServerXml = Resource.newSystemResource("fileserver.xml");
XmlConfiguration configuration = new XmlConfiguration(fileServerXml);
Server server = (Server)configuration.configure();
configuration.getProperties().put("http.port", Integer.toString(port));
configuration.getProperties().put("fileserver.baseresource", baseResource.toAbsolutePath().toString());
return (Server)configuration.configure();
}

public static void main(String[] args) throws Exception
{
int port = ExampleUtil.getPort(args, "jetty.http.port", 8080);
Path userDir = Paths.get(System.getProperty("user.dir"));
Server server = createServer(port, userDir);
server.start();
server.join();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ public void handle(String target,

public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
int port = ExampleUtil.getPort(args, "jetty.http.port", 8080);
Server server = new Server(port);
server.setHandler(new HelloWorld());

server.start();
Expand Down
Loading