Making embedded examples more consistent.

+ appearance (similar syntax on all examples)
+ declarations (if a variable is used, use it consistently across all of
  the examples)
+ line wrap at 80 columns (so that examples make sense when copy/pasted
  around for discussion. like github)
+ updating javadoc comments to be consistent
This commit is contained in:
Joakim Erdfelt 2014-11-07 10:09:41 -07:00
parent 9320e9e24a
commit a1d8a7a121
32 changed files with 1149 additions and 871 deletions

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
import java.io.IOException;
@ -29,23 +29,30 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
public class HelloWorld extends AbstractHandler
{
@Override
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
public void handle( String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
ServletException
{
response.setContentType("text/html;charset=utf-8");
// Declare response encoding and types
response.setContentType("text/html; charset=utf-8");
// Declare response status code
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
// Write back response
response.getWriter().println("<h1>Hello World</h1>");
// Inform jetty that this request has now been handled
baseRequest.setHandled(true);
}
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
server.setHandler(new HelloWorld());
server.start();
server.join();
}

View File

@ -1,24 +1,25 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
@ -28,26 +29,31 @@ import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class DumpServlet extends HttpServlet
{
public DumpServlet()
{
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>DumpServlet</h1><pre>");
response.getWriter().println("requestURI=" + request.getRequestURI());
response.getWriter().println("contextPath=" + request.getContextPath());
response.getWriter().println("servletPath=" + request.getServletPath());
response.getWriter().println("pathInfo=" + request.getPathInfo());
response.getWriter().println("session=" + request.getSession(true).getId());
String r=request.getParameter("resource");
if (r!=null)
response.getWriter().println("resource("+r+")=" + getServletContext().getResource(r));
response.getWriter().println("</pre>");
PrintWriter out = response.getWriter();
out.println("<h1>DumpServlet</h1>");
out.println("<pre>");
out.println("requestURI=" + request.getRequestURI());
out.println("contextPath=" + request.getContextPath());
out.println("servletPath=" + request.getServletPath());
out.println("pathInfo=" + request.getPathInfo());
out.println("session=" + request.getSession(true).getId());
String r = request.getParameter("resource");
if (r != null)
{
out.println("resource(" + r + ")="
+ getServletContext().getResource(r));
}
out.println("</pre>");
}
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -25,24 +25,23 @@ import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class ExampleServer
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server();
ServerConnector connector=new ServerConnector(server);
ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
server.setConnectors(new Connector[]{connector});
server.setConnectors(new Connector[] { connector });
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/hello");
context.addServlet(HelloServlet.class,"/");
context.addServlet(HelloServlet.class, "/");
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[]{context,new DefaultHandler()});
handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
server.setHandler(handlers);
server.start();

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -21,11 +21,20 @@ package org.eclipse.jetty.embedded;
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=
* "http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/resources/exampleserver.xml"
* >exampleserver.xml</a>
* </p>
*/
public class ExampleServerXml
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Resource fileserver_xml = Resource.newSystemResource("exampleserver.xml");
XmlConfiguration.main(fileserver_xml.getFile().getAbsolutePath());
// Find Jetty XML (in classpath) that configures and starts Server.
Resource serverXml = Resource.newSystemResource("exampleserver.xml");
XmlConfiguration.main(serverXml.getFile().getAbsolutePath());
}
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -39,31 +39,32 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
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.servlet.DefaultServlet;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.resource.Resource;
/* ------------------------------------------------------------ */
/** Fast FileServer.
*
* <p>This example shows how to use the Jetty APIs for sending static
* as fast as possible using various strategies for small, medium and
* large content.</p>
* <p>The Jetty {@link DefaultServlet} does all this and more, and to
* a lesser extent so does the {@link ResourceHandler}, so unless you
* have exceptional circumstances it is best to use those classes for
* static content</p>
/**
* Fast FileServer.
* <p>
* This example shows how to use the Jetty APIs for sending static as fast as
* possible using various strategies for small, medium and large content.
* </p>
* <p>
* The Jetty {@link DefaultServlet} does all this and more, and to a lesser
* extent so does the {@link ResourceHandler}, so unless you have exceptional
* circumstances it is best to use those classes for static content
* </p>
*/
public class FastFileServer
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { new FastFileHandler(new File(".")), new DefaultHandler() });
handlers.setHandlers(new Handler[] {
new FastFileHandler(new File(System.getProperty("user.dir"))),
new DefaultHandler() });
server.setHandler(handlers);
server.start();
@ -72,65 +73,74 @@ public class FastFileServer
static class FastFileHandler extends AbstractHandler
{
private final MimeTypes _mimeTypes = new MimeTypes();
private final File _dir;
FastFileHandler(File dir)
private final MimeTypes mimeTypes = new MimeTypes();
private final File dir;
private FastFileHandler( File dir )
{
_dir=dir;
this.dir = dir;
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
public void handle( String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
ServletException
{
// define small medium and large.
// This should be turned for your content, JVM and OS, but we will huge HTTP response buffer size as a measure
final int SMALL=response.getBufferSize();
final int MEDIUM=8*SMALL;
// define small medium and large.
// This should be turned for your content, JVM and OS, but we will
// huge HTTP response buffer size as a measure
final int SMALL = response.getBufferSize();
final int MEDIUM = 8 * SMALL;
// What file to serve?
final File file = new File(_dir,request.getPathInfo());
final File file = new File(this.dir, request.getPathInfo());
// Only handle existing files
if (!file.exists())
return;
// we will handle this request
baseRequest.setHandled(true);
// Handle directories
if (file.isDirectory())
{
if (!request.getPathInfo().endsWith(URIUtil.SLASH))
{
response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH)));
response.sendRedirect(response.encodeRedirectURL(URIUtil
.addPaths(request.getRequestURI(), URIUtil.SLASH)));
return;
}
String listing = Resource.newResource(file).getListHTML(request.getRequestURI(),request.getPathInfo().lastIndexOf("/") > 0);
response.setContentType("text/html; charset=UTF-8");
String listing = Resource.newResource(file).getListHTML(
request.getRequestURI(),
request.getPathInfo().lastIndexOf("/") > 0);
response.setContentType("text/html; charset=utf-8");
response.getWriter().println(listing);
return;
}
// Set some content headers.
// Set some content headers
// Jetty DefaultServlet will cache formatted date strings, but we will reformat for each request here
response.setDateHeader("Last-Modified",file.lastModified());
response.setDateHeader("Content-Length",file.length());
response.setContentType(_mimeTypes.getMimeByExtension(file.getName()));
// Jetty DefaultServlet will cache formatted date strings, but we
// will reformat for each request here
response.setDateHeader("Last-Modified", file.lastModified());
response.setDateHeader("Content-Length", file.length());
response.setContentType(mimeTypes.getMimeByExtension(file.getName()));
// send "small" files blocking directly from an input stream
if (file.length()<SMALL)
if (file.length() < SMALL)
{
// need to caste to Jetty output stream for best API
((HttpOutput)response.getOutputStream()).sendContent(FileChannel.open(file.toPath(),StandardOpenOption.READ));
((HttpOutput) response.getOutputStream())
.sendContent(FileChannel.open(file.toPath(),
StandardOpenOption.READ));
return;
}
// send not "small" files asynchronously so we don't hold threads if the client is slow
// send not "small" files asynchronously so we don't hold threads if
// the client is slow
final AsyncContext async = request.startAsync();
Callback completionCB = new Callback()
{
@ -142,41 +152,43 @@ public class FastFileServer
}
@Override
public void failed(Throwable x)
public void failed( Throwable x )
{
// log error and complete async response;
x.printStackTrace();
async.complete();
}
};
// send "medium" files from an input stream
if (file.length()<MEDIUM)
if (file.length() < MEDIUM)
{
// the file channel is closed by the async send
((HttpOutput)response.getOutputStream()).sendContent(FileChannel.open(file.toPath(),StandardOpenOption.READ),completionCB);
((HttpOutput) response.getOutputStream())
.sendContent(FileChannel.open(file.toPath(),
StandardOpenOption.READ), completionCB);
return;
}
// for "large" files get the file mapped buffer to send
// Typically the resulting buffer should be cached as allocating kernel memory
// can be hard to GC on some JVMs. But for this example we will create a new buffer per file
ByteBuffer buffer;
try (RandomAccessFile raf = new RandomAccessFile(file,"r");)
{
buffer=raf.getChannel().map(MapMode.READ_ONLY,0,raf.length());
}
// Assuming the file buffer might be shared cached version, so lets take our own view of it
buffer=buffer.asReadOnlyBuffer();
// send the content as a buffer with a callback to complete the async request
// need to caste to Jetty output stream for best API
((HttpOutput)response.getOutputStream()).sendContent(buffer,completionCB);
}
// for "large" files get the file mapped buffer to send Typically
// the resulting buffer should be cached as allocating kernel memory
// can be hard to GC on some JVMs. But for this example we will
// create a new buffer per file
ByteBuffer buffer;
try ( RandomAccessFile raf = new RandomAccessFile(file, "r"); )
{
buffer = raf.getChannel().map(MapMode.READ_ONLY, 0,
raf.length());
}
// Assuming the file buffer might be shared cached version, so lets
// take our own view of it
buffer = buffer.asReadOnlyBuffer();
// send the content as a buffer with a callback to complete the
// async request need to caste to Jetty output stream for best API
((HttpOutput) response.getOutputStream()).sendContent(buffer,
completionCB);
}
}
}

