From 0bad6b5d1741289a47dfe3f086da29ac3be62f4b Mon Sep 17 00:00:00 2001 From: Jesse McConnell Date: Thu, 18 Oct 2012 09:21:42 -0500 Subject: [PATCH] just fix a messed up git mv --- examples/async-rest/async-rest-jar/pom.xml | 29 +++ .../asyncrest/AbstractRestServlet.java | 121 ++++++++++ .../example/asyncrest/AsyncRestServlet.java | 228 ++++++++++++++++++ .../example/asyncrest/SerialRestServlet.java | 106 ++++++++ .../META-INF/resources/asyncrest.html | 38 +++ .../META-INF/resources/asyncrest/green.png | Bin 0 -> 166 bytes .../META-INF/resources/asyncrest/red.png | Bin 0 -> 164 bytes .../main/resources/META-INF/web-fragment.xml | 22 ++ examples/async-rest/async-rest-webapp/pom.xml | 33 +++ .../src/main/webapp/META-INF/MANIFEST.MF | 3 + .../src/main/webapp/WEB-INF/jetty-web.xml | 15 ++ .../src/main/webapp/WEB-INF/web.xml | 9 + .../src/main/webapp/index.html | 44 ++++ .../jetty/example/asyncrest/DemoServer.java | 43 ++++ examples/async-rest/pom.xml | 16 ++ examples/embedded/pom.xml | 58 +++++ examples/embedded/prodDb.properties | 17 ++ examples/embedded/prodDb.script | 4 + .../eclipse/jetty/embedded/DumpServlet.java | 47 ++++ .../eclipse/jetty/embedded/FileServer.java | 63 +++++ .../eclipse/jetty/embedded/FileServerXml.java | 44 ++++ .../eclipse/jetty/embedded/HelloHandler.java | 62 +++++ .../eclipse/jetty/embedded/HelloServlet.java | 48 ++++ .../eclipse/jetty/embedded/LikeJettyXml.java | 127 ++++++++++ .../jetty/embedded/ManyConnectors.java | 117 +++++++++ .../eclipse/jetty/embedded/ManyContexts.java | 77 ++++++ .../eclipse/jetty/embedded/ManyHandlers.java | 123 ++++++++++ .../jetty/embedded/ManyServletContexts.java | 57 +++++ .../jetty/embedded/MinimalServlets.java | 54 +++++ .../eclipse/jetty/embedded/OneContext.java | 48 ++++ .../eclipse/jetty/embedded/OneHandler.java | 33 +++ .../jetty/embedded/OneServletContext.java | 48 ++++ .../org/eclipse/jetty/embedded/OneWebApp.java | 64 +++++ .../jetty/embedded/SecuredHelloHandler.java | 70 ++++++ .../jetty/embedded/SimplestServer.java | 34 +++ .../eclipse/jetty/embedded/SpdyServer.java | 181 ++++++++++++++ .../jetty/embedded/SplitFileServer.java | 71 ++++++ .../src/main/resources/fileserver.xml | 35 +++ .../main/resources/jetty-logging.properties | 9 + .../jetty/embedded/GzipHandlerTest.java | 124 ++++++++++ .../org/eclipse/jetty/embedded/TestXml.java | 36 +++ .../src/test/resources/dir0/test0.txt | 1 + .../src/test/resources/dir1/test1.txt | 1 + .../src/test/resources/realm.properties | 22 ++ 44 files changed, 2382 insertions(+) create mode 100644 examples/async-rest/async-rest-jar/pom.xml create mode 100644 examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/AbstractRestServlet.java create mode 100644 examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/AsyncRestServlet.java create mode 100644 examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/SerialRestServlet.java create mode 100644 examples/async-rest/async-rest-jar/src/main/resources/META-INF/resources/asyncrest.html create mode 100644 examples/async-rest/async-rest-jar/src/main/resources/META-INF/resources/asyncrest/green.png create mode 100644 examples/async-rest/async-rest-jar/src/main/resources/META-INF/resources/asyncrest/red.png create mode 100644 examples/async-rest/async-rest-jar/src/main/resources/META-INF/web-fragment.xml create mode 100644 examples/async-rest/async-rest-webapp/pom.xml create mode 100644 examples/async-rest/async-rest-webapp/src/main/webapp/META-INF/MANIFEST.MF create mode 100644 examples/async-rest/async-rest-webapp/src/main/webapp/WEB-INF/jetty-web.xml create mode 100644 examples/async-rest/async-rest-webapp/src/main/webapp/WEB-INF/web.xml create mode 100644 examples/async-rest/async-rest-webapp/src/main/webapp/index.html create mode 100644 examples/async-rest/async-rest-webapp/src/test/java/org/eclipse/jetty/example/asyncrest/DemoServer.java create mode 100644 examples/async-rest/pom.xml create mode 100644 examples/embedded/pom.xml create mode 100644 examples/embedded/prodDb.properties create mode 100644 examples/embedded/prodDb.script create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/DumpServlet.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServer.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServerXml.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyContexts.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyHandlers.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyServletContexts.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneContext.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneHandler.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneServletContext.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneWebApp.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/SecuredHelloHandler.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/SimplestServer.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/SpdyServer.java create mode 100644 examples/embedded/src/main/java/org/eclipse/jetty/embedded/SplitFileServer.java create mode 100644 examples/embedded/src/main/resources/fileserver.xml create mode 100644 examples/embedded/src/main/resources/jetty-logging.properties create mode 100644 examples/embedded/src/test/java/org/eclipse/jetty/embedded/GzipHandlerTest.java create mode 100644 examples/embedded/src/test/java/org/eclipse/jetty/embedded/TestXml.java create mode 100644 examples/embedded/src/test/resources/dir0/test0.txt create mode 100644 examples/embedded/src/test/resources/dir1/test1.txt create mode 100644 examples/embedded/src/test/resources/realm.properties diff --git a/examples/async-rest/async-rest-jar/pom.xml b/examples/async-rest/async-rest-jar/pom.xml new file mode 100644 index 00000000000..919bcd955d7 --- /dev/null +++ b/examples/async-rest/async-rest-jar/pom.xml @@ -0,0 +1,29 @@ + + + org.eclipse.jetty + example-async-rest + 9.0.0-SNAPSHOT + + 4.0.0 + org.eclipse.jetty.example-async-rest + example-async-rest-jar + jar + Example Async Rest :: Jar + + + org.eclipse.jetty + jetty-client + ${project.version} + + + org.eclipse.jetty + jetty-util-ajax + ${project.version} + + + org.eclipse.jetty.orbit + javax.servlet + provided + + + diff --git a/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/AbstractRestServlet.java b/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/AbstractRestServlet.java new file mode 100644 index 00000000000..cd27972cc57 --- /dev/null +++ b/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/AbstractRestServlet.java @@ -0,0 +1,121 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.example.asyncrest; + +import java.io.IOException; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.net.URLEncoder; +import java.util.Map; +import java.util.Queue; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Abstract Servlet implementation class AsyncRESTServlet. + * Enquires ebay REST service for auctions by key word. + * May be configured with init parameters:
+ *
appid
The eBay application ID to use
+ *
+ * Each request examines the following request parameters:
+ *
items
The keyword to search for
+ *
+ */ +public class AbstractRestServlet extends HttpServlet +{ + protected final static String __DEFAULT_APPID = "Webtide81-adf4-4f0a-ad58-d91e41bbe85"; + protected final static String STYLE = + ""; + + protected final static String ITEMS_PARAM = "items"; + protected final static String APPID_PARAM = "appid"; + + protected String _appid; + + @Override + public void init(ServletConfig servletConfig) throws ServletException + { + if (servletConfig.getInitParameter(APPID_PARAM) == null) + _appid = __DEFAULT_APPID; + else + _appid = servletConfig.getInitParameter(APPID_PARAM); + } + + protected String restURL(String item) + { + try + { + return ("http://open.api.ebay.com/shopping?MaxEntries=3&appid=" + _appid + + "&version=573&siteid=0&callname=FindItems&responseencoding=JSON&QueryKeywords=" + + URLEncoder.encode(item,"UTF-8")); + } + catch(Exception e) + { + throw new RuntimeException(e); + } + } + + protected String generateThumbs(Queue> results) + { + StringBuilder thumbs = new StringBuilder(); + for (Map m : results) + { + if (!m.containsKey("GalleryURL")) + continue; + + thumbs.append(""); + thumbs.append(""); + thumbs.append(" "); + } + return thumbs.toString(); + } + + protected String ms(long nano) + { + BigDecimal dec = new BigDecimal(nano); + return dec.divide(new BigDecimal(1000000L)).setScale(1,RoundingMode.UP).toString(); + } + + protected int width(long nano) + { + int w=(int)((nano+999999L)/5000000L); + if (w==0) + w=2; + return w; + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + doGet(request, response); + } + +} diff --git a/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/AsyncRestServlet.java b/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/AsyncRestServlet.java new file mode 100644 index 00000000000..df1f88d24a4 --- /dev/null +++ b/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/AsyncRestServlet.java @@ -0,0 +1,228 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.example.asyncrest; + +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.ByteBuffer; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.servlet.AsyncContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.api.Response; +import org.eclipse.jetty.client.api.Result; +import org.eclipse.jetty.http.HttpMethod; +import org.eclipse.jetty.util.BufferUtil; +import org.eclipse.jetty.util.Utf8StringBuilder; +import org.eclipse.jetty.util.ajax.JSON; + +/** + * Servlet implementation class AsyncRESTServlet. + * Enquires ebay REST service for auctions by key word. + * May be configured with init parameters:
+ *
appid
The eBay application ID to use
+ *
+ * Each request examines the following request parameters:
+ *
items
The keyword to search for
+ *
+ */ +public class AsyncRestServlet extends AbstractRestServlet +{ + final static String RESULTS_ATTR = "org.eclipse.jetty.demo.client"; + final static String DURATION_ATTR = "org.eclipse.jetty.demo.duration"; + final static String START_ATTR = "org.eclispe.jetty.demo.start"; + + HttpClient _client; + + @Override + public void init(ServletConfig servletConfig) throws ServletException + { + super.init(servletConfig); + + _client = new HttpClient(); + + try + { + _client.start(); + } + catch (Exception e) + { + throw new ServletException(e); + } + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + Long start=System.nanoTime(); + + // Do we have results yet? + Queue> results = (Queue>) request.getAttribute(RESULTS_ATTR); + + // If no results, this must be the first dispatch, so send the REST request(s) + if (results==null) + { + // define results data structures + final Queue> resultsQueue = new ConcurrentLinkedQueue>(); + request.setAttribute(RESULTS_ATTR, results=resultsQueue); + + // suspend the request + // This is done before scheduling async handling to avoid race of + // dispatch before startAsync! + final AsyncContext async = request.startAsync(); + async.setTimeout(30000); + + // extract keywords to search for + String[] keywords=request.getParameter(ITEMS_PARAM).split(","); + final AtomicInteger outstanding=new AtomicInteger(keywords.length); + + // Send request each keyword + for (final String item:keywords) + { + _client.newRequest(restURL(item)).method(HttpMethod.GET).send( + new AsyncRestRequest() + { + @Override + void onAuctionFound(Map auction) + { + resultsQueue.add(auction); + } + @Override + void onComplete() + { + if (outstanding.decrementAndGet()<=0) + async.dispatch(); + } + }); + } + + // save timing info and return + request.setAttribute(START_ATTR, start); + request.setAttribute(DURATION_ATTR, new Long(System.nanoTime() - start)); + + return; + } + + // We have results! + + // Generate the response + String thumbs = generateThumbs(results); + + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(STYLE); + out.println(""); + + long initial = (Long) request.getAttribute(DURATION_ATTR); + long start0 = (Long) request.getAttribute(START_ATTR); + + long now = System.nanoTime(); + long total=now-start0; + long generate=now-start; + long thread=initial+generate; + + out.print("Asynchronous: "+request.getParameter(ITEMS_PARAM)+"
"); + out.print("Total Time: "+ms(total)+"ms
"); + + out.print("Thread held (red): "+ms(thread)+"ms (" + ms(initial) + " initial + " + ms(generate) + " generate )
"); + out.print("Async wait (green): "+ms(total-thread)+"ms
"); + + out.println(""+ + ""+ + ""); + + out.println("
"); + out.println(thumbs); + out.println("
"); + out.println(""); + out.close(); + } + + private abstract class AsyncRestRequest implements Response.Listener + { + final Utf8StringBuilder _content = new Utf8StringBuilder(); + + AsyncRestRequest() + { + } + + @Override + public void onBegin(Response response) + { + } + + @Override + public void onHeaders(Response response) + { + } + + @Override + public void onContent(Response response, ByteBuffer content) + { + byte[] bytes = BufferUtil.toArray(content); + _content.append(bytes,0,bytes.length); + } + + @Override + public void onSuccess(Response response) + { + } + + @Override + public void onFailure(Response response, Throwable failure) + { + } + + @Override + public void onComplete(Result result) + { + // extract auctions from the results + Map query = (Map) JSON.parse(_content.toString()); + Object[] auctions = (Object[]) query.get("Item"); + if (auctions != null) + { + for (Object o : auctions) + onAuctionFound((Map)o); + } + onComplete(); + + } + + abstract void onAuctionFound(Map details); + abstract void onComplete(); + + }; + + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + doGet(request, response); + } + +} diff --git a/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/SerialRestServlet.java b/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/SerialRestServlet.java new file mode 100644 index 00000000000..8097ef02adb --- /dev/null +++ b/examples/async-rest/async-rest-jar/src/main/java/org/eclipse/jetty/example/asyncrest/SerialRestServlet.java @@ -0,0 +1,106 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.example.asyncrest; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.util.ajax.JSON; + +/** + * Servlet implementation class SerialRestServlet + */ +public class SerialRestServlet extends AbstractRestServlet +{ + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + long start = System.nanoTime(); + + + String[] keywords=request.getParameter(ITEMS_PARAM).split(","); + Queue> results = new LinkedList>(); + + // make all requests serially + for (String itemName : keywords) + { + URL url = new URL(restURL(itemName)); + + HttpURLConnection connection = (HttpURLConnection)url.openConnection(); + connection.setRequestMethod("GET"); + + Map query = (Map)JSON.parse(new BufferedReader(new InputStreamReader(connection.getInputStream()))); + Object[] auctions = (Object[]) query.get("Item"); + if (auctions != null) + { + for (Object o : auctions) + results.add((Map) o); + } + } + + + // Generate the response + String thumbs=generateThumbs(results); + + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(STYLE); + out.println(""); + + long now = System.nanoTime(); + long total=now-start; + + out.print("Blocking: "+request.getParameter(ITEMS_PARAM)+"
"); + out.print("Total Time: "+ms(total)+"ms
"); + out.print("Thread held (red): "+ms(total)+"ms
"); + + out.println(""); + + out.println("
"); + out.println(thumbs); + out.println("
"); + out.println(""); + out.close(); + + + + } + + /** + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse + * response) + */ + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + doGet(request, response); + } + +} diff --git a/examples/async-rest/async-rest-jar/src/main/resources/META-INF/resources/asyncrest.html b/examples/async-rest/async-rest-jar/src/main/resources/META-INF/resources/asyncrest.html new file mode 100644 index 00000000000..f92f7f661d4 --- /dev/null +++ b/examples/async-rest/async-rest-jar/src/main/resources/META-INF/resources/asyncrest.html @@ -0,0 +1,38 @@ + + + + + +

Blocking vs Asynchronous REST

+

+This demo calls the EBay WS API both synchronously and asynchronously, +to obtain items matching each of the keywords passed on the query +string. The time the request thread is head is displayed for both. +

+ + + + + + + + + + + + + +
+ + + +
+ + + +
+ + diff --git a/examples/async-rest/async-rest-jar/src/main/resources/META-INF/resources/asyncrest/green.png b/examples/async-rest/async-rest-jar/src/main/resources/META-INF/resources/asyncrest/green.png new file mode 100644 index 0000000000000000000000000000000000000000..d0fb8420c5dbe9403c699c66f0d173cf09f5dbac GIT binary patch literal 166 zcmeAS@N?(olHy`uVBq!ia0vp^93afW1SGw4HSYi^#^NA%Cx&(BWL^R}oCO|{#S9GG z!XV7ZFl&wkP>{XE)7O>#CW{cGp=NP}b`?-avcxr_#5q4VH#M(>!MP|ku_QG`p**uB zL&4qCHz2%`PaLR7*we)^gyVX0%8&C6q6UTrJgS@wXPg-MB`*Gc1C(a)boFyt=akR{ E01^u){XE)7O>#CW{cGA&0%8wF*#3vcxr_#5q4VH#M(>!MP|ku_QG`p**uB zL&4qCHz2%`PaLR7(9^{+gyVYhpYsi}28KMEoD63j8TqfZ?P>r@GI+ZBxvX + + SerialRestServlet + SerialRestServlet + org.eclipse.jetty.example.asyncrest.SerialRestServlet + + + SerialRestServlet + /testSerial + + + + AsyncRestServlet + AsyncRestServlet + org.eclipse.jetty.example.asyncrest.AsyncRestServlet + true + + + AsyncRestServlet + /testAsync + + \ No newline at end of file diff --git a/examples/async-rest/async-rest-webapp/pom.xml b/examples/async-rest/async-rest-webapp/pom.xml new file mode 100644 index 00000000000..4544b19ade0 --- /dev/null +++ b/examples/async-rest/async-rest-webapp/pom.xml @@ -0,0 +1,33 @@ + + + org.eclipse.jetty + example-async-rest + 9.0.0-SNAPSHOT + + 4.0.0 + org.eclipse.jetty.example-async-rest + example-async-rest-webapp + war + Example Async Rest :: Webapp + + async-rest + + + + org.eclipse.jetty.example-async-rest + example-async-rest-jar + ${project.version} + + + org.eclipse.jetty + jetty-webapp + ${project.version} + test + + + org.eclipse.jetty.orbit + javax.servlet + provided + + + diff --git a/examples/async-rest/async-rest-webapp/src/main/webapp/META-INF/MANIFEST.MF b/examples/async-rest/async-rest-webapp/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 00000000000..5e9495128c0 --- /dev/null +++ b/examples/async-rest/async-rest-webapp/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/examples/async-rest/async-rest-webapp/src/main/webapp/WEB-INF/jetty-web.xml b/examples/async-rest/async-rest-webapp/src/main/webapp/WEB-INF/jetty-web.xml new file mode 100644 index 00000000000..572942fd5ca --- /dev/null +++ b/examples/async-rest/async-rest-webapp/src/main/webapp/WEB-INF/jetty-web.xml @@ -0,0 +1,15 @@ + + + + + + + + async-rest webapp is deployed. DO NOT USE IN PRODUCTION! + + diff --git a/examples/async-rest/async-rest-webapp/src/main/webapp/WEB-INF/web.xml b/examples/async-rest/async-rest-webapp/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000000..8916bdb6afa --- /dev/null +++ b/examples/async-rest/async-rest-webapp/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,9 @@ + + + + Async REST Webservice Example + + diff --git a/examples/async-rest/async-rest-webapp/src/main/webapp/index.html b/examples/async-rest/async-rest-webapp/src/main/webapp/index.html new file mode 100644 index 00000000000..e7f5d0a2c02 --- /dev/null +++ b/examples/async-rest/async-rest-webapp/src/main/webapp/index.html @@ -0,0 +1,44 @@ + + + + + +

Blocking vs Asynchronous REST

+

+This demo calls the EBay WS API both synchronously and asynchronously, +to obtain items matching each of the keywords passed on the query +string. The time the request thread is held by the servlet is displayed in red for both. +

+ + + + + + + + + + + + + +
+ + + +
+ + + +
+By the use of Asynchronous Servlets and the Jetty Asychronous client, the server is able to release the thread (green) while +waiting for the response from Ebay. This thread goes back into the thread pool and can service many other requests during the wait. +This greatly reduces the number of threads needed, which in turn greatly reduces the memory requirements of the server. +

+Press reload to see even better results after JIT and TCP/IP warmup! + + + diff --git a/examples/async-rest/async-rest-webapp/src/test/java/org/eclipse/jetty/example/asyncrest/DemoServer.java b/examples/async-rest/async-rest-webapp/src/test/java/org/eclipse/jetty/example/asyncrest/DemoServer.java new file mode 100644 index 00000000000..91471d50da1 --- /dev/null +++ b/examples/async-rest/async-rest-webapp/src/test/java/org/eclipse/jetty/example/asyncrest/DemoServer.java @@ -0,0 +1,43 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.example.asyncrest; + +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.webapp.WebAppContext; + +public class DemoServer +{ + public static void main(String[] args) + throws Exception + { + String jetty_home = System.getProperty("jetty.home","."); + + Server server = new Server(Integer.getInteger("jetty.port",8080).intValue()); + + WebAppContext webapp = new WebAppContext(); + webapp.setContextPath("/"); + webapp.setWar(jetty_home+"/target/async-rest/"); + webapp.setParentLoaderPriority(true); + webapp.setServerClasses(new String[]{}); + server.setHandler(webapp); + + server.start(); + server.join(); + } +} diff --git a/examples/async-rest/pom.xml b/examples/async-rest/pom.xml new file mode 100644 index 00000000000..9d4e527042a --- /dev/null +++ b/examples/async-rest/pom.xml @@ -0,0 +1,16 @@ + + + org.eclipse.jetty + jetty-project + 9.0.0-SNAPSHOT + + 4.0.0 + org.eclipse.jetty + example-async-rest + pom + Example Async Rest + + async-rest-jar + async-rest-webapp + + diff --git a/examples/embedded/pom.xml b/examples/embedded/pom.xml new file mode 100644 index 00000000000..132d7b41974 --- /dev/null +++ b/examples/embedded/pom.xml @@ -0,0 +1,58 @@ + + + org.eclipse.jetty + jetty-project + 9.0.0-SNAPSHOT + + 4.0.0 + example-jetty-embedded + Example :: Jetty Embedded + Jetty Embedded Examples + + + org.eclipse.jetty + jetty-util-ajax + ${project.version} + + + org.eclipse.jetty + jetty-webapp + ${project.version} + + + org.eclipse.jetty + jetty-security + ${project.version} + + + org.eclipse.jetty + jetty-servlets + ${project.version} + + + org.eclipse.jetty + jetty-deploy + ${project.version} + + + org.eclipse.jetty + jetty-jmx + ${project.version} + + + org.eclipse.jetty.websocket + websocket-server + ${project.version} + + + org.eclipse.jetty.spdy + spdy-http-server + ${project.version} + + + org.eclipse.jetty.toolchain + jetty-test-helper + + + + diff --git a/examples/embedded/prodDb.properties b/examples/embedded/prodDb.properties new file mode 100644 index 00000000000..5130d856783 --- /dev/null +++ b/examples/embedded/prodDb.properties @@ -0,0 +1,17 @@ +#HSQL Database Engine 1.8.0.10 +#Mon Nov 08 13:35:35 EST 2010 +hsqldb.script_format=0 +runtime.gc_interval=0 +sql.enforce_strict_size=false +hsqldb.cache_size_scale=8 +readonly=false +hsqldb.nio_data_file=true +hsqldb.cache_scale=14 +version=1.8.0 +hsqldb.default_table_type=memory +hsqldb.cache_file_scale=1 +hsqldb.log_size=200 +modified=no +hsqldb.cache_version=1.7.0 +hsqldb.original_version=1.8.0 +hsqldb.compatible_version=1.8.0 diff --git a/examples/embedded/prodDb.script b/examples/embedded/prodDb.script new file mode 100644 index 00000000000..382d243636c --- /dev/null +++ b/examples/embedded/prodDb.script @@ -0,0 +1,4 @@ +CREATE SCHEMA PUBLIC AUTHORIZATION DBA +CREATE USER SA PASSWORD "" +GRANT DBA TO SA +SET WRITE_DELAY 10 diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/DumpServlet.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/DumpServlet.java new file mode 100644 index 00000000000..f9b12ec2353 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/DumpServlet.java @@ -0,0 +1,47 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +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 + { + response.setContentType("text/html"); + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().println("

DumpServlet

");
+        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());
+        response.getWriter().println("
"); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServer.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServer.java new file mode 100644 index 00000000000..04505208376 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServer.java @@ -0,0 +1,63 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.DefaultHandler; +import org.eclipse.jetty.server.handler.HandlerList; +import org.eclipse.jetty.server.handler.ResourceHandler; +import org.eclipse.jetty.util.log.Log; +import org.eclipse.jetty.util.log.Logger; + +/* ------------------------------------------------------------ */ +/** Simple Jetty FileServer. + * This is a simple example of Jetty configured as a FileServer. + * + * File server Usage - java org.eclipse.jetty.server.example.FileServer [ port [ + * docroot ]] + * + * @see FileServerXml for the equivalent example done in XML configuration. + * @author gregw + * + */ +public class FileServer +{ + private static final Logger LOG = Log.getLogger(FileServer.class); + + public static void main(String[] args) throws Exception + { + Server server = new Server(args.length == 0?8080:Integer.parseInt(args[0])); + + ResourceHandler resource_handler = new ResourceHandler(); + resource_handler.setDirectoriesListed(true); + resource_handler.setWelcomeFiles(new String[]{ "index.html" }); + + resource_handler.setResourceBase(args.length == 2?args[1]:"."); + LOG.info("serving " + resource_handler.getBaseResource()); + + HandlerList handlers = new HandlerList(); + handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() }); + server.setHandler(handlers); + + server.start(); + server.join(); + } + +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServerXml.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServerXml.java new file mode 100644 index 00000000000..db4478b1898 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServerXml.java @@ -0,0 +1,44 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.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. + *

+ * See fileserver.xml + */ +public class FileServerXml +{ + 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(); + server.start(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java new file mode 100644 index 00000000000..f1fee637321 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java @@ -0,0 +1,62 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.AbstractHandler; + +public class HelloHandler extends AbstractHandler +{ + final String _greeting; + final String _body; + + public HelloHandler() + { + _greeting="Hello World"; + _body=null; + } + + public HelloHandler(String greeting) + { + _greeting=greeting; + _body=null; + } + + public HelloHandler(String greeting,String body) + { + _greeting=greeting; + _body=body; + } + + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException + { + response.setContentType("text/html;charset=utf-8"); + response.setStatus(HttpServletResponse.SC_OK); + baseRequest.setHandled(true); + + response.getWriter().println("

"+_greeting+"

"); + if (_body!=null) + response.getWriter().println(_body); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java new file mode 100644 index 00000000000..f24f184840d --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java @@ -0,0 +1,48 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@SuppressWarnings("serial") +public class HelloServlet extends HttpServlet +{ + String greeting = "Hello"; + + public HelloServlet() + { + } + + public HelloServlet(String hi) + { + greeting = hi; + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + response.setContentType("text/html"); + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().println("

" + greeting + " from HelloServlet

"); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java new file mode 100644 index 00000000000..c500162b082 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java @@ -0,0 +1,127 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import java.lang.management.ManagementFactory; + +import org.eclipse.jetty.deploy.DeploymentManager; +import org.eclipse.jetty.deploy.providers.WebAppProvider; +import org.eclipse.jetty.jmx.MBeanContainer; +import org.eclipse.jetty.security.HashLoginService; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.HttpConnectionFactory; +import org.eclipse.jetty.server.NCSARequestLog; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.handler.ContextHandlerCollection; +import org.eclipse.jetty.server.handler.DefaultHandler; +import org.eclipse.jetty.server.handler.HandlerCollection; +import org.eclipse.jetty.server.handler.RequestLogHandler; +import org.eclipse.jetty.server.handler.StatisticsHandler; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.eclipse.jetty.util.thread.QueuedThreadPool; + +public class LikeJettyXml +{ + 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); + + // Setup Threadpool + QueuedThreadPool threadPool = new QueuedThreadPool(); + threadPool.setMaxThreads(500); + + Server server = new Server(threadPool); + server.manage(threadPool); + server.setDumpAfterStart(false); + server.setDumpBeforeStop(false); + + // Setup JMX + MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); + server.addBean(mbContainer); + + // Setup Connectors + HttpConnectionFactory http = new HttpConnectionFactory(); + http.getHttpChannelConfig().setSecurePort(8443); + ServerConnector connector = new ServerConnector(server,http); + connector.setPort(8080); + connector.setIdleTimeout(30000); + + server.addConnector(connector); + + SslContextFactory sslContextFactory = new SslContextFactory(); + sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore"); + sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); + 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", + "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"); + ServerConnector sslConnector = new ServerConnector(server,sslContextFactory); + sslConnector.setPort(8443); + server.addConnector(sslConnector); + sslConnector.open(); + + HandlerCollection handlers = new HandlerCollection(); + ContextHandlerCollection contexts = new ContextHandlerCollection(); + RequestLogHandler requestLogHandler = new RequestLogHandler(); + + handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); + + StatisticsHandler stats = new StatisticsHandler(); + stats.setHandler(handlers); + + server.setHandler(stats); + + // Setup deployers + DeploymentManager deployer = new DeploymentManager(); + deployer.setContexts(contexts); + server.addBean(deployer); + + WebAppProvider webapp_provider = new WebAppProvider(); + webapp_provider.setMonitoredDirName(jetty_home + "/webapps"); + webapp_provider.setParentLoaderPriority(false); + webapp_provider.setExtractWars(true); + webapp_provider.setScanInterval(2); + webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml"); + deployer.addAppProvider(webapp_provider); + + HashLoginService login = new HashLoginService(); + login.setName("Test Realm"); + login.setConfig(jetty_home + "/etc/realm.properties"); + server.addBean(login); + + NCSARequestLog requestLog = new NCSARequestLog(jetty_home + "/logs/jetty-yyyy_mm_dd.log"); + requestLog.setExtended(false); + requestLogHandler.setRequestLog(requestLog); + + server.setStopAtShutdown(true); + server.setSendServerVersion(true); + + server.start(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java new file mode 100644 index 00000000000..bf3a6a55e45 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java @@ -0,0 +1,117 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.io.ArrayByteBufferPool; +import org.eclipse.jetty.io.ByteBufferPool; +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.ForwardedRequestCustomizer; +import org.eclipse.jetty.server.HttpChannelConfig; +import org.eclipse.jetty.server.HttpConnectionFactory; +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.spdy.server.NPNServerConnectionFactory; +import org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnectionFactory; +import org.eclipse.jetty.spdy.server.http.PushStrategy; +import org.eclipse.jetty.spdy.server.http.ReferrerPushStrategy; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.eclipse.jetty.util.thread.QueuedThreadPool; +import org.eclipse.jetty.util.thread.TimerScheduler; + +/* ------------------------------------------------------------ */ +/** + * A Jetty server with multiple connectors. + * + */ +public class ManyConnectors +{ + public static void main(String[] args) throws Exception + { + String jetty_home = System.getProperty("jetty.home","../jetty-server/src/main/config"); + System.setProperty("jetty.home", jetty_home); + + Server server = new Server(); + + // HTTP connector + ServerConnector connector0 = new ServerConnector(server); + connector0.setPort(8080); + connector0.setIdleTimeout(30000); + + // HTTPS connector + SslContextFactory sslContextFactory = new SslContextFactory(); + sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore"); + sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); + sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g"); + + ServerConnector connector1 = new ServerConnector(server,sslContextFactory); + connector1.setPort(8443); + + + // A verbosely fully configured connector with SSL, SPDY and HTTP + + HttpChannelConfig config = new HttpChannelConfig(); + config.setSecureScheme("https"); + config.setSecurePort(8443); + config.setOutputBufferSize(32768); + config.setRequestHeaderSize(8192); + config.setResponseHeaderSize(8192); + config.addCustomizer(new ForwardedRequestCustomizer()); + config.addCustomizer(new SecureRequestCustomizer()); + + HttpConnectionFactory http = new HttpConnectionFactory(config); + http.setInputBufferSize(16384); + + PushStrategy push = new ReferrerPushStrategy(); + HTTPSPDYServerConnectionFactory spdy2 = new HTTPSPDYServerConnectionFactory(2,config,push); + spdy2.setInputBufferSize(8192); + spdy2.setInitialWindowSize(32768); + + HTTPSPDYServerConnectionFactory spdy3 = new HTTPSPDYServerConnectionFactory(3,config,push); + spdy2.setInputBufferSize(8192); + + NPNServerConnectionFactory npn = new NPNServerConnectionFactory(spdy3.getProtocol(),spdy2.getProtocol(),http.getProtocol()); + npn.setDefaultProtocol(http.getProtocol()); + npn.setInputBufferSize(1024); + + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,npn.getProtocol()); + + QueuedThreadPool threadPool = new QueuedThreadPool(); + threadPool.setMaxThreads(256); + TimerScheduler scheduler = new TimerScheduler(); + ByteBufferPool bufferPool= new ArrayByteBufferPool(32,4096,32768); + + ServerConnector connector2 = new ServerConnector(server,threadPool,scheduler,bufferPool,2,2,ssl,npn,spdy3,spdy2,http); + connector2.setDefaultProtocol("ssl-npn"); + connector2.setPort(8444); + connector2.setIdleTimeout(30000); + connector2.setSoLingerTime(10000); + + // Set the connectors + server.setConnectors(new Connector[] { connector0, connector1, connector2 }); + + + server.setHandler(new HelloHandler()); + + server.start(); + server.dumpStdErr(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyContexts.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyContexts.java new file mode 100644 index 00000000000..958bf147cda --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyContexts.java @@ -0,0 +1,77 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.server.handler.ContextHandlerCollection; + +/* ------------------------------------------------------------ */ +/** + * 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 ManyContexts +{ + public final static String BODY= + "root context
"+ + "normal context
"+ + "virtual context
"; + + public static void main(String[] args) throws Exception + { + Server server = new Server(); + ServerConnector connector = new ServerConnector(server); + connector.setPort(8080); + server.setConnectors(new Connector[] + { connector }); + + ContextHandler context0 = new ContextHandler(); + context0.setContextPath("/"); + Handler handler0 = new HelloHandler("Root Context",BODY); + context0.setHandler(handler0); + + ContextHandler context1 = new ContextHandler(); + context1.setContextPath("/context"); + Handler handler1 = new HelloHandler("A Context",BODY); + context1.setHandler(handler1); + + ContextHandler context2 = new ContextHandler(); + context2.setContextPath("/context"); + context2.setVirtualHosts(new String[] + { "127.0.0.2" }); + Handler handler2 = new HelloHandler("A Virtual Context",BODY); + context2.setHandler(handler2); + + ContextHandlerCollection contexts = new ContextHandlerCollection(); + contexts.setHandlers(new Handler[] + { context0, context1, context2 }); + + server.setHandler(contexts); + + server.start(); + System.err.println(server.dump()); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyHandlers.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyHandlers.java new file mode 100644 index 00000000000..f220739b0d9 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyHandlers.java @@ -0,0 +1,123 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import java.io.File; +import java.io.IOException; +import java.util.Map; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.NCSARequestLog; +import org.eclipse.jetty.server.Request; +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.HandlerCollection; +import org.eclipse.jetty.server.handler.HandlerList; +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: + *
    + *
  • handle the request and completely generate the response + *
  • partially handle the request, but defer response generation to another + * handler. + *
  • select another handler to pass the request to. + *
  • use business logic to decide to do one of the above. + *
+ * + * Multiple handlers may be combined with: + *
    + *
  • {@link HandlerWrapper} which will nest one handler inside another. In + * this example, the HelloHandler is nested inside a HandlerWrapper that sets + * the greeting as a request attribute. + *
  • {@link HandlerList} which will call a collection of handlers until the + * request is marked as handled. In this example, a list is used to combine the + * param handler (which only handles the request if there are parameters) and + * the wrapper handler. Frequently handler lists are terminated with the + * {@link DefaultHandler}, which will generate a suitable 404 response if the + * request has not been handled. + *
  • {@link HandlerCollection} which will call each handler regardless if the + * request has been handled or not. Typically this is used to always pass a + * request to the logging handler. + *
+ */ +public class ManyHandlers +{ + 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); + } + }; + Handler hello = new HelloHandler(); + Handler dft = new DefaultHandler(); + RequestLogHandler log = new RequestLogHandler(); + + // configure logs + log.setRequestLog(new NCSARequestLog(File.createTempFile("demo","log").getAbsolutePath())); + + // create the handler collections + HandlerCollection handlers = new HandlerCollection(); + HandlerList list = new HandlerList(); + + // link them all together + wrapper.setHandler(hello); + list.setHandlers(new Handler[] + { param, wrapper, dft }); + handlers.setHandlers(new Handler[] + { list, log }); + + 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 params = request.getParameterMap(); + if (params.size() > 0) + { + response.setContentType("text/plain"); + response.getWriter().println(JSON.toString(params)); + ((Request)request).setHandled(true); + } + } + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyServletContexts.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyServletContexts.java new file mode 100644 index 00000000000..d2a3306b8db --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyServletContexts.java @@ -0,0 +1,57 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + + +import java.lang.management.ManagementFactory; + +import org.eclipse.jetty.jmx.MBeanContainer; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.ContextHandlerCollection; +import org.eclipse.jetty.servlet.DefaultServlet; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; + +public class ManyServletContexts +{ + 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); + + 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/*"); + + 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(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java new file mode 100644 index 00000000000..96775ec7c62 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java @@ -0,0 +1,54 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletHandler; + +public class MinimalServlets +{ + public static void main(String[] args) throws Exception + { + Server server = new Server(8080); + ServletHandler handler = new ServletHandler(); + server.setHandler(handler); + + handler.addServletWithMapping("org.eclipse.jetty.embedded.MinimalServlets$HelloServlet","/"); + + server.start(); + server.join(); + } + + public static class HelloServlet extends HttpServlet + { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + { + response.setContentType("text/html"); + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().println("

Hello SimpleServlet

"); + } + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneContext.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneContext.java new file mode 100644 index 00000000000..44dfbcc986d --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneContext.java @@ -0,0 +1,48 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.ContextHandler; + +/* ------------------------------------------------------------ */ +/** + * A {@link ContextHandler} provides a common environment for multiple Handlers, + * such as: URI context path, class loader, static resource base. + * + * Typically a ContextHandler is used only when multiple contexts are likely. + */ +public class OneContext +{ + public static void main(String[] args) throws Exception + { + Server server = new Server(8080); + + ContextHandler context = new ContextHandler(); + context.setContextPath("/"); + context.setResourceBase("."); + context.setClassLoader(Thread.currentThread().getContextClassLoader()); + server.setHandler(context); + + context.setHandler(new HelloHandler()); + + server.start(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneHandler.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneHandler.java new file mode 100644 index 00000000000..6ba5846e723 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneHandler.java @@ -0,0 +1,33 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.server.Server; + +public class OneHandler +{ + public static void main(String[] args) throws Exception + { + Server server = new Server(8080); + server.setHandler(new HelloHandler()); + + server.start(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneServletContext.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneServletContext.java new file mode 100644 index 00000000000..f21607b21a8 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneServletContext.java @@ -0,0 +1,48 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; + +public class OneServletContext +{ + public static void main(String[] args) throws Exception + { + Server server = new Server(8080); + + ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); + context.setContextPath("/"); + server.setHandler(context); + + // Server content from tmp + ServletHolder holder = context.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class,"/tmp/*"); + holder.setInitParameter("resourceBase","/tmp"); + holder.setInitParameter("pathInfoOnly","true"); + + // Serve some hello world servlets + context.addServlet(new ServletHolder(new HelloServlet()),"/*"); + context.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*"); + context.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*"); + + server.start(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneWebApp.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneWebApp.java new file mode 100644 index 00000000000..7ef98f4ad53 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneWebApp.java @@ -0,0 +1,64 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.webapp.WebAppContext; + +public class OneWebApp +{ + public static void main(String[] args) throws Exception + { + Server server = new Server(); + + ServerConnector connector = new ServerConnector(server); + connector.setPort(Integer.getInteger("jetty.port",8080).intValue()); + server.setConnectors(new Connector[] + { connector }); + + + //If you're running this from inside Eclipse, then Server.getVersion will not provide + //the correct number as there is no manifest. Use the command line instead to provide the path to the + //test webapp + String war = args.length > 0?args[0]: "../test-jetty-webapp/target/test-jetty-webapp-"+Server.getVersion(); + String path = args.length > 1?args[1]:"/"; + + System.err.println(war + " " + path); + + WebAppContext webapp = new WebAppContext(); + webapp.setContextPath(path); + webapp.setWar(war); + + //If the webapp contains security constraints, you will need to configure a LoginService + if (war.contains("test-jetty-webapp")) + { + org.eclipse.jetty.security.HashLoginService loginService = new org.eclipse.jetty.security.HashLoginService(); + loginService.setName("Test Realm"); + loginService.setConfig("src/test/resources/realm.properties"); + webapp.getSecurityHandler().setLoginService(loginService); + } + + server.setHandler(webapp); + + server.start(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SecuredHelloHandler.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SecuredHelloHandler.java new file mode 100644 index 00000000000..63ccdcb3c45 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SecuredHelloHandler.java @@ -0,0 +1,70 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.jetty.security.ConstraintMapping; +import org.eclipse.jetty.security.ConstraintSecurityHandler; +import org.eclipse.jetty.security.HashLoginService; +import org.eclipse.jetty.security.LoginService; +import org.eclipse.jetty.security.authentication.BasicAuthenticator; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.util.security.Constraint; + +public class SecuredHelloHandler +{ + public static void main(String[] args) throws Exception + { + Server server = new Server(8080); + + LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties"); + server.addBean(loginService); + + ConstraintSecurityHandler security = new ConstraintSecurityHandler(); + server.setHandler(security); + + Constraint constraint = new Constraint(); + constraint.setName("auth"); + constraint.setAuthenticate( true ); + constraint.setRoles(new String[]{"user", "admin"}); + + ConstraintMapping mapping = new ConstraintMapping(); + mapping.setPathSpec( "/*" ); + mapping.setConstraint( constraint ); + + Set knownRoles = new HashSet(); + knownRoles.add("user"); + knownRoles.add("admin"); + + security.setConstraintMappings(Collections.singletonList(mapping), knownRoles); + security.setAuthenticator(new BasicAuthenticator()); + security.setLoginService(loginService); + security.setStrict(false); + + HelloHandler hh = new HelloHandler(); + + security.setHandler(hh); + + server.start(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SimplestServer.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SimplestServer.java new file mode 100644 index 00000000000..80b8732313b --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SimplestServer.java @@ -0,0 +1,34 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.server.Server; + +/* ------------------------------------------------------------ */ +/** The simplest possible Jetty server. + */ +public class SimplestServer +{ + public static void main(String[] args) throws Exception + { + Server server = new Server(8080); + server.start(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SpdyServer.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SpdyServer.java new file mode 100644 index 00000000000..a95c9a970de --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SpdyServer.java @@ -0,0 +1,181 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import java.lang.management.ManagementFactory; + +import org.eclipse.jetty.deploy.DeploymentManager; +import org.eclipse.jetty.deploy.providers.WebAppProvider; +import org.eclipse.jetty.io.ArrayByteBufferPool; +import org.eclipse.jetty.io.ByteBufferPool; +import org.eclipse.jetty.io.FilterConnection; +import org.eclipse.jetty.jmx.MBeanContainer; +import org.eclipse.jetty.security.HashLoginService; +import org.eclipse.jetty.server.FilterConnectionFactory; +import org.eclipse.jetty.server.ForwardedRequestCustomizer; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.HttpChannelConfig; +import org.eclipse.jetty.server.HttpConnectionFactory; +import org.eclipse.jetty.server.NCSARequestLog; +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.ContextHandlerCollection; +import org.eclipse.jetty.server.handler.DefaultHandler; +import org.eclipse.jetty.server.handler.HandlerCollection; +import org.eclipse.jetty.server.handler.RequestLogHandler; +import org.eclipse.jetty.server.handler.StatisticsHandler; +import org.eclipse.jetty.spdy.server.NPNServerConnectionFactory; +import org.eclipse.jetty.spdy.server.SPDYServerConnectionFactory; +import org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnectionFactory; +import org.eclipse.jetty.spdy.server.http.PushStrategy; +import org.eclipse.jetty.spdy.server.http.ReferrerPushStrategy; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.eclipse.jetty.util.thread.QueuedThreadPool; +import org.eclipse.jetty.util.thread.TimerScheduler; + +public class SpdyServer +{ + 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); + + // Setup Threadpool + QueuedThreadPool threadPool = new QueuedThreadPool(); + threadPool.setMaxThreads(500); + + Server server = new Server(threadPool); + server.manage(threadPool); + server.setDumpAfterStart(false); + server.setDumpBeforeStop(false); + + // Setup JMX + MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); + server.addBean(mbContainer); + + + // Common HTTP configuration + HttpChannelConfig config = new HttpChannelConfig(); + config.setSecurePort(8443); + config.addCustomizer(new ForwardedRequestCustomizer()); + config.addCustomizer(new SecureRequestCustomizer()); + + + // Http Connector + HttpConnectionFactory http = new HttpConnectionFactory(config); + FilterConnectionFactory filter = new FilterConnectionFactory(http.getProtocol()); + filter.addFilter(new FilterConnection.DumpToFileFilter("http-")); + ServerConnector httpConnector = new ServerConnector(server,filter,http); + httpConnector.setPort(8080); + httpConnector.setIdleTimeout(30000); + + server.addConnector(httpConnector); + + + // SSL configurations + SslContextFactory sslContextFactory = new SslContextFactory(); + sslContextFactory.setKeyStorePath(jetty_home + "/etc/keystore"); + sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4"); + 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", + "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 + SPDYServerConnectionFactory.checkNPNAvailable(); + + PushStrategy push = new ReferrerPushStrategy(); + HTTPSPDYServerConnectionFactory spdy2 = new HTTPSPDYServerConnectionFactory(2,config,push); + spdy2.setInputBufferSize(8192); + spdy2.setInitialWindowSize(32768); + + HTTPSPDYServerConnectionFactory spdy3 = new HTTPSPDYServerConnectionFactory(3,config,push); + spdy2.setInputBufferSize(8192); + + NPNServerConnectionFactory npn = new NPNServerConnectionFactory(spdy3.getProtocol(),spdy2.getProtocol(),http.getProtocol()); + npn.setDefaultProtocol(http.getProtocol()); + npn.setInputBufferSize(1024); + + FilterConnectionFactory npn_filter = new FilterConnectionFactory(npn.getProtocol()); + npn_filter.addFilter(new FilterConnection.DumpToFileFilter("npn-")); + + SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,npn_filter.getProtocol()); + FilterConnectionFactory ssl_filter = new FilterConnectionFactory(ssl.getProtocol()); + ssl_filter.addFilter(new FilterConnection.DumpToFileFilter("ssl-")); + + ServerConnector spdyConnector = new ServerConnector(server,ssl_filter,ssl,npn_filter,npn,spdy3,spdy2,http); + spdyConnector.setPort(8443); + + server.addConnector(spdyConnector); + + + // Setup handlers + HandlerCollection handlers = new HandlerCollection(); + ContextHandlerCollection contexts = new ContextHandlerCollection(); + RequestLogHandler requestLogHandler = new RequestLogHandler(); + + handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); + + StatisticsHandler stats = new StatisticsHandler(); + stats.setHandler(handlers); + + server.setHandler(stats); + + // Setup deployers + DeploymentManager deployer = new DeploymentManager(); + deployer.setContexts(contexts); + server.addBean(deployer); + + WebAppProvider webapp_provider = new WebAppProvider(); + webapp_provider.setMonitoredDirName(jetty_home + "/webapps"); + webapp_provider.setParentLoaderPriority(false); + webapp_provider.setExtractWars(true); + webapp_provider.setScanInterval(2); + webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml"); + deployer.addAppProvider(webapp_provider); + + HashLoginService login = new HashLoginService(); + login.setName("Test Realm"); + login.setConfig(jetty_home + "/etc/realm.properties"); + server.addBean(login); + + NCSARequestLog requestLog = new NCSARequestLog(jetty_home + "/logs/jetty-yyyy_mm_dd.log"); + requestLog.setExtended(false); + requestLogHandler.setRequestLog(requestLog); + + server.setStopAtShutdown(true); + server.setSendServerVersion(true); + + server.start(); + server.dumpStdErr(); + server.join(); + } +} diff --git a/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SplitFileServer.java b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SplitFileServer.java new file mode 100644 index 00000000000..a8f99346754 --- /dev/null +++ b/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SplitFileServer.java @@ -0,0 +1,71 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.server.Connector; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.server.handler.ContextHandlerCollection; +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 + { + Server server = new Server(); + ServerConnector connector = new ServerConnector(server); + connector.setPort(8090); + server.setConnectors(new Connector[] + { connector }); + + ContextHandler context0 = new ContextHandler(); + context0.setContextPath("/"); + ResourceHandler rh0 = new ResourceHandler(); + rh0.setBaseResource( Resource.newResource(MavenTestingUtils.getTestResourceDir("dir0"))); + context0.setHandler(rh0); + + ContextHandler context1 = new ContextHandler(); + context1.setContextPath("/"); + ResourceHandler rh1 = new ResourceHandler(); + rh1.setBaseResource( Resource.newResource(MavenTestingUtils.getTestResourceDir("dir1"))); + context1.setHandler(rh1); + + ContextHandlerCollection contexts = new ContextHandlerCollection(); + contexts.setHandlers(new Handler[] + { context0, context1 }); + + server.setHandler(contexts); + + server.start(); + System.err.println(server.dump()); + server.join(); + } +} diff --git a/examples/embedded/src/main/resources/fileserver.xml b/examples/embedded/src/main/resources/fileserver.xml new file mode 100644 index 00000000000..ac3a76f5ac5 --- /dev/null +++ b/examples/embedded/src/main/resources/fileserver.xml @@ -0,0 +1,35 @@ + + + + + + + + + 8080 + + + + + + + + + + + true + + index.html + + . + + + + + + + + + + + diff --git a/examples/embedded/src/main/resources/jetty-logging.properties b/examples/embedded/src/main/resources/jetty-logging.properties new file mode 100644 index 00000000000..f912160249f --- /dev/null +++ b/examples/embedded/src/main/resources/jetty-logging.properties @@ -0,0 +1,9 @@ +org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StdErrLog +org.eclipse.jetty.LEVEL=INFO +org.eclipse.jetty.STACKS=true +org.eclipse.jetty.SOURCE=false +#org.eclipse.jetty.STACKS=false +#org.eclipse.jetty.spdy.LEVEL=DEBUG +#org.eclipse.jetty.server.LEVEL=DEBUG +#org.eclipse.jetty.io.ssl.LEVEL=DEBUG +#org.eclipse.jetty.spdy.server.LEVEL=DEBUG diff --git a/examples/embedded/src/test/java/org/eclipse/jetty/embedded/GzipHandlerTest.java b/examples/embedded/src/test/java/org/eclipse/jetty/embedded/GzipHandlerTest.java new file mode 100644 index 00000000000..fdcea86c59c --- /dev/null +++ b/examples/embedded/src/test/java/org/eclipse/jetty/embedded/GzipHandlerTest.java @@ -0,0 +1,124 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.util.zip.GZIPInputStream; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.http.HttpTester; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.LocalConnector; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.AbstractHandler; +import org.eclipse.jetty.servlets.gzip.GzipHandler; +import org.eclipse.jetty.util.IO; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class GzipHandlerTest +{ + private static String __content = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis felis nunc. "+ + "Quisque suscipit mauris et ante auctor ornare rhoncus lacus aliquet. Pellentesque "+ + "habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. "+ + "Vestibulum sit amet felis augue, vel convallis dolor. Cras accumsan vehicula diam "+ + "at faucibus. Etiam in urna turpis, sed congue mi. Morbi et lorem eros. Donec vulputate "+ + "velit in risus suscipit lobortis. Aliquam id urna orci, nec sollicitudin ipsum. "+ + "Cras a orci turpis. Donec suscipit vulputate cursus. Mauris nunc tellus, fermentum "+ + "eu auctor ut, mollis at diam. Quisque porttitor ultrices metus, vitae tincidunt massa "+ + "sollicitudin a. Vivamus porttitor libero eget purus hendrerit cursus. Integer aliquam "+ + "consequat mauris quis luctus. Cras enim nibh, dignissim eu faucibus ac, mollis nec neque. "+ + "Aliquam purus mauris, consectetur nec convallis lacinia, porta sed ante. Suspendisse "+ + "et cursus magna. Donec orci enim, molestie a lobortis eu, imperdiet vitae neque."; + + private Server _server; + private LocalConnector _connector; + + @Before + public void init() throws Exception + { + _server = new Server(); + _connector = new LocalConnector(_server); + _server.addConnector(_connector); + + Handler testHandler = new AbstractHandler() + { + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, + ServletException + { + PrintWriter writer = response.getWriter(); + writer.write(__content); + writer.close(); + + baseRequest.setHandled(true); + } + }; + + GzipHandler gzipHandler = new GzipHandler(); + gzipHandler.setHandler(testHandler); + + _server.setHandler(gzipHandler); + _server.start(); + } + + @After + public void destroy() throws Exception + { + _server.stop(); + _server.join(); + } + + @Test + public void testGzipHandler() throws Exception + { + // generated and parsed test + HttpTester.Request request = HttpTester.newRequest(); + HttpTester.Response response; + + request.setMethod("GET"); + request.setVersion("HTTP/1.0"); + request.setHeader("Host","tester"); + request.setHeader("accept-encoding","gzip"); + request.setURI("/"); + + response = HttpTester.parseResponse(_connector.getResponses(request.generate())); + + assertTrue(response.get("Content-Encoding").equalsIgnoreCase("gzip")); + assertEquals(HttpServletResponse.SC_OK,response.getStatus()); + + InputStream testIn = new GZIPInputStream(new ByteArrayInputStream(response.getContentBytes())); + ByteArrayOutputStream testOut = new ByteArrayOutputStream(); + IO.copy(testIn,testOut); + + assertEquals(__content, testOut.toString("UTF8")); + + } +} diff --git a/examples/embedded/src/test/java/org/eclipse/jetty/embedded/TestXml.java b/examples/embedded/src/test/java/org/eclipse/jetty/embedded/TestXml.java new file mode 100644 index 00000000000..58a3319f85c --- /dev/null +++ b/examples/embedded/src/test/java/org/eclipse/jetty/embedded/TestXml.java @@ -0,0 +1,36 @@ +// +// ======================================================================== +// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd. +// ------------------------------------------------------------------------ +// All rights reserved. This program and the accompanying materials +// are made available under the terms of the Eclipse Public License v1.0 +// and Apache License v2.0 which accompanies this distribution. +// +// The Eclipse Public License is available at +// http://www.eclipse.org/legal/epl-v10.html +// +// The Apache License v2.0 is available at +// http://www.opensource.org/licenses/apache2.0.php +// +// You may elect to redistribute this code under either of these licenses. +// ======================================================================== +// + +package org.eclipse.jetty.embedded; + +import org.eclipse.jetty.xml.XmlConfiguration; + +public class TestXml +{ + public static void main(String[] args) throws Exception + { + System.setProperty("jetty.home","../jetty-distribution/target/distribution"); + XmlConfiguration.main(new String[] + { + "../jetty-jmx/src/main/config/etc/jetty-jmx.xml", + "../jetty-server/src/main/config/etc/jetty.xml", + "../jetty-spdy/spdy-jetty-http-webapp/src/main/config/etc/jetty-spdy.xml" + } + ); + } +} diff --git a/examples/embedded/src/test/resources/dir0/test0.txt b/examples/embedded/src/test/resources/dir0/test0.txt new file mode 100644 index 00000000000..a39c44cc614 --- /dev/null +++ b/examples/embedded/src/test/resources/dir0/test0.txt @@ -0,0 +1 @@ +test0 \ No newline at end of file diff --git a/examples/embedded/src/test/resources/dir1/test1.txt b/examples/embedded/src/test/resources/dir1/test1.txt new file mode 100644 index 00000000000..f079749c42f --- /dev/null +++ b/examples/embedded/src/test/resources/dir1/test1.txt @@ -0,0 +1 @@ +test1 \ No newline at end of file diff --git a/examples/embedded/src/test/resources/realm.properties b/examples/embedded/src/test/resources/realm.properties new file mode 100644 index 00000000000..6cd8ffa4012 --- /dev/null +++ b/examples/embedded/src/test/resources/realm.properties @@ -0,0 +1,22 @@ +# +# This file defines users passwords and roles for a HashUserRealm +# +# The format is +# : [, ...] +# +# Passwords may be clear text, obfuscated or checksummed. The class +# org.eclipse.util.Password should be used to generate obfuscated +# passwords or password checksums +# +# If DIGEST Authentication is used, the password must be in a recoverable +# format, either plain text or OBF:. +# +# if using digest authentication, do not MD5-hash the password +jetty: jetty,user +admin: CRYPT:ad1ks..kc.1Ug,server-administrator,content-administrator,admin,user +other: OBF:1xmk1w261u9r1w1c1xmq,user +plain: plain,user +user: password,user + +# This entry is for digest auth. The credential is a MD5 hash of username:realmname:password +digest: MD5:6e120743ad67abfbc385bc2bb754e297,user