View File

@ -24,8 +24,8 @@ import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
/* ------------------------------------------------------------ */
/** Simple Jetty FileServer.
/**
* Simple Jetty FileServer.
* This is a simple example of Jetty configured as a FileServer.
*/
public class FileServer
@ -56,5 +56,4 @@ public class FileServer
server.start();
server.join();
}
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -22,22 +22,26 @@ import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.xml.XmlConfiguration;
/* ------------------------------------------------------------ */
/** A Jetty FileServer.
* This server is identical to {@link FileServer}, except that it
* is configured via an {@link XmlConfiguration} config file that
* does the identical work.
/**
* A Jetty FileServer.
* <p>
* See <a href="http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/example-jetty-embedded/src/main/resources/fileserver.xml">fileserver.xml</a>
* 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=
* "http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/resources/fileserver.xml"
* >fileserver.xml</a>
* </p>
*/
public class FileServerXml
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Resource fileserver_xml = Resource.newSystemResource("fileserver.xml");
XmlConfiguration configuration = new XmlConfiguration(fileserver_xml.getInputStream());
Server server = (Server)configuration.configure();
Resource fileserverXml = Resource.newSystemResource("fileserver.xml");
XmlConfiguration configuration = new XmlConfiguration(
fileserverXml.getInputStream());
Server server = (Server) configuration.configure();
server.start();
server.join();
}

View File

@ -1,24 +1,25 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -29,35 +30,42 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
public class HelloHandler extends AbstractHandler
{
final String _greeting;
final String _body;
final String greeting;
final String body;
public HelloHandler()
{
_greeting="Hello World";
_body=null;
this("Hello World");
}
public HelloHandler(String greeting)
public HelloHandler( String greeting )
{
_greeting=greeting;
_body=null;
this(greeting, null);
}
public HelloHandler(String greeting,String body)
public HelloHandler( String greeting, String body )
{
_greeting=greeting;
_body=body;
this.greeting = greeting;
this.body = body;
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
public void handle( String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
ServletException
{
response.setContentType("text/html;charset=utf-8");
response.setContentType("text/html; charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>"+_greeting+"</h1>");
if (_body!=null)
response.getWriter().println(_body);
PrintWriter out = response.getWriter();
out.println("<h1>" + greeting + "</h1>");
if (body != null)
{
out.println(body);
}
baseRequest.setHandled(true);
}
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -28,22 +28,26 @@ import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class HelloServlet extends HttpServlet
{
String greeting = "Hello";
final String greeting;
public HelloServlet()
{
this("Hello");
}
public HelloServlet(String hi)
public HelloServlet( String greeting )
{
greeting = hi;
this.greeting = greeting;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>" + greeting + " from HelloServlet</h1>");
response.getWriter().println(
"<h1>" + greeting + " from HelloServlet</h1>");
}
}

View File

@ -18,6 +18,8 @@
package org.eclipse.jetty.embedded;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.management.ManagementFactory;
import org.eclipse.jetty.deploy.DeploymentManager;
@ -34,7 +36,6 @@ import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.AsyncDelayHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
@ -45,14 +46,36 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.eclipse.jetty.webapp.Configuration;
/**
* Starts the Jetty Distribution's demo-base directory using entirely
* embedded jetty techniques.
*/
public class LikeJettyXml
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
String jetty_home = System.getProperty("jetty.home","../../jetty-distribution/target/distribution");
String jetty_base = System.getProperty("jetty.home","../../jetty-distribution/target/distribution/demo-base");
System.setProperty("jetty.home",jetty_home);
System.setProperty("jetty.base",jetty_base);
// Path to as-built jetty-distribution directory
String jettyHomeBuild = "../../jetty-distribution/target/distribution";
// Find jetty home and base directories
String homePath = System.getProperty("jetty.home", jettyHomeBuild);
File homeDir = new File(homePath);
if (!homeDir.exists())
{
throw new FileNotFoundException(homeDir.getAbsolutePath());
}
String basePath = System.getProperty("jetty.base", homeDir + "/demo-base");
File baseDir = new File(basePath);
if(!baseDir.exists())
{
throw new FileNotFoundException(baseDir.getAbsolutePath());
}
// Configure jetty.home and jetty.base system properties
String jetty_home = homeDir.getAbsolutePath();
String jetty_base = baseDir.getAbsolutePath();
System.setProperty("jetty.home", jetty_home);
System.setProperty("jetty.base", jetty_base);
// === jetty.xml ===
@ -88,14 +111,15 @@ public class LikeJettyXml
server.setDumpBeforeStop(false);
server.setStopAtShutdown(true);
// === jetty-jmx.xml ===
MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
MBeanContainer mbContainer = new MBeanContainer(
ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
// === jetty-http.xml ===
ServerConnector http = new ServerConnector(server,new HttpConnectionFactory(http_config));
ServerConnector http = new ServerConnector(server,
new HttpConnectionFactory(http_config));
http.setPort(8080);
http.setIdleTimeout(30000);
server.addConnector(http);
@ -109,10 +133,8 @@ public class LikeJettyXml
sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
sslContextFactory.setTrustStorePath(jetty_home + "/etc/keystore");
sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setExcludeCipherSuites(
"SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_DSS_WITH_DES_CBC_SHA",
sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA",
"SSL_RSA_EXPORT_WITH_RC4_40_MD5",
"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
@ -133,7 +155,9 @@ public class LikeJettyXml
// === jetty-deploy.xml ===
DeploymentManager deployer = new DeploymentManager();
deployer.setContexts(contexts);
deployer.setContextAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/servlet-api-[^/]*\\.jar$");
deployer.setContextAttribute(
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/servlet-api-[^/]*\\.jar$");
WebAppProvider webapp_provider = new WebAppProvider();
webapp_provider.setMonitoredDirName(jetty_base + "/webapps");
@ -146,9 +170,10 @@ public class LikeJettyXml
server.addBean(deployer);
// === setup jetty plus ==
Configuration.ClassList.setServerDefault(server)
.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration",
"org.eclipse.jetty.plus.webapp.EnvConfiguration","org.eclipse.jetty.plus.webapp.PlusConfiguration");
Configuration.ClassList.setServerDefault(server).addAfter(
"org.eclipse.jetty.webapp.FragmentConfiguration",
"org.eclipse.jetty.plus.webapp.EnvConfiguration",
"org.eclipse.jetty.plus.webapp.PlusConfiguration");
// === jetty-stats.xml ===
StatisticsHandler stats = new StatisticsHandler();
@ -188,6 +213,7 @@ public class LikeJettyXml
login.setRefreshInterval(0);
server.addBean(login);
// Start the server
server.start();
server.join();

View File

@ -1,23 +1,26 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.File;
import java.io.FileNotFoundException;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
@ -27,70 +30,89 @@ import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.util.ssl.SslContextFactory;
/* ------------------------------------------------------------ */
/**
* A Jetty server with multiple connectors.
*/
public class ManyConnectors
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
// Since this example shows off SSL configuration, we need a keystore with the appropriate key. These two
// lines are purely a hack to get access to a keystore that we use in many unit tests and should probably be
// a direct path to your own keystore (used on line 29).
String jetty_home = System.getProperty("jetty.home","../../jetty-distribution/target/distribution");
System.setProperty("jetty.home", jetty_home);
// Since this example shows off SSL configuration, we need a keystore
// with the appropriate key. These lookup of jetty.home is purely a hack
// to get access to a keystore that we use in many unit tests and should
// probably be a direct path to your own keystore.
// Create a basic jetty server object without declaring the port. Since we are configuring connectors
// directly we'll be setting ports on those connectors.
String jettyDistKeystore = "../../jetty-distribution/target/distribution/etc/keystore";
String keystorePath = System.getProperty(
"example.keystore", jettyDistKeystore);
File keystoreFile = new File(keystorePath);
if (!keystoreFile.exists())
{
throw new FileNotFoundException(keystoreFile.getAbsolutePath());
}
// Create a basic jetty server object without declaring the port. Since
// we are configuring connectors directly we'll be setting ports on
// those connectors.
Server server = new Server();
// HTTP Configuration
// HttpConfiguration is a collection of configuration information appropriate for http and https. The default
// scheme for http is <code>http</code> of course, as the default for secured http is <code>https</code> but
// we show setting the scheme to show it can be done. The port for secured communication is also set here.
// HttpConfiguration is a collection of configuration information
// appropriate for http and https. The default scheme for http is
// <code>http</code> of course, as the default for secured http is
// <code>https</code> but we show setting the scheme to show it can be
// done. The port for secured communication is also set here.
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setOutputBufferSize(32768);
// HTTP connector
// The first server connector we create is the one for http, passing in the http configuration we configured
// above so it can get things like the output buffer size, etc. We also set the port (8080) and configure an
// idle timeout.
ServerConnector http = new ServerConnector(server,new HttpConnectionFactory(http_config));
// The first server connector we create is the one for http, passing in
// the http configuration we configured above so it can get things like
// the output buffer size, etc. We also set the port (8080) and
// configure an idle timeout.
ServerConnector http = new ServerConnector(server,
new HttpConnectionFactory(http_config));
http.setPort(8080);
http.setIdleTimeout(30000);
// SSL Context Factory for HTTPS and SPDY
// SSL requires a certificate so we configure a factory for ssl contents with information pointing to what
// keystore the ssl connection needs to know about. Much more configuration is available the ssl context,
// including things like choosing the particular certificate out of a keystore to be used.
// SSL requires a certificate so we configure a factory for ssl contents
// with information pointing to what keystore the ssl connection needs
// to know about. Much more configuration is available the ssl context,
// including things like choosing the particular certificate out of a
// keystore to be used.
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore");
sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
// HTTPS Configuration
// A new HttpConfiguration object is needed for the next connector and you can pass the old one as an
// argument to effectively clone the contents. On this HttpConfiguration object we add a
// SecureRequestCustomizer which is how a new connector is able to resolve the https connection before
// handing control over to the Jetty Server.
// A new HttpConfiguration object is needed for the next connector and
// you can pass the old one as an argument to effectively clone the
// contents. On this HttpConfiguration object we add a
// SecureRequestCustomizer which is how a new connector is able to
// resolve the https connection before handing control over to the Jetty
// Server.
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
// HTTPS connector
// We create a second ServerConnector, passing in the http configuration we just made along with the
// previously created ssl context factory. Next we set the port and a longer idle timeout.
// We create a second ServerConnector, passing in the http configuration
// we just made along with the previously created ssl context factory.
// Next we set the port and a longer idle timeout.
ServerConnector https = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,"http/1.1"),
new HttpConnectionFactory(https_config));
new SslConnectionFactory(sslContextFactory, "http/1.1"),
new HttpConnectionFactory(https_config));
https.setPort(8443);
https.setIdleTimeout(500000);
// Here you see the server having multiple connectors registered with it, now requests can flow into the server
// from both http and https urls to their respective ports and be processed accordingly by jetty. A simple
// handler is also registered with the server so the example has something to pass requests off to.
// Here you see the server having multiple connectors registered with
// it, now requests can flow into the server from both http and https
// urls to their respective ports and be processed accordingly by jetty.
// A simple handler is also registered with the server so the example
// has something to pass requests off to.
// Set the connectors
server.setConnectors(new Connector[] { http, https });

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -25,7 +25,7 @@ import org.eclipse.jetty.server.handler.ContextHandlerCollection;
public class ManyContexts
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
@ -35,16 +35,17 @@ public class ManyContexts
ContextHandler contextFR = new ContextHandler("/fr");
contextFR.setHandler(new HelloHandler("Bonjoir"));
ContextHandler contextIT = new ContextHandler("/it");
contextIT.setHandler(new HelloHandler("Bongiorno"));
ContextHandler contextV = new ContextHandler("/");
contextV.setVirtualHosts(new String[]{ "127.0.0.2" });
contextV.setVirtualHosts(new String[] { "127.0.0.2" });
contextV.setHandler(new HelloHandler("Virtual Hello"));
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { context, contextFR, contextIT, contextV });
contexts.setHandlers(new Handler[] { context, contextFR, contextIT,
contextV });
server.setHandler(contexts);

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -38,7 +38,6 @@ import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.util.ajax.JSON;
/* ------------------------------------------------------------ */
/**
* Frequently many handlers are combined together to handle different aspects of
* a request. A handler may:
@ -49,7 +48,6 @@ import org.eclipse.jetty.util.ajax.JSON;
* <li>select another handler to pass the request to.
* <li>use business logic to decide to do one of the above.
* </ul>
*
* Multiple handlers may be combined with:
* <ul>
* <li>{@link HandlerWrapper} which will nest one handler inside another. In
@ -68,28 +66,60 @@ import org.eclipse.jetty.util.ajax.JSON;
*/
public class ManyHandlers
{
public static void main(String[] args) throws Exception
/**
* Produce output that lists all of the request parameters
*/
public static class ParamHandler extends AbstractHandler
{
public void handle( String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
ServletException
{
Map<String, String[]> params = request.getParameterMap();
if (params.size() > 0)
{
response.setContentType("text/plain");
response.getWriter().println(JSON.toString(params));
baseRequest.setHandled(true);
}
}
}
/**
* Add a request attribute, but produce no output.
*/
public static class WelcomeWrapHandler extends HandlerWrapper
{
@Override
public void handle( String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
ServletException
{
request.setAttribute("welcome", "Hello");
super.handle(target, baseRequest, request, response);
}
}
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
// create the handlers
Handler param = new ParamHandler();
HandlerWrapper wrapper = new HandlerWrapper()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException
{
request.setAttribute("welcome","Hello");
super.handle(target,baseRequest,request,response);
}
};
HandlerWrapper wrapper = new WelcomeWrapHandler();
Handler hello = new HelloHandler();
Handler dft = new DefaultHandler();
RequestLogHandler log = new RequestLogHandler();
RequestLogHandler requestLog = new RequestLogHandler();
// configure logs
log.setRequestLog(new NCSARequestLog(File.createTempFile("demo","log").getAbsolutePath()));
// configure request logging
File requestLogFile = File.createTempFile("demo", "log");
NCSARequestLog ncsaLog = new NCSARequestLog(
requestLogFile.getAbsolutePath());
requestLog.setRequestLog(ncsaLog);
// create the handler collections
HandlerCollection handlers = new HandlerCollection();
@ -97,28 +127,24 @@ public class ManyHandlers
// link them all together
wrapper.setHandler(hello);
list.setHandlers(new Handler[]
{ param, wrapper, dft });
handlers.setHandlers(new Handler[]
{ list, log });
list.setHandlers(new Handler[] { param, wrapper, dft });
handlers.setHandlers(new Handler[] { list, requestLog });
// Handler tree looks like the following
// <pre>
// Server
// + HandlerCollection
// . + HandlerList
// . | + param (ParamHandler)
// . | + wrapper (WelcomeWrapHandler)
// . | | \ hello (HelloHandler)
// . | \ dft (DefaultHandler)
// . \ requestLog (RequestLogHandler)
// </pre>
server.setHandler(handlers);
server.start();
server.join();
}
public static class ParamHandler extends AbstractHandler
{
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
Map<String,String[]> params = request.getParameterMap();
if (params.size() > 0)
{
response.setContentType("text/plain");
response.getWriter().println(JSON.toString(params));
((Request)request).setHandled(true);
}
}
}
}

View File

@ -1,24 +1,23 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.lang.management.ManagementFactory;
import org.eclipse.jetty.jmx.MBeanContainer;
@ -30,28 +29,35 @@ import org.eclipse.jetty.servlet.ServletHolder;
public class ManyServletContexts
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
// Setup JMX
MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer,true);
MBeanContainer mbContainer = new MBeanContainer(
ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer, true);
// Declare server handler collection
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
ServletContextHandler root = new ServletContextHandler(contexts,"/",ServletContextHandler.SESSIONS);
root.addServlet(new ServletHolder(new HelloServlet("Hello")),"/");
root.addServlet(new ServletHolder(new HelloServlet("Ciao")),"/it/*");
root.addServlet(new ServletHolder(new HelloServlet("Bonjoir")),"/fr/*");
// Configure context "/" (root) for servlets
ServletContextHandler root = new ServletContextHandler(contexts, "/",
ServletContextHandler.SESSIONS);
// Add servlets to root context
root.addServlet(new ServletHolder(new HelloServlet("Hello")), "/");
root.addServlet(new ServletHolder(new HelloServlet("Ciao")), "/it/*");
root.addServlet(new ServletHolder(new HelloServlet("Bonjoir")), "/fr/*");
// Configure context "/other" for servlets
ServletContextHandler other = new ServletContextHandler(contexts,
"/other", ServletContextHandler.SESSIONS);
// Add servlets to /other context
other.addServlet(DefaultServlet.class.getCanonicalName(), "/");
other.addServlet(new ServletHolder(new HelloServlet("YO!")), "*.yo");
ServletContextHandler other = new ServletContextHandler(contexts,"/other",ServletContextHandler.SESSIONS);
other.addServlet(DefaultServlet.class.getCanonicalName(),"/");
other.addServlet(new ServletHolder(new HelloServlet("YO!")),"*.yo");
server.start();
server.dumpStdErr();
server.join();
}
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -30,27 +30,35 @@ import org.eclipse.jetty.servlet.ServletHandler;
public class MinimalServlets
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) 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,
// 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);
// The ServletHandler is a dead simple way to create a context handler that is backed by an instance of a
// Servlet. This handler then needs to be registered with the Server object.
// The ServletHandler is a dead simple way to create a context handler
// that is backed by an instance of a Servlet.
// This handler then needs to be registered with the Server object.
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
// Passing in the class for the servlet allows jetty to instantite an instance of that servlet and mount it
// on a given context path.
// Passing in the class for the Servlet allows jetty to instantiate an
// instance of that Servlet and mount it on a given context path.
// !! This is a raw Servlet, not a servlet that has been configured through a web.xml or anything like that !!
// IMPORTANT:
// This is a raw Servlet, not a Servlet that has been configured
// through a web.xml @WebServlet annotation, or anything similar.
handler.addServletWithMapping(HelloServlet.class, "/*");
// 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.
// Start things up!
server.start();
// The use of server.join() the will make the current thread join and
// wait until the server is done executing.
// See
// http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
server.join();
}
@ -58,11 +66,13 @@ public class MinimalServlets
public static class HelloServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>Hello SimpleServlet</h1>");
response.getWriter().println("<h1>Hello from HelloServlet</h1>");
}
}
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -21,13 +21,12 @@ package org.eclipse.jetty.embedded;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
/* ------------------------------------------------------------ */
/**
* A Jetty server with one connectors.
*/
public class OneConnector
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
// The Server
Server server = new Server();
@ -37,7 +36,7 @@ public class OneConnector
http.setHost("localhost");
http.setPort(8080);
http.setIdleTimeout(30000);
// Set the connector
server.addConnector(http);

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -23,18 +23,20 @@ import org.eclipse.jetty.server.handler.ContextHandler;
public class OneContext
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
Server server = new Server( 8080 );
// Add a single handler on context "/hello"
ContextHandler context = new ContextHandler();
context.setContextPath("/");
context.setResourceBase(".");
context.setClassLoader(Thread.currentThread().getContextClassLoader());
context.setHandler(new HelloHandler());
context.setContextPath( "/hello" );
context.setHandler( new HelloHandler() );
server.setHandler(context);
// Can be accessed using http://localhost:8080/hello
server.setHandler( context );
// Start the server
server.start();
server.join();
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -22,7 +22,7 @@ import org.eclipse.jetty.server.Server;
public class OneHandler
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
server.setHandler(new HelloHandler());

View File

@ -1,40 +1,44 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class OneServletContext
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setResourceBase(System.getProperty("java.io.tmpdir"));
server.setHandler(context);
context.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class,"/");
context.addServlet(new ServletHolder(new DumpServlet()),"/dump/*");
// Add dump servlet
context.addServlet(DumpServlet.class, "/dump/*");
// Add default servlet
context.addServlet(DefaultServlet.class, "/");
server.start();
server.join();
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -23,25 +23,29 @@ import java.lang.management.ManagementFactory;
import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.server.ConnectorStatistics;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class OneServletContextJmxStats
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
server.addBean(new MBeanContainer(ManagementFactory.getPlatformMBeanServer()));
Server server = new Server(8080);
// Add JMX tracking to Server
server.addBean(new MBeanContainer(ManagementFactory
.getPlatformMBeanServer()));
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
context.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class,"/");
context.addServlet(new ServletHolder(new DumpServlet()),"/dump/*");
context.addServlet(DumpServlet.class, "/dump/*");
context.addServlet(DefaultServlet.class, "/");
// Add Connector Statistics tracking to all connectors
ConnectorStatistics.addToAllConnectors(server);
server.start();
server.join();
}

View File

@ -1,23 +1,24 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.File;
import java.lang.management.ManagementFactory;
import org.eclipse.jetty.jmx.MBeanContainer;
@ -27,43 +28,55 @@ import org.eclipse.jetty.webapp.WebAppContext;
public class OneWebApp
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) 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,
// 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);
// Setup JMX
MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
MBeanContainer mbContainer = new MBeanContainer(
ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
// The WebAppContext is the entity that controls the environment in which a web application lives and
// breathes. In this example the context path is being set to "/" so it is suitable for serving root context
// requests and then we see it setting the location of the war. A whole host of other configurations are
// available, ranging from configuring to support annotation scanning in the webapp (through
// The WebAppContext is the entity that controls the environment in
// which a web application lives and breathes. In this example the
// context path is being set to "/" so it is suitable for serving root
// context requests and then we see it setting the location of the war.
// A whole host of other configurations are available, ranging from
// configuring to support annotation scanning in the webapp (through
// PlusConfiguration) to choosing where the webapp will unpack itself.
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("../../jetty-distribution/target/distribution/demo-base/webapps/test.war");
File warFile = new File(
"../../jetty-distribution/target/distribution/demo-base/webapps/test.war");
webapp.setWar(warFile.getAbsolutePath());
// A WebAppContext is a ContextHandler as well so it needs to be set to the server so it is aware of where to
// send the appropriate requests.
// A WebAppContext is a ContextHandler as well so it needs to be set to
// the server so it is aware of where to send the appropriate requests.
server.setHandler(webapp);
// Configure a LoginService
// Since this example is for our test webapp, we need to setup a LoginService so this shows how to create a
// very simple hashmap based one. The name of the LoginService needs to correspond to what is configured in
// the webapp's web.xml and since it has a lifecycle of its own we register it as a bean with the Jetty
// server object so it can be started and stopped according to the lifecycle of the server itself.
// Since this example is for our test webapp, we need to setup a
// LoginService so this shows how to create a very simple hashmap based
// one. The name of the LoginService needs to correspond to what is
// configured in the webapp's web.xml and since it has a lifecycle of
// its own we register it as a bean with the Jetty server object so it
// can be started and stopped according to the lifecycle of the server
// itself.
HashLoginService loginService = new HashLoginService();
loginService.setName("Test Realm");
loginService.setConfig("src/test/resources/realm.properties");
server.addBean(loginService);
// 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.
// Start things up!
server.start();
// The use of server.join() the will make the current thread join and
// wait until the server is done executing.
// See http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
server.join();
}
}

View File

@ -1,80 +1,109 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.File;
import java.lang.management.ManagementFactory;
import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
public class OneWebAppWithJsp
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) 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,
// 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);
// Setup JMX
MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
Server server = new Server( 8080 );
// The WebAppContext is the entity that controls the environment in which a web application lives and
// breathes. In this example the context path is being set to "/" so it is suitable for serving root context
// requests and then we see it setting the location of the war. A whole host of other configurations are
// available, ranging from configuring to support annotation scanning in the webapp (through
// Setup JMX
MBeanContainer mbContainer = new MBeanContainer(
ManagementFactory.getPlatformMBeanServer() );
server.addBean( mbContainer );
// The WebAppContext is the entity that controls the environment in
// which a web application lives and
// breathes. In this example the context path is being set to "/" so it
// is suitable for serving root context
// requests and then we see it setting the location of the war. A whole
// host of other configurations are
// available, ranging from configuring to support annotation scanning in
// the webapp (through
// PlusConfiguration) to choosing where the webapp will unpack itself.
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("../../jetty-distribution/target/distribution/demo-base/webapps/test.war");
// This webapp will use jsps and jstl. We need to enable the AnnotationConfiguration in order to correctly
webapp.setContextPath( "/" );
File warFile = new File(
"../../jetty-distribution/target/distribution/demo-base/webapps/test.war" );
if (!warFile.exists())
{
throw new RuntimeException( "Unable to find WAR File: "
+ warFile.getAbsolutePath() );
}
webapp.setWar( warFile.getAbsolutePath() );
// This webapp will use jsps and jstl. We need to enable the
// AnnotationConfiguration in order to correctly
// set up the jsp container
org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
// Set the ContainerIncludeJarPattern so that jetty examines these container-path jars for tlds, web-fragments etc.
// If you omit the jar that contains the jstl .tlds, the jsp engine will scan for them instead.
webapp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$");
Configuration.ClassList classlist = Configuration.ClassList
.setServerDefault( server );
classlist.addBefore(
"org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
"org.eclipse.jetty.annotations.AnnotationConfiguration" );
// A WebAppContext is a ContextHandler as well so it needs to be set to the server so it is aware of where to
// Set the ContainerIncludeJarPattern so that jetty examines these
// container-path jars for tlds, web-fragments etc.
// If you omit the jar that contains the jstl .tlds, the jsp engine will
// scan for them instead.
webapp.setAttribute(
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
// A WebAppContext is a ContextHandler as well so it needs to be set to
// the server so it is aware of where to
// send the appropriate requests.
server.setHandler(webapp);
server.setHandler( webapp );
// Configure a LoginService
// Since this example is for our test webapp, we need to setup a LoginService so this shows how to create a
// very simple hashmap based one. The name of the LoginService needs to correspond to what is configured in
// the webapp's web.xml and since it has a lifecycle of its own we register it as a bean with the Jetty
// server object so it can be started and stopped according to the lifecycle of the server itself.
// Configure a LoginService.
// Since this example is for our test webapp, we need to setup a
// LoginService so this shows how to create a very simple hashmap based
// one. The name of the LoginService needs to correspond to what is
// configured in the webapp's web.xml and since it has a lifecycle of
// its own we register it as a bean with the Jetty server object so it
// can be started and stopped according to the lifecycle of the server
// itself.
HashLoginService loginService = new HashLoginService();
loginService.setName("Test Realm");
loginService.setConfig("src/test/resources/realm.properties");
server.addBean(loginService);
loginService.setName( "Test Realm" );
loginService.setConfig( "src/test/resources/realm.properties" );
server.addBean( loginService );
// 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.
// Start things up!
server.start();
// The use of server.join() the will make the current thread join and
// wait until the server is done executing.
// See http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
server.join();
}
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -27,7 +27,7 @@ import org.eclipse.jetty.servlet.ServletHolder;
public class ProxyServer
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
@ -39,7 +39,8 @@ public class ProxyServer
server.setHandler(proxy);
// Setup proxy servlet
ServletContextHandler context = new ServletContextHandler(proxy, "/", ServletContextHandler.SESSIONS);
ServletContextHandler context = new ServletContextHandler(proxy, "/",
ServletContextHandler.SESSIONS);
ServletHolder proxyServlet = new ServletHolder(ProxyServlet.class);
proxyServlet.setInitParameter("blackList", "www.eclipse.org");
context.addServlet(proxyServlet, "/*");

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -30,59 +30,75 @@ import org.eclipse.jetty.util.security.Constraint;
public class SecuredHelloHandler
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) 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,
// 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);
// Since this example is for our test webapp, we need to setup a LoginService so this shows how to create a
// very simple hashmap based one. The name of the LoginService needs to correspond to what is configured a
// webapp's web.xml and since it has a lifecycle of its own we register it as a bean with the Jetty server
// object so it can be started and stopped according to the lifecycle of the server itself. In this example
// the name can be whatever you like since we are not dealing with webapp realms.
LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService);
// Since this example is for our test webapp, we need to setup a
// LoginService so this shows how to create a very simple hashmap based
// one. The name of the LoginService needs to correspond to what is
// configured a webapp's web.xml and since it has a lifecycle of its own
// we register it as a bean with the Jetty server object so it can be
// started and stopped according to the lifecycle of the server itself.
// In this example the name can be whatever you like since we are not
// dealing with webapp realms.
LoginService loginService = new HashLoginService("MyRealm",
"src/test/resources/realm.properties");
server.addBean(loginService);
// A security handler is a jetty handler that secures content behind a particular portion of a url space. The
// ConstraintSecurityHandler is a more specialized handler that allows matching of urls to different
// A security handler is a jetty handler that secures content behind a
// particular portion of a url space. The ConstraintSecurityHandler is a
// more specialized handler that allows matching of urls to different
// constraints. The server sets this as the first handler in the chain,
// effectively applying these constraints to all subsequent handlers in the chain.
// effectively applying these constraints to all subsequent handlers in
// the chain.
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
// This constraint requires authentication and in addition that an authenticated user be a member of a given
// set of roles for authorization purposes.
// This constraint requires authentication and in addition that an
// authenticated user be a member of a given set of roles for
// authorization purposes.
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate( true );
constraint.setRoles(new String[]{"user", "admin"});
constraint.setAuthenticate(true);
constraint.setRoles(new String[] { "user", "admin" });
// Binds a url pattern with the previously created constraint. The roles for this constraing mapping are
// mined from the Constraint itself although methods exist to declare and bind roles separately as well.
// Binds a url pattern with the previously created constraint. The roles
// for this constraing mapping are mined from the Constraint itself
// although methods exist to declare and bind roles separately as well.
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );
mapping.setPathSpec("/*");
mapping.setConstraint(constraint);
// First you see the constraint mapping being applied to the handler as a singleton list,
// however you can passing in as many security constraint mappings as you like so long as they follow the
// mapping requirements of the servlet api. Next we set a BasicAuthenticator instance which is the object
// that actually checks the credentials followed by the LoginService which is the store of known users, etc.
// First you see the constraint mapping being applied to the handler as
// a singleton list, however you can passing in as many security
// constraint mappings as you like so long as they follow the mapping
// requirements of the servlet api. Next we set a BasicAuthenticator
// instance which is the object that actually checks the credentials
// followed by the LoginService which is the store of known users, etc.
security.setConstraintMappings(Collections.singletonList(mapping));
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
// The Hello Handler is the handler we are securing so we create one, and then set it as the handler on the
// The Hello Handler is the handler we are securing so we create one,
// and then set it as the handler on the
// security handler to complain the simple handler chain.
HelloHandler hh = new HelloHandler();
// chain the hello handler into the security handler
security.setHandler(hh);
// 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.
// Start things up!
server.start();
// The use of server.join() the will make the current thread join and
// wait until the server is done executing.
// See
// http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
server.join();
}
}

View File

@ -1,70 +1,80 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.File;
import org.eclipse.jetty.plus.jndi.EnvEntry;
import org.eclipse.jetty.plus.jndi.Resource;
import org.eclipse.jetty.plus.jndi.Transaction;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
/**
* ServerWithAnnotations
*
*
*/
public class ServerWithAnnotations
{
public static final void main(String args[]) throws Exception
public static final void main( String args[] ) throws Exception
{
//Create the server
// Create the server
Server server = new Server(8080);
//Enable parsing of jndi-related parts of web.xml and jetty-env.xml
org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
//Create a WebApp
// Enable parsing of jndi-related parts of web.xml and jetty-env.xml
Configuration.ClassList classlist = Configuration.ClassList
.setServerDefault(server);
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration",
"org.eclipse.jetty.plus.webapp.EnvConfiguration",
"org.eclipse.jetty.plus.webapp.PlusConfiguration");
classlist.addBefore(
"org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
"org.eclipse.jetty.annotations.AnnotationConfiguration");
// Create a WebApp
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("../../jetty-distribution/target/distribution/demo-base/webapps/test-spec.war");
webapp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/javax.servlet-[^/]*\\.jar$|.*/servlet-api-[^/]*\\.jar$");
File warFile = new File(
"../../jetty-distribution/target/distribution/demo-base/webapps/test.war");
webapp.setWar(warFile.getAbsolutePath());
webapp.setAttribute(
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/javax.servlet-[^/]*\\.jar$|.*/servlet-api-[^/]*\\.jar$");
server.setHandler(webapp);
//Register new transaction manager in JNDI
//At runtime, the webapp accesses this as java:comp/UserTransaction
org.eclipse.jetty.plus.jndi.Transaction transactionMgr = new org.eclipse.jetty.plus.jndi.Transaction(new com.acme.MockUserTransaction());
// Register new transaction manager in JNDI
// At runtime, the webapp accesses this as java:comp/UserTransaction
new Transaction(new com.acme.MockUserTransaction());
// Define an env entry with webapp scope.
new EnvEntry(webapp, "maxAmount", new Double(100), true);
// Register a mock DataSource scoped to the webapp
new Resource(webapp, "jdbc/mydatasource", new com.acme.MockDataSource());
//Define an env entry with webapp scope.
org.eclipse.jetty.plus.jndi.EnvEntry maxAmount = new org.eclipse.jetty.plus.jndi.EnvEntry (webapp, "maxAmount", new Double(100), true);
// Register a mock DataSource scoped to the webapp
org.eclipse.jetty.plus.jndi.Resource mydatasource = new org.eclipse.jetty.plus.jndi.Resource(webapp, "jdbc/mydatasource", new com.acme.MockDataSource());
// Configure a LoginService
HashLoginService loginService = new HashLoginService();
loginService.setName("Test Realm");
loginService.setConfig("src/test/resources/realm.properties");
server.addBean(loginService);
server.start();
server.join();
}

View File

@ -1,111 +1,115 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.File;
import java.util.Properties;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
/**
* ServerWithJNDI
*
*
*/
public class ServerWithJNDI
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
//Create the server
// Create the server
Server server = new Server(8080);
//Enable parsing of jndi-related parts of web.xml and jetty-env.xml
org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
//Create a WebApp
// Enable parsing of jndi-related parts of web.xml and jetty-env.xml
Configuration.ClassList classlist = Configuration.ClassList
.setServerDefault(server);
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration",
"org.eclipse.jetty.plus.webapp.EnvConfiguration",
"org.eclipse.jetty.plus.webapp.PlusConfiguration");
// Create a WebApp
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("../../jetty-distribution/target/distribution/demo-base/webapps/test-jndi.war");
File warFile = new File(
"../../jetty-distribution/target/distribution/demo-base/webapps/test.war");
webapp.setWar(warFile.getAbsolutePath());
server.setHandler(webapp);
//Register new transaction manager in JNDI
//At runtime, the webapp accesses this as java:comp/UserTransaction
org.eclipse.jetty.plus.jndi.Transaction transactionMgr = new org.eclipse.jetty.plus.jndi.Transaction(new com.acme.MockUserTransaction());
// Register new transaction manager in JNDI
// At runtime, the webapp accesses this as java:comp/UserTransaction
new org.eclipse.jetty.plus.jndi.Transaction(
new com.acme.MockUserTransaction());
//Define an env entry with Server scope.
//At runtime, the webapp accesses this as java:comp/env/woggle
//This is equivalent to putting an env-entry in web.xml:
//<env-entry>
// <env-entry-name>woggle</env-entry-name>
// <env-entry-type>java.lang.Integer</env-entry-type>
// <env-entry-value>4000</env-entry-value>
//</env-entry>
org.eclipse.jetty.plus.jndi.EnvEntry woggle = new org.eclipse.jetty.plus.jndi.EnvEntry(server, "woggle", new Integer(4000), false);
// Define an env entry with Server scope.
// At runtime, the webapp accesses this as java:comp/env/woggle
// This is equivalent to putting an env-entry in web.xml:
// <env-entry>
// <env-entry-name>woggle</env-entry-name>
// <env-entry-type>java.lang.Integer</env-entry-type>
// <env-entry-value>4000</env-entry-value>
// </env-entry>
new org.eclipse.jetty.plus.jndi.EnvEntry(server, "woggle", new Integer(4000), false);
// Define an env entry with webapp scope.
// At runtime, the webapp accesses this as java:comp/env/wiggle
// This is equivalent to putting a web.xml entry in web.xml:
// <env-entry>
// <env-entry-name>wiggle</env-entry-name>
// <env-entry-value>100</env-entry-value>
// <env-entry-type>java.lang.Double</env-entry-type>
// </env-entry>
// Note that the last arg of "true" means that this definition for
// "wiggle" would override an entry of the
// same name in web.xml
new org.eclipse.jetty.plus.jndi.EnvEntry(webapp, "wiggle", new Double(100), true);
//Define an env entry with webapp scope.
//At runtime, the webapp accesses this as java:comp/env/wiggle
//This is equivalent to putting a web.xml entry in web.xml:
//<env-entry>
// <env-entry-name>wiggle</env-entry-name>
// <env-entry-value>100</env-entry-value>
// <env-entry-type>java.lang.Double</env-entry-type>
//</env-entry>
//Note that the last arg of "true" means that this definition for "wiggle" would override an entry of the
//same name in web.xml
org.eclipse.jetty.plus.jndi.EnvEntry wiggle = new org.eclipse.jetty.plus.jndi.EnvEntry(webapp, "wiggle", new Double(100), true);
//Register a reference to a mail service scoped to the webapp.
//This must be linked to the webapp by an entry in web.xml:
// Register a reference to a mail service scoped to the webapp.
// This must be linked to the webapp by an entry in web.xml:
// <resource-ref>
// <res-ref-name>mail/Session</res-ref-name>
// <res-type>javax.mail.Session</res-type>
// <res-auth>Container</res-auth>
// <res-ref-name>mail/Session</res-ref-name>
// <res-type>javax.mail.Session</res-type>
// <res-auth>Container</res-auth>
// </resource-ref>
//At runtime the webapp accesses this as java:comp/env/mail/Session
// At runtime the webapp accesses this as java:comp/env/mail/Session
org.eclipse.jetty.jndi.factories.MailSessionReference mailref = new org.eclipse.jetty.jndi.factories.MailSessionReference();
mailref.setUser("CHANGE-ME");
mailref.setPassword("CHANGE-ME");
Properties props = new Properties();
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.host","CHANGE-ME");
props.put("mail.from","CHANGE-ME");
props.put("mail.smtp.host", "CHANGE-ME");
props.put("mail.from", "CHANGE-ME");
props.put("mail.debug", "false");
mailref.setProperties(props);
org.eclipse.jetty.plus.jndi.Resource xxxmail = new org.eclipse.jetty.plus.jndi.Resource(webapp, "mail/Session", mailref);
new org.eclipse.jetty.plus.jndi.Resource(webapp, "mail/Session", mailref);
// Register a mock DataSource scoped to the webapp
// This must be linked to the webapp via an entry in web.xml:
// <resource-ref>
// <res-ref-name>jdbc/mydatasource</res-ref-name>
// <res-type>javax.sql.DataSource</res-type>
// <res-auth>Container</res-auth>
// </resource-ref>
// At runtime the webapp accesses this as
// java:comp/env/jdbc/mydatasource
new org.eclipse.jetty.plus.jndi.Resource(
webapp, "jdbc/mydatasource", new com.acme.MockDataSource());
// Register a mock DataSource scoped to the webapp
//This must be linked to the webapp via an entry in web.xml:
//<resource-ref>
// <res-ref-name>jdbc/mydatasource</res-ref-name>
// <res-type>javax.sql.DataSource</res-type>
// <res-auth>Container</res-auth>
//</resource-ref>
//At runtime the webapp accesses this as java:comp/env/jdbc/mydatasource
org.eclipse.jetty.plus.jndi.Resource mydatasource = new org.eclipse.jetty.plus.jndi.Resource(webapp, "jdbc/mydatasource",
new com.acme.MockDataSource());
server.start();
server.join();
}

View File

@ -1,31 +1,31 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import org.eclipse.jetty.server.Server;
/* ------------------------------------------------------------ */
/** The simplest possible Jetty server.
/**
* The simplest possible Jetty server.
*/
public class SimplestServer
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
server.start();

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.embedded;
import java.io.File;
import java.io.FileNotFoundException;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
@ -30,7 +33,6 @@ import org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnectionFactory;
import org.eclipse.jetty.spdy.server.http.ReferrerPushStrategy;
import org.eclipse.jetty.util.ssl.SslContextFactory;
/* ------------------------------------------------------------ */
/**
* A Jetty server with HTTP and SPDY connectors.
*/
@ -38,7 +40,17 @@ public class SpdyConnector
{
public static void main(String[] args) throws Exception
{
String jetty_home = System.getProperty("jetty.home","../../jetty-distribution/target/distribution");
// Path to as-built jetty-distribution directory
String jettyHomeBuild = "../../jetty-distribution/target/distribution";
// Find jetty home directories
String homePath = System.getProperty("jetty.home", jettyHomeBuild);
File homeDir = new File(homePath);
if (!homeDir.exists())
{
throw new FileNotFoundException(homeDir.getAbsolutePath());
}
String jetty_home = homeDir.getAbsolutePath();
System.setProperty("jetty.home", jetty_home);
// The Server
@ -50,7 +62,8 @@ public class SpdyConnector
http_config.setSecurePort(8443);
// HTTP connector
ServerConnector http = new ServerConnector(server,new HttpConnectionFactory(http_config));
ServerConnector http = new ServerConnector(server,
new HttpConnectionFactory(http_config));
http.setPort(8080);
server.addConnector(http);
@ -66,23 +79,28 @@ public class SpdyConnector
// SPDY versions
HTTPSPDYServerConnectionFactory spdy2 =
new HTTPSPDYServerConnectionFactory(2,https_config);
new HTTPSPDYServerConnectionFactory(2, https_config);
HTTPSPDYServerConnectionFactory spdy3 =
new HTTPSPDYServerConnectionFactory(3,https_config,new ReferrerPushStrategy());
new HTTPSPDYServerConnectionFactory(3, https_config,
new ReferrerPushStrategy());
// NPN Factory
SPDYServerConnectionFactory.checkProtocolNegotiationAvailable();
NPNServerConnectionFactory npn =
new NPNServerConnectionFactory(spdy3.getProtocol(),spdy2.getProtocol(),http.getDefaultProtocol());
NPNServerConnectionFactory npn = new NPNServerConnectionFactory(
spdy3.getProtocol(),
spdy2.getProtocol(),
http.getDefaultProtocol());
npn.setDefaultProtocol(http.getDefaultProtocol());
// SSL Factory
SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,npn.getProtocol());
SslConnectionFactory ssl = new SslConnectionFactory(
sslContextFactory, npn.getProtocol());
// SPDY Connector
ServerConnector spdyConnector =
new ServerConnector(server,ssl,npn,spdy3,spdy2,new HttpConnectionFactory(https_config));
ServerConnector spdyConnector = new ServerConnector(server, ssl,
npn, spdy3, spdy2,
new HttpConnectionFactory(https_config));
spdyConnector.setPort(8443);
server.addConnector(spdyConnector);

View File

@ -1,23 +1,25 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.management.ManagementFactory;
import org.eclipse.jetty.deploy.DeploymentManager;
@ -49,10 +51,20 @@ import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class SpdyServer
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
String jetty_home = System.getProperty("jetty.home","../../jetty-distribution/target/distribution");
System.setProperty("jetty.home",jetty_home);
// Path to as-built jetty-distribution directory
String jettyHomeBuild = "../../jetty-distribution/target/distribution";
// Find jetty home directories
String homePath = System.getProperty("jetty.home", jettyHomeBuild);
File homeDir = new File(homePath);
if (!homeDir.exists())
{
throw new FileNotFoundException(homeDir.getAbsolutePath());
}
String jetty_home = homeDir.getAbsolutePath();
System.setProperty("jetty.home", jetty_home);
// Setup Threadpool
QueuedThreadPool threadPool = new QueuedThreadPool(512);
@ -64,10 +76,10 @@ public class SpdyServer
server.setDumpBeforeStop(false);
// Setup JMX
MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
MBeanContainer mbContainer = new MBeanContainer(
ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
// Common HTTP configuration
HttpConfiguration config = new HttpConfiguration();
config.setSecurePort(8443);
@ -75,21 +87,23 @@ public class SpdyServer
config.addCustomizer(new SecureRequestCustomizer());
config.setSendServerVersion(true);
// Http Connector Setup
// A plain HTTP connector listening on port 8080. Note that it's also possible to have port 8080 configured as
// a non SSL SPDY connector. But the specification and most browsers do not allow to use SPDY without SSL
// encryption. However some browsers allow it to be configured.
// A plain HTTP connector listening on port 8080. Note that it's also
// possible to have port 8080 configured as a non SSL SPDY connector.
// But the specification and most browsers do not allow to use SPDY
// without SSL encryption. However some browsers allow it to be
// configured.
HttpConnectionFactory http = new HttpConnectionFactory(config);
ServerConnector httpConnector = new ServerConnector(server,http);
ServerConnector httpConnector = new ServerConnector(server, http);
httpConnector.setPort(8080);
httpConnector.setIdleTimeout(10000);
server.addConnector(httpConnector);
// SSL configurations
// We need a SSLContextFactory for the SSL encryption. That SSLContextFactory will be used by the SPDY
// We need a SSLContextFactory for the SSL encryption. That
// SSLContextFactory will be used by the SPDY
// connector.
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore");
@ -99,53 +113,64 @@ public class SpdyServer
sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setExcludeCipherSuites(
"SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_DSS_WITH_DES_CBC_SHA",
"SSL_RSA_EXPORT_WITH_RC4_40_MD5",
"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
// Spdy Connector
// Make sure that the required NPN implementations are available.
SPDYServerConnectionFactory.checkProtocolNegotiationAvailable();
// A ReferrerPushStrategy is being initialized.
// See: http://www.eclipse.org/jetty/documentation/current/spdy-configuring-push.html for more details.
// See:
// http://www.eclipse.org/jetty/documentation/current/spdy-configuring-push.html
// for more details.
PushStrategy push = new ReferrerPushStrategy();
HTTPSPDYServerConnectionFactory spdy2 = new HTTPSPDYServerConnectionFactory(2,config,push);
HTTPSPDYServerConnectionFactory spdy2 =
new HTTPSPDYServerConnectionFactory(2, config, push);
spdy2.setInputBufferSize(8192);
spdy2.setInitialWindowSize(32768);
// We need a connection factory per protocol that our server is supposed to support on the NPN port. We then
// create a ServerConnector and pass in the supported factories. NPN will then be used to negotiate the
// We need a connection factory per protocol that our server is supposed
// to support on the NPN port. We then
// create a ServerConnector and pass in the supported factories. NPN
// will then be used to negotiate the
// protocol with the client.
HTTPSPDYServerConnectionFactory spdy3 = new HTTPSPDYServerConnectionFactory(3,config,push);
HTTPSPDYServerConnectionFactory spdy3 =
new HTTPSPDYServerConnectionFactory(3, config, push);
spdy3.setInputBufferSize(8192);
NPNServerConnectionFactory npn = new NPNServerConnectionFactory(spdy3.getProtocol(),spdy2.getProtocol(),http.getProtocol());
NPNServerConnectionFactory npn = new NPNServerConnectionFactory(
spdy3.getProtocol(), spdy2.getProtocol(), http.getProtocol());
npn.setDefaultProtocol(http.getProtocol());
npn.setInputBufferSize(1024);
SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,npn.getProtocol());
SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,
npn.getProtocol());
// Setup the npn connector on port 8443
ServerConnector spdyConnector = new ServerConnector(server,ssl,npn,spdy3,spdy2,http);
ServerConnector spdyConnector = new ServerConnector(server, ssl,
npn, spdy3, spdy2, http);
spdyConnector.setPort(8443);
server.addConnector(spdyConnector);
// The following section adds some handlers, deployers and webapp providers.
// See: http://www.eclipse.org/jetty/documentation/current/advanced-embedding.html for details.
// The following section adds some handlers, deployers and webapp
// providers. See
// http://www.eclipse.org/jetty/documentation/current/advanced-embedding.html
// for details.
// Setup handlers
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
RequestLogHandler requestLogHandler = new RequestLogHandler();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler });
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(),
requestLogHandler });
StatisticsHandler stats = new StatisticsHandler();
stats.setHandler(handlers);
@ -162,7 +187,8 @@ public class SpdyServer
webapp_provider.setParentLoaderPriority(false);
webapp_provider.setExtractWars(true);
webapp_provider.setScanInterval(2);
webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml");
webapp_provider.setDefaultsDescriptor(jetty_home
+ "/etc/webdefault.xml");
deployer.addAppProvider(webapp_provider);
HashLoginService login = new HashLoginService();

View File

@ -1,23 +1,25 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.File;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
@ -28,56 +30,64 @@ import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.resource.Resource;
/* ------------------------------------------------------------ */
/**
* A {@link ContextHandlerCollection} handler may be used to direct a request to
* a specific Context. The URI path prefix and optional virtual host is used to
* select the context.
*
*/
public class SplitFileServer
{
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
// Create the Server object and a corresponding ServerConnector and then set the port for the connector. In
// this example the server will listen on port 8090. If you set this to port 0 then when the server has been
// started you can called connector.getLocalPort() to programmatically get the port the server started on.
// Create the Server object and a corresponding ServerConnector and then
// set the port for the connector. In this example the server will
// listen on port 8090. If you set this to port 0 then when the server
// has been started you can called connector.getLocalPort() to
// programmatically get the port the server started on.
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8090);
server.setConnectors(new Connector[]
{ connector });
server.setConnectors(new Connector[] { connector });
// Create a Context Handler and ResourceHandler. The ContextHandler is getting set to "/" path but this could
// be anything you like for builing out your url. Note how we are setting the ResourceBase using our jetty
// maven testing utilities to get the proper resource directory, you needn't use these,
// you simply need to supply the paths you are looking to serve content from.
// Create a Context Handler and ResourceHandler. The ContextHandler is
// getting set to "/" path but this could be anything you like for
// builing out your url. Note how we are setting the ResourceBase using
// our jetty maven testing utilities to get the proper resource
// directory, you needn't use these, you simply need to supply the paths
// you are looking to serve content from.
ContextHandler context0 = new ContextHandler();
context0.setContextPath("/");
ResourceHandler rh0 = new ResourceHandler();
rh0.setBaseResource( Resource.newResource(MavenTestingUtils.getTestResourceDir("dir0")));
File dir0 = MavenTestingUtils.getTestResourceDir("dir0");
rh0.setBaseResource(Resource.newResource(dir0));
context0.setHandler(rh0);
// Rinse and repeat the previous item, only specifying a different resource base.
// Rinse and repeat the previous item, only specifying a different
// resource base.
ContextHandler context1 = new ContextHandler();
context1.setContextPath("/");
context1.setContextPath("/");
ResourceHandler rh1 = new ResourceHandler();
rh1.setBaseResource( Resource.newResource(MavenTestingUtils.getTestResourceDir("dir1")));
File dir1 = MavenTestingUtils.getTestResourceDir("dir1");
rh1.setBaseResource(Resource.newResource(dir1));
context1.setHandler(rh1);
// Create a ContextHandlerCollection and set the context handlers to it. This will let jetty process urls
// against the declared contexts in order to match up content.
// Create a ContextHandlerCollection and set the context handlers to it.
// This will let jetty process urls against the declared contexts in
// order to match up content.
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[]
{ context0, context1 });
contexts.setHandlers(new Handler[] { context0, context1 });
server.setHandler(contexts);
// 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.
// Start things up!
server.start();
System.err.println(server.dump());
// Dump the server state
System.out.println(server.dump());
// The use of server.join() the will make the current thread join and
// wait until the server is done executing.
// See http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
server.join();
}
}

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -39,22 +39,24 @@ public class WebSocketJsrServer
public static class EchoJsrSocket
{
@OnMessage
public void onMessage(Session session, String message)
public void onMessage( Session session, String message )
{
session.getAsyncRemote().sendText(message);
}
}
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
// Enable javax.websocket configuration for the context
ServerContainer wsContainer = WebSocketServerContainerInitializer.configureContext(context);
ServerContainer wsContainer = WebSocketServerContainerInitializer
.configureContext(context);
// Add your websockets to the container
wsContainer.addEndpoint(EchoJsrSocket.class);

View File

@ -1,19 +1,19 @@
//
// ========================================================================
// Copyright (c) 1995-2014 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.
// ========================================================================
// Copyright (c) 1995-2014 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 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
// 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.
// ========================================================================
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.embedded;
@ -41,7 +41,7 @@ public class WebSocketServer
public static class EchoSocket
{
@OnWebSocketMessage
public void onMessage(Session session, String message)
public void onMessage( Session session, String message )
{
session.getRemote().sendStringByFuture(message);
}
@ -54,23 +54,24 @@ public class WebSocketServer
public static class EchoServlet extends WebSocketServlet
{
@Override
public void configure(WebSocketServletFactory factory)
public void configure( WebSocketServletFactory factory )
{
// Register the echo websocket with the basic WebSocketCreator
factory.register(EchoSocket.class);
}
}
public static void main(String[] args) throws Exception
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
// Add the echo socket servlet to the /echo path map
context.addServlet(new ServletHolder(EchoServlet.class),"/echo");
context.addServlet(new ServletHolder(EchoServlet.class), "/echo");
server.start();
context.dumpStdErr();