Merge branch 'master' into release-9

This commit is contained in:
Jesse McConnell 2014-08-21 08:42:10 -05:00
commit 8ba0d600b9
55 changed files with 855 additions and 330 deletions

View File

@ -74,12 +74,6 @@
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- JSP Api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
</dependency>
<!-- JSP Impl -->
<dependency>
<groupId>org.mortbay.jasper</groupId>

View File

@ -57,11 +57,6 @@
<artifactId>spdy-http-server</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-plus</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-annotations</artifactId>
@ -80,6 +75,20 @@
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-proxy</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>apache-jsp</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>apache-jstl</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.orbit</groupId>
<artifactId>javax.mail.glassfish</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.toolchain</groupId>

View File

@ -0,0 +1,80 @@
//
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// 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.security.HashLoginService;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class OneWebAppWithJsp
{
public static void main(String[] args) throws Exception
{
// Create a basic jetty server object that will listen on port 8080. Note that if you set this to port 0 then
// a randomly available port will be assigned that you can either look in the logs for the port,
// or programmatically obtain it for use in test cases.
Server server = new Server(8080);
// Setup JMX
MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
// The WebAppContext is the entity that controls the environment in which a web application lives and
// breathes. In this example the context path is being set to "/" so it is suitable for serving root context
// requests and then we see it setting the location of the war. A whole host of other configurations are
// available, ranging from configuring to support annotation scanning in the webapp (through
// PlusConfiguration) to choosing where the webapp will unpack itself.
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("../../jetty-distribution/target/distribution/demo-base/webapps/test.war");
// This webapp will use jsps and jstl. We need to enable the AnnotationConfiguration in order to correctly
// set up the jsp container
org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
// Set the ContainerIncludeJarPattern so that jetty examines these container-path jars for tlds, web-fragments etc.
// If you omit the jar that contains the jstl .tlds, the jsp engine will scan for them instead.
webapp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$");
// A WebAppContext is a ContextHandler as well so it needs to be set to the server so it is aware of where to
// send the appropriate requests.
server.setHandler(webapp);
// Configure a LoginService
// Since this example is for our test webapp, we need to setup a LoginService so this shows how to create a
// very simple hashmap based one. The name of the LoginService needs to correspond to what is configured in
// the webapp's web.xml and since it has a lifecycle of its own we register it as a bean with the Jetty
// server object so it can be started and stopped according to the lifecycle of the server itself.
HashLoginService loginService = new HashLoginService();
loginService.setName("Test Realm");
loginService.setConfig("src/test/resources/realm.properties");
server.addBean(loginService);
// Start things up! By using the server.join() the server thread will join with the current thread.
// See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details.
server.start();
server.join();
}
}

View File

@ -43,7 +43,7 @@ public class ServerWithAnnotations
//Create a WebApp
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("../../tests/test-webapps/test-servlet-spec/test-spec-webapp/target/test-spec-webapp-9.1.0-SNAPSHOT.war");
webapp.setWar("../../jetty-distribution/target/distribution/demo-base/webapps/test-spec.war");
webapp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/javax.servlet-[^/]*\\.jar$|.*/servlet-api-[^/]*\\.jar$");
server.setHandler(webapp);

View File

@ -45,7 +45,7 @@ public class ServerWithJNDI
//Create a WebApp
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("../../tests/test-webapps/test-jndi-webapp/target/test-jndi-webapp-9.0.4-SNAPSHOT.war");
webapp.setWar("../../jetty-distribution/target/distribution/demo-base/webapps/test-jndi.war");
server.setHandler(webapp);
//Register new transaction manager in JNDI

View File

@ -8,3 +8,5 @@ org.eclipse.jetty.SOURCE=false
#org.eclipse.jetty.io.LEVEL=DEBUG
#org.eclipse.jetty.io.ssl.LEVEL=DEBUG
#org.eclipse.jetty.spdy.server.LEVEL=DEBUG
#org.eclipse.jetty.server.LEVEL=DEBUG
#org.eclipse.jetty.servlets.LEVEL=DEBUG

View File

@ -0,0 +1,8 @@
[name]
protonego-boot
[files]
http://central.maven.org/maven2/org/mortbay/jetty/alpn/alpn-boot/7.0.0.v20140317/alpn-boot-7.0.0.v20140317.jar|lib/alpn/alpn-boot-7.0.0.v20140317.jar
[exec]
-Xbootclasspath/p:lib/alpn/alpn-boot-7.0.0.v20140317.jar

View File

@ -0,0 +1,8 @@
[name]
protonego-boot
[files]
http://central.maven.org/maven2/org/mortbay/jetty/alpn/alpn-boot/8.0.0.v20140317/alpn-boot-8.0.0.v20140317.jar|lib/alpn/alpn-boot-8.0.0.v20140317.jar
[exec]
-Xbootclasspath/p:lib/alpn/alpn-boot-8.0.0.v20140317.jar

View File

@ -43,7 +43,7 @@
</goals>
<configuration>
<instructions>
<Import-Package>javax.servlet.*;version="[2.6.0,3.2)",org.objectweb.asm.*;version=4,*</Import-Package>
<Import-Package>javax.servlet.*;version="[2.6.0,3.2)",org.objectweb.asm.*;version=5,*</Import-Package>
<Require-Capability>osgi.serviceloader; filter:="(osgi.serviceloader=javax.servlet.ServletContainerInitializer)";resolution:=optional;cardinality:=multiple, osgi.extender; filter:="(osgi.extender=osgi.serviceloader.processor)"</Require-Capability>
</instructions>
</configuration>

View File

@ -147,6 +147,13 @@ public interface Response
public interface AsyncContentListener extends ResponseListener
{
/**
* Callback method invoked asynchronously when the response content has been received.
*
* @param response the response containing the response line data and the headers
* @param content the content bytes received
* @param callback the callback to call when the content is consumed.
*/
public void onContent(Response response, ByteBuffer content, Callback callback);
}

View File

@ -302,7 +302,7 @@
<configuration>
<includeGroupIds>org.eclipse.jetty</includeGroupIds>
<excludeGroupIds>org.eclipse.jetty.orbit,org.eclipse.jetty.spdy,org.eclipse.jetty.websocket,org.eclipse.jetty.fcgi,org.eclipse.jetty.toolchain,org.apache.taglibs</excludeGroupIds>
<excludeArtifactIds>jetty-all,jetty-jsp,apache-jsp,jetty-start,jetty-monitor,jetty-spring</excludeArtifactIds>
<excludeArtifactIds>jetty-all,jetty-jsp,apache-jsp,apache-jstl,jetty-start,jetty-monitor,jetty-spring</excludeArtifactIds>
<includeTypes>jar</includeTypes>
<outputDirectory>${assembly-directory}/lib</outputDirectory>
</configuration>
@ -477,8 +477,8 @@
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeGroupIds>org.eclipse.jetty,org.eclipse.jetty.toolchain,javax.servlet.jsp,org.mortbay.jasper,org.mortbay.jasper,org.eclipse.jetty.orbit</includeGroupIds>
<includeArtifactIds>apache-jsp,javax.servlet.jsp-api,apache-el,org.eclipse.jdt.core</includeArtifactIds>
<includeGroupIds>org.eclipse.jetty,org.eclipse.jetty.toolchain,org.mortbay.jasper,org.eclipse.jetty.orbit</includeGroupIds>
<includeArtifactIds>apache-jsp,apache-el,org.eclipse.jdt.core</includeArtifactIds>
<includeTypes>jar</includeTypes>
<prependGroupId>true</prependGroupId>
<outputDirectory>${assembly-directory}/lib/apache-jsp</outputDirectory>

View File

@ -4,6 +4,7 @@
[depend]
servlet
annotations
jsp-impl/${jsp-impl}-jsp
[ini-template]

View File

@ -697,7 +697,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
contentLatch.set(new CountDownLatch(1));
callback.succeeded();
Assert.assertTrue(completeLatch.await(555, TimeUnit.SECONDS));
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
Assert.assertEquals(2, contentCount.get());
}
}

View File

@ -168,5 +168,11 @@ public interface HttpContent
{
_resource.close();
}
@Override
public String toString()
{
return String.format("%s@%x{r=%s}",this.getClass().getSimpleName(),hashCode(),_resource);
}
}
}

View File

@ -338,18 +338,15 @@ abstract public class WriteFlusher
if (DEBUG)
LOG.debug("flushed {}", flushed);
// Are we complete?
for (ByteBuffer b : buffers)
// if we are incomplete?
if (!flushed)
{
if (!flushed||BufferUtil.hasContent(b))
{
PendingState pending=new PendingState(buffers, callback);
if (updateState(__WRITING,pending))
onIncompleteFlushed();
else
fail(pending);
return;
}
PendingState pending=new PendingState(buffers, callback);
if (updateState(__WRITING,pending))
onIncompleteFlushed();
else
fail(pending);
return;
}
// If updateState didn't succeed, we don't care as our buffers have been written
@ -403,17 +400,14 @@ abstract public class WriteFlusher
if (DEBUG)
LOG.debug("flushed {}", flushed);
// Are we complete?
for (ByteBuffer b : buffers)
// if we are incomplete?
if (!flushed)
{
if (!flushed || BufferUtil.hasContent(b))
{
if (updateState(__COMPLETING,pending))
onIncompleteFlushed();
else
fail(pending);
return;
}
if (updateState(__COMPLETING,pending))
onIncompleteFlushed();
else
fail(pending);
return;
}
// If updateState didn't succeed, we don't care as our buffers have been written

View File

@ -773,7 +773,7 @@ public class SslConnection extends AbstractConnection
{
if (DEBUG)
LOG.debug("{} renegotiation denied", SslConnection.this);
shutdownOutput();
getEndPoint().shutdownOutput();
return allConsumed;
}

View File

@ -211,21 +211,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo
*/
protected boolean dumpOnStart;
/**
* <p>
* Determines whether or not the server blocks when started. The default
* behavior (daemon = false) will cause the server to pause other processes
* while it continues to handle web requests. This is useful when starting the
* server with the intent to work with it interactively.
* </p><p>
* Often, it is desirable to let the server start and continue running subsequent
* processes in an automated build environment. This can be facilitated by setting
* daemon to true.
* </p>
*
* @parameter expression="${jetty.daemon}" default-value="false"
*/
protected boolean daemon;
/**
@ -319,9 +305,20 @@ public abstract class AbstractJettyMojo extends AbstractMojo
protected Thread consoleScanner;
/**
* <p>
* Determines whether or not the server blocks when started. The default
* behavior (false) will cause the server to pause other processes
* while it continues to handle web requests. This is useful when starting the
* server with the intent to work with it interactively. This is the
* behaviour of the jetty:run, jetty:run-war, jetty:run-war-exploded goals.
* </p><p>
* If true, the server will not block the execution of subsequent code. This
* is the behaviour of the jetty:start and default behaviour of the jetty:deploy goals.
* </p>
*/
protected boolean nonblocking = false;
public abstract void restartWebApp(boolean reconfigureScanner) throws Exception;
@ -472,14 +469,8 @@ public abstract class AbstractJettyMojo extends AbstractMojo
try
{
getLog().debug("Starting Jetty Server ...");
if(stopPort>0 && stopKey!=null)
{
ShutdownMonitor monitor = ShutdownMonitor.getInstance();
monitor.setPort(stopPort);
monitor.setKey(stopKey);
monitor.setExitVm(!daemon);
}
configureMonitor();
printSystemProperties();
@ -558,7 +549,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo
startConsoleScanner();
// keep the thread going if not in daemon mode
if (!daemon )
if (!nonblocking )
{
server.join();
}
@ -569,7 +560,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo
}
finally
{
if (!daemon )
if (!nonblocking )
{
getLog().info("Jetty server exiting.");
}
@ -577,6 +568,16 @@ public abstract class AbstractJettyMojo extends AbstractMojo
}
public void configureMonitor()
{
if(stopPort>0 && stopKey!=null)
{
ShutdownMonitor monitor = ShutdownMonitor.getInstance();
monitor.setPort(stopPort);
monitor.setKey(stopKey);
monitor.setExitVm(!nonblocking);
}
}
/**

View File

@ -18,6 +18,11 @@
package org.eclipse.jetty.maven.plugin;
import java.io.File;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* <p>
* This goal is used to run Jetty with a pre-assembled war.
@ -27,7 +32,7 @@ package org.eclipse.jetty.maven.plugin;
* However, it doesn't assume that the current artifact is a
* webapp and doesn't try to assemble it into a war before its execution.
* So using it makes sense only when used in conjunction with the
* <a href="run-war-mojo.html#webApp">webApp</a> configuration parameter pointing to a pre-built WAR.
* <a href="run-war-mojo.html#webApp">war</a> configuration parameter pointing to a pre-built WAR.
* </p>
* <p>
* This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested
@ -42,4 +47,34 @@ package org.eclipse.jetty.maven.plugin;
*/
public class JettyDeployWar extends JettyRunWarMojo
{
/**
* If true, the plugin should continue and not block. Otherwise the
* plugin will block further execution and you will need to use
* cntrl-c to stop it.
*
*
* @parameter default-value="true"
*/
protected boolean daemon = true;
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
nonblocking = daemon;
super.execute();
}
@Override
public void finishConfigurationBeforeStart() throws Exception
{
//only stop the server at shutdown if we are blocking
server.setStopAtShutdown(!nonblocking);
super.finishConfigurationBeforeStart();
}
}

View File

@ -290,6 +290,16 @@ public class JettyRunMojo extends AbstractJettyMojo
@Override
public void finishConfigurationBeforeStart() throws Exception
{
server.setStopAtShutdown(true); //as we will normally be stopped with a cntrl-c, ensure server stopped
super.finishConfigurationBeforeStart();
}
/**
* @see org.eclipse.jetty.maven.plugin.AbstractJettyMojo#configureWebApplication()
*/

View File

@ -32,17 +32,13 @@ import org.eclipse.jetty.util.Scanner;
* This goal is used to assemble your webapp into an exploded war and automatically deploy it to Jetty.
* </p>
* <p>
* Once invoked, the plugin can be configured to run continuously, scanning for changes in the pom.xml and
* Once invoked, the plugin runs continuously, and can be configured to scan for changes in the pom.xml and
* to WEB-INF/web.xml, WEB-INF/classes or WEB-INF/lib and hot redeploy when a change is detected.
* </p>
* <p>
* You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration.
* This can be used, for example, to deploy a static webapp that is not part of your maven build.
* </p>
* <p>
* There is a <a href="run-exploded-mojo.html">reference guide</a> to the configuration parameters for this plugin, and more detailed information
* with examples in the <a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin">Configuration Guide</a>.
* </p>
*
*@goal run-exploded
*@requiresDependencyResolution compile+runtime
@ -56,7 +52,7 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo
/**
* The location of the war file.
*
* @parameter alias="webApp" expression="${project.build.directory}/${project.build.finalName}"
* @parameter expression="${project.build.directory}/${project.build.finalName}"
* @required
*/
private File war;
@ -74,7 +70,14 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo
}
@Override
public void finishConfigurationBeforeStart() throws Exception
{
server.setStopAtShutdown(true); //as we will normally be stopped with a cntrl-c, ensure server stopped
super.finishConfigurationBeforeStart();
}
/**
*

View File

@ -31,18 +31,13 @@ import org.eclipse.jetty.util.Scanner;
* This goal is used to assemble your webapp into a war and automatically deploy it to Jetty.
* </p>
* <p>
* Once invoked, the plugin can be configured to run continuously, scanning for changes in the project and to the
* war file and automatically performing a
* hot redeploy when necessary.
* Once invoked, the plugin runs continuously and can be configured to scan for changes in the project and to the
* war file and automatically perform a hot redeploy when necessary.
* </p>
* <p>
* You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration.
* This can be used, for example, to deploy a static webapp that is not part of your maven build.
* </p>
* <p>
* There is a <a href="run-war-mojo.html">reference guide</a> to the configuration parameters for this plugin, and more detailed information
* with examples in the <a href="http://docs.codehaus.org/display/JETTY/Maven+Jetty+Plugin/">Configuration Guide</a>.
* </p>
*
* @goal run-war
* @requiresDependencyResolution compile+runtime
@ -70,6 +65,13 @@ public class JettyRunWarMojo extends AbstractJettyMojo
}
@Override
public void finishConfigurationBeforeStart() throws Exception
{
server.setStopAtShutdown(true); //as we will normally be stopped with a cntrl-c, ensure server stopped
super.finishConfigurationBeforeStart();
}
public void configureWebApplication () throws Exception

View File

@ -43,9 +43,7 @@ import org.eclipse.jetty.xml.XmlConfiguration;
*
*/
public class JettyServer extends org.eclipse.jetty.server.Server
{
public static final JettyServer __instance = new JettyServer();
{
private RequestLog requestLog;
private ContextHandlerCollection contexts;
@ -57,7 +55,6 @@ public class JettyServer extends org.eclipse.jetty.server.Server
public JettyServer()
{
super();
setStopAtShutdown(true);
//make sure Jetty does not use URLConnection caches with the plugin
Resource.setDefaultUseCaches(false);
}

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.maven.plugin;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* <p>
@ -37,4 +40,20 @@ package org.eclipse.jetty.maven.plugin;
*/
public class JettyStartMojo extends JettyRunMojo
{
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
nonblocking = true; //ensure that starting jetty won't hold up the thread
super.execute();
}
@Override
public void finishConfigurationBeforeStart() throws Exception
{
super.finishConfigurationBeforeStart();
server.setStopAtShutdown(false); //as we will normally be stopped with a cntrl-c, ensure server stopped
}
}

View File

@ -63,6 +63,10 @@ public class JettyStopMojo extends AbstractMojo
*/
protected int stopWait;
public void execute() throws MojoExecutionException, MojoFailureException
{
@ -71,13 +75,17 @@ public class JettyStopMojo extends AbstractMojo
if (stopKey == null)
throw new MojoExecutionException("Please specify a valid stopKey");
//Ensure jetty Server instance stops. Whether or not the remote process
//also stops depends whether or not it was started with ShutdownMonitor.exitVm=true
String command = "forcestop";
try
{
Socket s=new Socket(InetAddress.getByName("127.0.0.1"),stopPort);
s.setSoLinger(false, 0);
OutputStream out=s.getOutputStream();
out.write((stopKey+"\r\nstop\r\n").getBytes());
out.write((stopKey+"\r\n"+command+"\r\n").getBytes());
out.flush();
if (stopWait > 0)

View File

@ -178,7 +178,6 @@ public class Starter
this.server.addWebApplication(webApp);
System.err.println("STOP PORT="+stopPort+", STOP KEY="+stopKey);
if(stopPort>0 && stopKey!=null)
{
ShutdownMonitor monitor = ShutdownMonitor.getInstance();

View File

@ -176,71 +176,63 @@ public abstract class NoSqlSessionManager extends AbstractSessionManager impleme
@Override
protected boolean removeSession(String idInCluster)
{
synchronized (this)
NoSqlSession session = _sessions.remove(idInCluster);
try
{
NoSqlSession session = _sessions.remove(idInCluster);
try
if (session != null)
{
if (session != null)
{
return remove(session);
}
return remove(session);
}
catch (Exception e)
{
__log.warn("Problem deleting session {}", idInCluster,e);
}
return session != null;
}
catch (Exception e)
{
__log.warn("Problem deleting session {}", idInCluster,e);
}
return session != null;
}
/* ------------------------------------------------------------ */
protected void expire( String idInCluster )
{
synchronized (this)
{
//get the session from memory
NoSqlSession session = _sessions.get(idInCluster);
//get the session from memory
NoSqlSession session = _sessions.get(idInCluster);
try
try
{
if (session == null)
{
if (session == null)
{
//we need to expire the session with its listeners, so load it
session = loadSession(idInCluster);
}
if (session != null)
session.timeout();
}
catch (Exception e)
{
__log.warn("Problem expiring session {}", idInCluster,e);
//we need to expire the session with its listeners, so load it
session = loadSession(idInCluster);
}
if (session != null)
session.timeout();
}
catch (Exception e)
{
__log.warn("Problem expiring session {}", idInCluster,e);
}
}
public void invalidateSession (String idInCluster)
{
synchronized (this)
NoSqlSession session = _sessions.get(idInCluster);
try
{
NoSqlSession session = _sessions.get(idInCluster);
try
__log.debug("invalidating session {}", idInCluster);
if (session != null)
{
__log.debug("invalidating session {}", idInCluster);
if (session != null)
{
session.invalidate();
}
}
catch (Exception e)
{
__log.warn("Problem invalidating session {}", idInCluster,e);
session.invalidate();
}
}
catch (Exception e)
{
__log.warn("Problem invalidating session {}", idInCluster,e);
}
}

View File

@ -23,9 +23,6 @@ import java.net.URI;
import java.net.URL;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
@ -35,7 +32,6 @@ import org.eclipse.jetty.annotations.ClassNameResolver;
import org.eclipse.jetty.osgi.boot.utils.BundleFileLocatorHelper;
import org.eclipse.jetty.util.ConcurrentHashSet;
import org.eclipse.jetty.util.resource.Resource;
import org.objectweb.asm.Opcodes;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
@ -51,13 +47,6 @@ public class AnnotationParser extends org.eclipse.jetty.annotations.AnnotationPa
private ConcurrentHashMap<Resource, Bundle> _resourceToBundle = new ConcurrentHashMap<Resource, Bundle>();
private ConcurrentHashMap<Bundle,URI> _bundleToUri = new ConcurrentHashMap<Bundle, URI>();
static
{
//As of jetty 9.2.0, the impl of asm visitor classes is compatible with both asm4 and asm5.
//We need to use asm4 with osgi, because we need to use aries spifly to support annotations,
//and currently this only supports asm4. Therefore, we set the asm api version to be 4 for osgi.
ASM_OPCODE_VERSION = Opcodes.ASM4;
}
/**
* Keep track of a jetty URI Resource and its associated OSGi bundle.
@ -212,5 +201,4 @@ public class AnnotationParser extends org.eclipse.jetty.annotations.AnnotationPa
scanClass(handlers, getResource(bundle), classUrl.openStream());
}
}
}

View File

@ -164,24 +164,10 @@
<dependency>
<groupId>org.apache.aries.spifly</groupId>
<artifactId>org.apache.aries.spifly.dynamic.bundle</artifactId>
<version>1.0.0</version>
<version>1.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-commons</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-tree</artifactId>
<version>4.1</version>
</dependency>
<!-- Jetty Deps -->
@ -189,20 +175,6 @@
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-annotations</artifactId>
<scope>runtime</scope>
<exclusions>
<exclusion>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
</exclusion>
<exclusion>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-commons</artifactId>
</exclusion>
<exclusion>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-tree</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
@ -362,31 +334,6 @@
</dependency>
<!-- Eclipse OSGi Deps -->
<!--
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
<scope>runtime</scope>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.eclipse.equinox.http</groupId>
<artifactId>servlet</artifactId>
<scope>runtime</scope>
</dependency>
-->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>test-jetty-webapp</artifactId>

View File

@ -31,13 +31,12 @@ import javax.inject.Inject;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.MavenUtils;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.options.MavenUrlReference.VersionResolver;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
@ -64,7 +63,7 @@ public class TestJettyOSGiBootCore
options.addAll(Arrays.asList(options(systemProperty("pax.exam.logging").value("none"))));
options.addAll(Arrays.asList(options(systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value(LOG_LEVEL))));
options.addAll(Arrays.asList(options(systemProperty("org.eclipse.jetty.LEVEL").value(LOG_LEVEL))));
options.addAll(Arrays.asList(options(systemProperty("org.eclipse.jetty.annotations.LEVEL").value("DEBUG"))));
return options.toArray(new Option[options.size()]);
}
@ -82,20 +81,12 @@ public class TestJettyOSGiBootCore
public static List<Option> coreJettyDependencies()
{
List<Option> res = new ArrayList<Option>();
String jdk = System.getProperty("java.version");
int firstdot = jdk.indexOf(".");
jdk = jdk.substring(0,firstdot+2);
double version = Double.parseDouble(jdk);
if (version < 1.8)
{
res.add(mavenBundle().groupId( "org.ow2.asm" ).artifactId( "asm" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.ow2.asm" ).artifactId( "asm-commons" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.ow2.asm" ).artifactId( "asm-tree" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.apache.aries" ).artifactId( "org.apache.aries.util" ).version("1.0.0").start());
res.add(mavenBundle().groupId( "org.apache.aries.spifly" ).artifactId( "org.apache.aries.spifly.dynamic.bundle" ).version("1.0.0").start());
}
res.add(mavenBundle().groupId( "org.ow2.asm" ).artifactId( "asm" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.ow2.asm" ).artifactId( "asm-commons" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.ow2.asm" ).artifactId( "asm-tree" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.apache.aries" ).artifactId( "org.apache.aries.util" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.apache.aries.spifly" ).artifactId( "org.apache.aries.spifly.dynamic.bundle" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "javax.servlet" ).artifactId( "javax.servlet-api" ).versionAsInProject().noStart());
res.add(mavenBundle().groupId( "javax.annotation" ).artifactId( "javax.annotation-api" ).versionAsInProject().noStart());
@ -119,10 +110,7 @@ public class TestJettyOSGiBootCore
res.add(mavenBundle().groupId( "org.eclipse.jetty" ).artifactId( "jetty-client" ).versionAsInProject().noStart());
res.add(mavenBundle().groupId( "org.eclipse.jetty" ).artifactId( "jetty-jndi" ).versionAsInProject().noStart());
res.add(mavenBundle().groupId( "org.eclipse.jetty" ).artifactId( "jetty-plus" ).versionAsInProject().noStart());
if (version < 1.8)
{
res.add(mavenBundle().groupId( "org.eclipse.jetty" ).artifactId( "jetty-annotations" ).versionAsInProject().start());
}
res.add(mavenBundle().groupId( "org.eclipse.jetty" ).artifactId( "jetty-annotations" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.eclipse.jetty.websocket" ).artifactId( "websocket-api" ).versionAsInProject().noStart());
res.add(mavenBundle().groupId( "org.eclipse.jetty.websocket" ).artifactId( "websocket-common" ).versionAsInProject().noStart());
res.add(mavenBundle().groupId( "org.eclipse.jetty.websocket" ).artifactId( "websocket-servlet" ).versionAsInProject().noStart());

View File

@ -85,7 +85,7 @@ public class AsyncProxyServlet extends ProxyServlet
catch (Throwable x)
{
callback.failed(x);
onResponseFailure(request, response, proxyResponse, x);
proxyResponse.abort(x);
}
}
@ -279,8 +279,7 @@ public class AsyncProxyServlet extends ProxyServlet
@Override
public void onError(Throwable failure)
{
HttpServletResponse response = (HttpServletResponse)request.getAsyncContext().getResponse();
onResponseFailure(request, response, proxyResponse, failure);
proxyResponse.abort(failure);
}
}

View File

@ -354,7 +354,7 @@ public class ProxyServletTest
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.method(HttpMethod.POST)
.content(new BytesContentProvider(content))
.timeout(555, TimeUnit.SECONDS)
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());

View File

@ -49,6 +49,7 @@ import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.server.HttpChannelState.Action;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.SharedBlockingCallback.Blocker;
import org.eclipse.jetty.util.URIUtil;
@ -360,7 +361,10 @@ public class HttpChannel<T> implements HttpParser.RequestHandler<T>, Runnable, H
else
{
error=true;
throw e;
LOG.warn(String.valueOf(_uri), e);
_state.error(e);
_request.setHandled(true);
handleException(e);
}
}
catch (Exception e)
@ -484,10 +488,11 @@ public class HttpChannel<T> implements HttpParser.RequestHandler<T>, Runnable, H
@Override
public String toString()
{
return String.format("%s@%x{r=%s,a=%s,uri=%s}",
return String.format("%s@%x{r=%s,c=%b,a=%s,uri=%s}",
getClass().getSimpleName(),
hashCode(),
_requests,
_committed.get(),
_state.getState(),
_state.getState()==HttpChannelState.State.IDLE?"-":_request.getRequestURI()
);
@ -724,7 +729,6 @@ public class HttpChannel<T> implements HttpParser.RequestHandler<T>, Runnable, H
protected boolean sendResponse(ResponseInfo info, ByteBuffer content, boolean complete, final Callback callback)
{
// TODO check that complete only set true once by changing _committed to AtomicRef<Enum>
boolean committing = _committed.compareAndSet(false, true);
if (committing)
{
@ -732,7 +736,7 @@ public class HttpChannel<T> implements HttpParser.RequestHandler<T>, Runnable, H
if (info==null)
info = _response.newResponseInfo();
// wrap callback to process 100 or 500 responses
// wrap callback to process 100 responses
final int status=info.getStatus();
final Callback committed = (status<200&&status>=100)?new Commit100Callback(callback):new CommitCallback(callback);
@ -864,8 +868,10 @@ public class HttpChannel<T> implements HttpParser.RequestHandler<T>, Runnable, H
@Override
public void succeeded()
{
_committed.set(false);
super.succeeded();
if (_committed.compareAndSet(true, false))
super.succeeded();
else
super.failed(new IllegalStateException());
}
}

View File

@ -444,15 +444,17 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
// then we can't be persistent
_generator.setPersistent(false);
_sendCallback.reset(info,content,lastContent,callback);
_sendCallback.iterate();
if(_sendCallback.reset(info,content,lastContent,callback))
_sendCallback.iterate();
}
@Override
public void send(ByteBuffer content, boolean lastContent, Callback callback)
{
_sendCallback.reset(null,content,lastContent,callback);
_sendCallback.iterate();
if (!lastContent && BufferUtil.isEmpty(content))
callback.succeeded();
else if (_sendCallback.reset(null,content,lastContent,callback))
_sendCallback.iterate();
}
protected class HttpChannelOverHttp extends HttpChannel<ByteBuffer>
@ -565,7 +567,7 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
super(true);
}
private void reset(ResponseInfo info, ByteBuffer content, boolean last, Callback callback)
private boolean reset(ResponseInfo info, ByteBuffer content, boolean last, Callback callback)
{
if (reset())
{
@ -575,15 +577,14 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
_callback = callback;
_header = null;
_shutdownOut = false;
return true;
}
else if (isClosed())
{
if (isClosed())
callback.failed(new EofException());
}
else
{
callback.failed(new WritePendingException());
}
return false;
}
@Override
@ -651,7 +652,9 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
getEndPoint().write(this, _content);
}
else
continue;
{
succeeded(); // nothing to write
}
return Action.SCHEDULED;
}
case SHUTDOWN_OUT:
@ -661,7 +664,6 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
}
case DONE:
{
releaseHeader();
return Action.SUCCEEDED;
}
case CONTINUE:

View File

@ -248,6 +248,15 @@ public abstract class HttpInput<T> extends ServletInputStream implements Runnabl
_channelState.onReadPossible();
}
public boolean isEarlyEOF()
{
synchronized (lock())
{
return _contentState==EARLY_EOF;
}
}
/**
* This method should be called to signal that all the expected
* content arrived.
@ -317,6 +326,7 @@ public abstract class HttpInput<T> extends ServletInputStream implements Runnabl
return _contentState.isEOF();
}
}
@Override
public boolean isReady()
@ -473,7 +483,7 @@ public abstract class HttpInput<T> extends ServletInputStream implements Runnabl
@Override
public int noContent() throws IOException
{
throw new EofException();
throw new EofException("Early EOF");
}
@Override

View File

@ -643,6 +643,9 @@ public class HttpOutput extends ServletOutputStream implements Runnable
if (buffer!=null)
{
if (LOG.isDebugEnabled())
LOG.debug("sendContent({}=={},{},direct={})",httpContent,BufferUtil.toDetailString(buffer),callback,_channel.useDirectBuffers());
sendContent(buffer,callback);
return;
}
@ -650,6 +653,8 @@ public class HttpOutput extends ServletOutputStream implements Runnable
ReadableByteChannel rbc=httpContent.getReadableByteChannel();
if (rbc!=null)
{
if (LOG.isDebugEnabled())
LOG.debug("sendContent({}=={},{},direct={})",httpContent,rbc,callback,_channel.useDirectBuffers());
// Close of the rbc is done by the async sendContent
sendContent(rbc,callback);
return;
@ -658,6 +663,8 @@ public class HttpOutput extends ServletOutputStream implements Runnable
InputStream in = httpContent.getInputStream();
if ( in!=null )
{
if (LOG.isDebugEnabled())
LOG.debug("sendContent({}=={},{},direct={})",httpContent,in,callback,_channel.useDirectBuffers());
sendContent(in,callback);
return;
}

View File

@ -504,7 +504,7 @@ public class ResourceCache
@Override
public String toString()
{
return String.format("%s %s %d %s %s",_resource,_resource.exists(),_resource.lastModified(),_contentType,_lastModifiedBytes);
return String.format("CachedContent@%x{r=%s,e=%b,lm=%d,ct=%s}",hashCode(),_resource,_resource.exists(),BufferUtil.toString(_lastModifiedBytes),_contentType);
}
}
}

View File

@ -18,7 +18,6 @@
package org.eclipse.jetty.server;
import java.awt.geom.PathIterator;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
@ -54,7 +53,6 @@ import org.eclipse.jetty.util.AttributesMap;
import org.eclipse.jetty.util.Jetty;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.UrlEncoded;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.Name;
@ -145,7 +143,8 @@ public class Server extends HandlerWrapper implements Attributes
{
return _stopAtShutdown;
}
/* ------------------------------------------------------------ */
/**
* Set a graceful stop time.
@ -313,11 +312,16 @@ public class Server extends HandlerWrapper implements Attributes
@Override
protected void doStart() throws Exception
{
//If the Server should be stopped when the jvm exits, register
//with the shutdown handler thread.
if (getStopAtShutdown())
{
ShutdownThread.register(this);
}
//Register the Server with the handler thread for receiving
//remote stop commands
ShutdownMonitor.register(this);
//Start a thread waiting to receive "stop" commands.
ShutdownMonitor.getInstance().start(); // initialize
LOG.info("jetty-" + getVersion());
@ -455,6 +459,11 @@ public class Server extends HandlerWrapper implements Attributes
if (getStopAtShutdown())
ShutdownThread.deregister(this);
//Unregister the Server with the handler thread for receiving
//remote stop commands as we are stopped already
ShutdownMonitor.deregister(this);
mex.ifExceptionThrow();

View File

@ -26,8 +26,15 @@ import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import org.eclipse.jetty.util.component.Destroyable;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.thread.ShutdownThread;
/**
@ -42,6 +49,8 @@ import org.eclipse.jetty.util.thread.ShutdownThread;
*/
public class ShutdownMonitor
{
private final Set<LifeCycle> _lifeCycles = new CopyOnWriteArraySet<LifeCycle>();
// Implementation of safe lazy init, using Initialization on Demand Holder technique.
static class Holder
{
@ -52,6 +61,26 @@ public class ShutdownMonitor
{
return Holder.instance;
}
/* ------------------------------------------------------------ */
public static synchronized void register(LifeCycle... lifeCycles)
{
getInstance()._lifeCycles.addAll(Arrays.asList(lifeCycles));
}
/* ------------------------------------------------------------ */
public static synchronized void deregister(LifeCycle lifeCycle)
{
getInstance()._lifeCycles.remove(lifeCycle);
}
/* ------------------------------------------------------------ */
public static synchronized boolean isRegistered(LifeCycle lifeCycle)
{
return getInstance()._lifeCycles.contains(lifeCycle);
}
/**
* ShutdownMonitorRunnable
@ -95,29 +124,38 @@ public class ShutdownMonitor
String cmd = lin.readLine();
debug("command=%s",cmd);
if ("stop".equals(cmd))
if ("stop".equalsIgnoreCase(cmd)) //historic, for backward compatibility
{
// Graceful Shutdown
debug("Issuing graceful shutdown..");
ShutdownThread.getInstance().run();
//Stop accepting any more
close(serverSocket);
serverSocket = null;
//Stop the lifecycles, only if they are registered with the ShutdownThread, only destroying if vm is exiting
debug("Issuing stop...");
//Shutdown input from client
shutdownInput(socket);
for (LifeCycle l:_lifeCycles)
{
try
{
if (l.isStarted() && ShutdownThread.isRegistered(l))
{
l.stop();
}
if ((l instanceof Destroyable) && exitVm)
((Destroyable)l).destroy();
}
catch (Exception e)
{
debug(e);
}
}
//Stop accepting any more commands
stopInput(socket);
// Reply to client
debug("Informing client that we are stopped.");
out.write("Stopped\r\n".getBytes(StandardCharsets.UTF_8));
out.flush();
informClient(out, "Stopped\r\n");
// Shutdown Monitor
socket.shutdownOutput();
close(socket);
socket = null;
debug("Shutting down monitor");
//Stop the output and close the monitor socket
stopOutput(socket);
if (exitVm)
{
@ -126,11 +164,59 @@ public class ShutdownMonitor
System.exit(0);
}
}
else if ("status".equals(cmd))
else if ("forcestop".equalsIgnoreCase(cmd))
{
debug("Issuing force stop...");
//Ensure that objects are stopped, destroyed only if vm is forcibly exiting
stopLifeCycles(exitVm);
//Stop accepting any more commands
stopInput(socket);
// Reply to client
debug("Informing client that we are stopped.");
informClient(out, "Stopped\r\n");
//Stop the output and close the monitor socket
stopOutput(socket);
//Honour any pre-setup config to stop the jvm when this command is given
if (exitVm)
{
// Kill JVM
debug("Killing JVM");
System.exit(0);
}
}
else if ("stopexit".equalsIgnoreCase(cmd))
{
debug("Issuing stop and exit...");
//Make sure that objects registered with the shutdown thread will be stopped
stopLifeCycles(true);
//Stop accepting any more input
stopInput(socket);
// Reply to client
debug("Informing client that we are stopped.");
informClient(out, "Stopped\r\n");
//Stop the output and close the monitor socket
stopOutput(socket);
debug("Killing JVM");
System.exit(0);
}
else if ("exit".equalsIgnoreCase(cmd))
{
debug("Killing JVM");
System.exit(0);
}
else if ("status".equalsIgnoreCase(cmd))
{
// Reply to client
out.write("OK\r\n".getBytes(StandardCharsets.UTF_8));
out.flush();
informClient(out, "OK\r\n");
}
}
catch (Exception e)
@ -146,6 +232,57 @@ public class ShutdownMonitor
}
}
public void stopInput (Socket socket)
{
//Stop accepting any more input
close(serverSocket);
serverSocket = null;
//Shutdown input from client
shutdownInput(socket);
}
public void stopOutput (Socket socket) throws IOException
{
socket.shutdownOutput();
close(socket);
socket = null;
debug("Shutting down monitor");
serverSocket = null;
}
public void informClient (OutputStream out, String message) throws IOException
{
out.write(message.getBytes(StandardCharsets.UTF_8));
out.flush();
}
/**
* Stop the registered lifecycles, optionally
* calling destroy on them.
*
* @param destroy
*/
public void stopLifeCycles (boolean destroy)
{
for (LifeCycle l:_lifeCycles)
{
try
{
if (l.isStarted())
{
l.stop();
}
if ((l instanceof Destroyable) && destroy)
((Destroyable)l).destroy();
}
catch (Exception e)
{
debug(e);
}
}
}
public void startListenSocket()
{
if (port < 0)
@ -309,6 +446,9 @@ public class ShutdownMonitor
this.DEBUG = flag;
}
/**
* @param exitVm
*/
public void setExitVm(boolean exitVm)
{
synchronized (this)

View File

@ -66,6 +66,9 @@ public class RequestLogHandler extends HandlerWrapper
@Override
public void onError(AsyncEvent event) throws IOException
{
HttpServletResponse response = (HttpServletResponse)event.getAsyncContext().getResponse();
if (!response.isCommitted())
response.setStatus(500);
}
@ -91,6 +94,12 @@ public class RequestLogHandler extends HandlerWrapper
{
super.handle(target, baseRequest, request, response);
}
catch(Error|IOException|ServletException|RuntimeException e)
{
if (!response.isCommitted() && !baseRequest.getHttpChannelState().isAsync())
response.setStatus(500);
throw e;
}
finally
{
if (_requestLog != null && baseRequest.getDispatcherType().equals(DispatcherType.REQUEST))

View File

@ -30,6 +30,7 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ -41,6 +42,7 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -49,6 +51,7 @@ import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
/**
@ -69,7 +72,7 @@ public class HttpConnectionTest
http.getHttpConfiguration().setResponseHeaderSize(1024);
connector = new LocalConnector(server,http,null);
connector.setIdleTimeout(500);
connector.setIdleTimeout(5000);
server.addConnector(connector);
server.setHandler(new DumpHandler());
ErrorHandler eh=new ErrorHandler();
@ -324,6 +327,31 @@ public class HttpConnectionTest
offset = checkContains(response,offset,"/R1");
offset = checkContains(response,offset,"12345");
}
@Test
public void testEmptyFlush() throws Exception
{
server.stop();
server.setHandler(new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setStatus(200);
OutputStream out =response.getOutputStream();
out.flush();
out.flush();
}
});
server.start();
String response=connector.getResponses("GET / HTTP/1.1\n"+
"Host: localhost\n"+
"Connection: close\n"+
"\n");
assertThat(response, Matchers.containsString("200 OK"));
}
@Test
public void testCharset() throws Exception
@ -431,6 +459,7 @@ public class HttpConnectionTest
@Test
public void testUnconsumedTimeout() throws Exception
{
connector.setIdleTimeout(500);
String response=null;
String requests=null;
int offset=0;

View File

@ -28,6 +28,7 @@ import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.util.thread.ShutdownThread;
import org.junit.Test;
/**
@ -35,8 +36,34 @@ import org.junit.Test;
*/
public class ShutdownMonitorTest
{
public class TestableServer extends Server
{
boolean destroyed = false;
boolean stopped = false;
@Override
protected void doStop() throws Exception
{
stopped = true;
super.doStop();
}
@Override
public void destroy()
{
destroyed = true;
super.destroy();
}
@Override
protected void doStart() throws Exception
{
stopped = false;
destroyed = false;
super.doStart();
}
}
@Test
public void testShutdown() throws Exception
public void testShutdownMonitor() throws Exception
{
// test port and key assignment
ShutdownMonitor.getInstance().setPort(0);
@ -48,7 +75,7 @@ public class ShutdownMonitorTest
// try starting a 2nd time (should be ignored)
ShutdownMonitor.getInstance().start();
stop(port,key,true);
stop("stop", port,key,true);
assertTrue(!ShutdownMonitor.getInstance().isAlive());
// should be able to change port and key because it is stopped
@ -60,19 +87,113 @@ public class ShutdownMonitorTest
port = ShutdownMonitor.getInstance().getPort();
assertTrue(ShutdownMonitor.getInstance().isAlive());
stop(port,key,true);
stop("stop", port,key,true);
assertTrue(!ShutdownMonitor.getInstance().isAlive());
}
public void stop(int port, String key, boolean check) throws Exception
@Test
public void testForceStopCommand() throws Exception
{
System.out.printf("Attempting stop to localhost:%d (%b)%n",port,check);
//create a testable Server with stop(), destroy() overridden to instrument
//start server
//call "forcestop" and check that server stopped but not destroyed
// test port and key assignment
System.setProperty("DEBUG", "true");
ShutdownMonitor.getInstance().setPort(0);
TestableServer server = new TestableServer();
server.start();
//shouldn't be registered for shutdown on jvm
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
String key = ShutdownMonitor.getInstance().getKey();
int port = ShutdownMonitor.getInstance().getPort();
stop("forcestop", port,key,true);
assertTrue(!ShutdownMonitor.getInstance().isAlive());
assertTrue(server.stopped);
assertTrue(!server.destroyed);
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(!ShutdownMonitor.isRegistered(server));
}
@Test
public void testOldStopCommandWithStopOnShutdownTrue() throws Exception
{
//create a testable Server with stop(), destroy() overridden to instrument
//call server.setStopAtShudown(true);
//start server
//call "stop" and check that server stopped but not destroyed
//stop server
//call server.setStopAtShutdown(false);
//start server
//call "stop" and check that the server is not stopped and not destroyed
System.setProperty("DEBUG", "true");
ShutdownMonitor.getInstance().setExitVm(false);
ShutdownMonitor.getInstance().setPort(0);
TestableServer server = new TestableServer();
server.setStopAtShutdown(true);
server.start();
//should be registered for shutdown on exit
assertTrue(ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
String key = ShutdownMonitor.getInstance().getKey();
int port = ShutdownMonitor.getInstance().getPort();
stop("stop", port, key, true);
assertTrue(!ShutdownMonitor.getInstance().isAlive());
assertTrue(server.stopped);
assertTrue(!server.destroyed);
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(!ShutdownMonitor.isRegistered(server));
}
@Test
public void testOldStopCommandWithStopOnShutdownFalse() throws Exception
{
//change so stopatshutdown is false, so stop does nothing in this case (as exitVm is false otherwise we couldn't run test)
ShutdownMonitor.getInstance().setExitVm(false);
System.setProperty("DEBUG", "true");
ShutdownMonitor.getInstance().setPort(0);
TestableServer server = new TestableServer();
server.setStopAtShutdown(false);
server.start();
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
String key = ShutdownMonitor.getInstance().getKey();
int port = ShutdownMonitor.getInstance().getPort();
stop ("stop", port, key, true);
assertTrue(!ShutdownMonitor.getInstance().isAlive());
assertTrue(!server.stopped);
assertTrue(!server.destroyed);
assertTrue(!ShutdownThread.isRegistered(server));
assertTrue(ShutdownMonitor.isRegistered(server));
}
public void stop(String command, int port, String key, boolean check) throws Exception
{
System.out.printf("Attempting to send "+command+" to localhost:%d (%b)%n",port,check);
try (Socket s = new Socket(InetAddress.getByName("127.0.0.1"),port))
{
// send stop command
try (OutputStream out = s.getOutputStream())
{
out.write((key + "\r\nstop\r\n").getBytes());
out.write((key + "\r\n"+command+"\r\n").getBytes());
out.flush();
if (check)

View File

@ -494,7 +494,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
}
if (LOG.isDebugEnabled())
LOG.debug("uri="+request.getRequestURI()+" resource="+resource+(content!=null?" content":""));
LOG.debug(String.format("uri=%s, resource=%s, content=%s",request.getRequestURI(),resource,content));
// Handle resource
if (resource==null || !resource.exists())
@ -863,7 +863,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
throws IOException
{
final long content_length = (content==null)?resource.length():content.getContentLength();
// Get the output stream (or writer)
OutputStream out =null;
boolean written;
@ -881,6 +881,9 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
out = new WriterOutputStream(response.getWriter());
written=true; // there may be data in writer buffer, so assume written
}
if (LOG.isDebugEnabled())
LOG.debug(String.format("sendData content=%s out=%s async=%b",content,out,request.isAsyncSupported()));
if ( reqRanges == null || !reqRanges.hasMoreElements() || content_length<0)
{
@ -935,6 +938,12 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
LOG.warn(x);
context.complete();
}
@Override
public String toString()
{
return String.format("DefaultServlet@%x$CB", DefaultServlet.this.hashCode());
}
});
}
// otherwise write content blocking

View File

@ -129,13 +129,14 @@ public class AsyncGzipFilter extends UserAgentFilter implements GzipFactory
private static final Logger LOG = Log.getLogger(GzipFilter.class);
public final static String GZIP = "gzip";
public static final String DEFLATE = "deflate";
public final static String ETAG_GZIP="--gzip";
public final static String ETAG = "o.e.j.s.GzipFilter.ETag";
public final static int DEFAULT_MIN_GZIP_SIZE=256;
protected ServletContext _context;
protected final Set<String> _mimeTypes=new HashSet<>();
protected boolean _excludeMimeTypes;
protected int _bufferSize=8192;
protected int _bufferSize=32*1024;
protected int _minGzipSize=DEFAULT_MIN_GZIP_SIZE;
protected int _deflateCompressionLevel=Deflater.DEFAULT_COMPRESSION;
protected boolean _deflateNoWrap = true;
@ -363,9 +364,8 @@ public class AsyncGzipFilter extends UserAgentFilter implements GzipFactory
String etag = request.getHeader("If-None-Match");
if (etag!=null)
{
int dd=etag.indexOf("--");
if (dd>0)
request.setAttribute(ETAG,etag.substring(0,dd)+(etag.endsWith("\"")?"\"":""));
if (etag.contains(ETAG_GZIP))
request.setAttribute(ETAG,etag.replace(ETAG_GZIP,""));
}
HttpChannel<?> channel = HttpChannel.getCurrentHttpChannel();

View File

@ -255,7 +255,7 @@ public abstract class AbstractCompressedStream extends ServletOutputStream
String etag=_wrapper.getETag();
if (etag!=null)
setHeader("ETag",etag.substring(0,etag.length()-1)+'-'+_encoding+'"');
setHeader("ETag",etag.substring(0,etag.length()-1)+"--"+_encoding+'"');
return;
}
}

View File

@ -31,6 +31,7 @@ import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.HttpChannel;
import org.eclipse.jetty.server.HttpOutput;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.servlets.AsyncGzipFilter;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.IteratingNestedCallback;
@ -78,14 +79,16 @@ public class GzipHttpOutput extends HttpOutput
break;
case COMMITTING:
throw new WritePendingException();
callback.failed(new WritePendingException());
break;
case COMPRESSING:
gzip(content,complete,callback);
break;
case FINISHED:
throw new IllegalStateException();
default:
callback.failed(new IllegalStateException("state="+_state.get()));
break;
}
}
@ -122,6 +125,8 @@ public class GzipHttpOutput extends HttpOutput
else
new GzipBufferCB(content,complete,callback).iterate();
}
else
callback.succeeded();
}
protected void commit(ByteBuffer content, boolean complete, Callback callback)
@ -191,14 +196,15 @@ public class GzipHttpOutput extends HttpOutput
response.setContentLength(-1);
String etag=fields.get(HttpHeader.ETAG);
if (etag!=null)
fields.put(HttpHeader.ETAG,etag.substring(0,etag.length()-1)+"--gzip\"");
fields.put(HttpHeader.ETAG,etag.substring(0,etag.length()-1)+AsyncGzipFilter.ETAG_GZIP+ '"');
LOG.debug("{} compressing {}",this,_deflater);
_state.set(GZState.COMPRESSING);
gzip(content,complete,callback);
}
// TODO else ?
else
callback.failed(new WritePendingException());
}
public void noCompression()
@ -299,6 +305,8 @@ public class GzipHttpOutput extends HttpOutput
if (!_complete)
return Action.SUCCEEDED;
_deflater.finish();
}
BufferUtil.compact(_buffer);
@ -319,22 +327,22 @@ public class GzipHttpOutput extends HttpOutput
{
private final ByteBuffer _input;
private final ByteBuffer _content;
private final boolean _complete;
private final boolean _last;
public GzipBufferCB(ByteBuffer content, boolean complete, Callback callback)
{
super(callback);
_input=getHttpChannel().getByteBufferPool().acquire(Math.min(_factory.getBufferSize(),content.remaining()),false);
_content=content;
_complete=complete;
_last=complete;
}
@Override
protected Action process() throws Exception
{
if (_deflater.needsInput())
{
{
if (BufferUtil.isEmpty(_content))
{
{
if (_deflater.finished())
{
_factory.recycle(_deflater);
@ -344,40 +352,45 @@ public class GzipHttpOutput extends HttpOutput
return Action.SUCCEEDED;
}
if (!_complete)
if (!_last)
{
return Action.SUCCEEDED;
}
_deflater.finish();
}
else
{
BufferUtil.clearToFill(_input);
BufferUtil.put(_content,_input);
int took=BufferUtil.put(_content,_input);
BufferUtil.flipToFlush(_input,0);
if (took==0)
throw new IllegalStateException();
byte[] array=_input.array();
int off=_input.arrayOffset()+_input.position();
int len=_input.remaining();
_crc.update(array,off,len);
_deflater.setInput(array,off,len);
if (_complete && BufferUtil.isEmpty(_content))
if (_last && BufferUtil.isEmpty(_content))
_deflater.finish();
}
}
BufferUtil.compact(_buffer);
int off=_buffer.arrayOffset()+_buffer.limit();
int len=_buffer.capacity()-_buffer.limit() - (_complete?8:0);
int len=_buffer.capacity()-_buffer.limit() - (_last?8:0);
int produced=_deflater.deflate(_buffer.array(),off,len,Deflater.NO_FLUSH);
_buffer.limit(_buffer.limit()+produced);
boolean complete=_deflater.finished();
boolean finished=_deflater.finished();
if (complete)
if (finished)
addTrailer();
superWrite(_buffer,complete,this);
superWrite(_buffer,finished,this);
return Action.SCHEDULED;
}
}
}

View File

@ -0,0 +1,8 @@
[name]
protonego-boot
[files]
http://central.maven.org/maven2/org/mortbay/jetty/npn/npn-boot/1.1.7.v20140316/npn-boot-1.1.7.v20140316.jar|lib/npn/npn-boot-1.1.7.v20140316.jar
[exec]
-Xbootclasspath/p:lib/npn/npn-boot-1.1.7.v20140316.jar

View File

@ -176,18 +176,21 @@ public class CommandLineBuilder
@Override
public String toString()
{
return toString(" ");
}
public String toString(String delim)
{
StringBuilder buf = new StringBuilder();
boolean delim = false;
for (String arg : args)
{
if (delim)
if (buf.length()>0)
{
buf.append(' ');
buf.append(delim);
}
buf.append(quote(arg));
delim = true;
}
return buf.toString();

View File

@ -654,7 +654,7 @@ public class Main
if (args.isDryRun())
{
CommandLineBuilder cmd = args.getMainArgs(baseHome,true);
System.out.println(cmd.toString());
System.out.println(cmd.toString(File.separatorChar=='/'?" \\\n":" "));
}
if (args.isStopCommand())

View File

@ -330,6 +330,7 @@ public class Modules implements Iterable<Module>
parentNames.addAll(module.getParentNames());
for(String name: parentNames)
{
StartLog.debug("Enable parent '%s' of module: %s",name,module.getName());
Module parent = modules.get(name);
if (parent == null)
{
@ -468,6 +469,7 @@ public class Modules implements Iterable<Module>
// load missing post-expanded dependent modules
private void normalizeDependencies() throws FileNotFoundException, IOException
{
Set<String> expandedModules = new HashSet<>();
boolean done = false;
while (!done)
{
@ -478,26 +480,31 @@ public class Modules implements Iterable<Module>
{
for (String parent : m.getParentNames())
{
if (modules.containsKey(parent) || missingModules.contains(parent))
String expanded = args.getProperties().expand(parent);
if (modules.containsKey(expanded) || missingModules.contains(parent) || expandedModules.contains(parent))
{
continue; // found. skip it.
}
done = false;
StartLog.debug("Missing parent module %s == %s for %s",parent,expanded,m);
missingParents.add(parent);
}
}
for (String missingParent : missingParents)
{
Path file = baseHome.getPath("modules/" + missingParent + ".mod");
String expanded = args.getProperties().expand(missingParent);
Path file = baseHome.getPath("modules/" + expanded + ".mod");
if (FS.canReadFile(file))
{
Module module = registerModule(file);
updateParentReferencesTo(module);
if (!expanded.equals(missingParent))
expandedModules.add(missingParent);
}
else
{
StartLog.debug("Missing module definition: [ Mod: %s | File: %s ]",missingParent,file);
StartLog.debug("Missing module definition: %s == %s",missingParent,expanded);
missingModules.add(missingParent);
}
}

View File

@ -186,16 +186,7 @@ public class SharedBlockingCallback
try
{
while (_state == null)
{
// TODO remove this debug timout!
// This is here to help debug 435322,
if (!_complete.await(10,TimeUnit.MINUTES))
{
IOException x = new IOException("DEBUG timeout");
LOG.warn("Blocked too long (please report!!!) "+this, x);
_state=x;
}
}
_complete.await();
if (_state == SUCCEEDED)
return;
@ -241,7 +232,11 @@ public class SharedBlockingCallback
if (_state == IDLE)
throw new IllegalStateException("IDLE");
if (_state == null)
LOG.debug("Blocker not complete",new Throwable());
{
LOG.warn("Blocker not complete {}",this);
if (LOG.isDebugEnabled())
LOG.debug(new Throwable());
}
}
finally
{
@ -249,6 +244,7 @@ public class SharedBlockingCallback
{
_state = IDLE;
_idle.signalAll();
_complete.signalAll();
}
finally
{
@ -263,7 +259,7 @@ public class SharedBlockingCallback
_lock.lock();
try
{
return String.format("%s@%x{%s}",SharedBlockingCallback.class.getSimpleName(),hashCode(),_state);
return String.format("%s@%x{%s}",Blocker.class.getSimpleName(),hashCode(),_state);
}
finally
{

View File

@ -119,6 +119,12 @@ public class ShutdownThread extends Thread
_thread.unhook();
}
/* ------------------------------------------------------------ */
public static synchronized boolean isRegistered(LifeCycle lifeCycle)
{
return _thread._lifeCycles.contains(lifeCycle);
}
/* ------------------------------------------------------------ */
@Override
public void run()
@ -132,7 +138,7 @@ public class ShutdownThread extends Thread
lifeCycle.stop();
LOG.debug("Stopped {}",lifeCycle);
}
if (lifeCycle instanceof Destroyable)
{
((Destroyable)lifeCycle).destroy();

View File

@ -23,6 +23,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
@ -461,16 +462,43 @@ public class WebAppClassLoader extends URLClassLoader
}
/* ------------------------------------------------------------ */
/**
* @see addTransformer
* @deprecated
*/
public void addClassFileTransformer(ClassFileTransformer transformer)
{
_transformers.add(transformer);
}
/* ------------------------------------------------------------ */
/**
* @see removeTransformer
* @deprecated
*/
public boolean removeClassFileTransformer(ClassFileTransformer transformer)
{
return _transformers.remove(transformer);
}
/* ------------------------------------------------------------ */
/**
* @see addClassFileTransformer
*/
public void addTransformer(ClassFileTransformer transformer)
{
_transformers.add(transformer);
}
/* ------------------------------------------------------------ */
/**
* @see removeClassFileTransformer
*/
public boolean removeTransformer(ClassFileTransformer transformer)
{
return _transformers.remove(transformer);
}
/* ------------------------------------------------------------ */
@Override

View File

@ -97,7 +97,7 @@ public class WebAppClassLoaderTest
{
final List<Object> results=new ArrayList<Object>();
_loader.addClassFileTransformer(new ClassFileTransformer()
_loader.addTransformer(new ClassFileTransformer()
{
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer)
throws IllegalClassFormatException
@ -109,7 +109,7 @@ public class WebAppClassLoaderTest
return b;
}
});
_loader.addClassFileTransformer(new ClassFileTransformer()
_loader.addTransformer(new ClassFileTransformer()
{
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer)
throws IllegalClassFormatException

View File

@ -1212,13 +1212,13 @@ public class XmlConfiguration
// For all arguments, load properties
for (String arg : args)
{
if (arg.toLowerCase(Locale.ENGLISH).endsWith(".properties"))
properties.load(Resource.newResource(arg).getInputStream());
else if (arg.indexOf('=')>=0)
if (arg.indexOf('=')>=0)
{
int i=arg.indexOf('=');
properties.put(arg.substring(0,i),arg.substring(i+1));
}
else if (arg.toLowerCase(Locale.ENGLISH).endsWith(".properties"))
properties.load(Resource.newResource(arg).getInputStream());
}
// For all arguments, parse XMLs

27
pom.xml
View File

@ -540,7 +540,7 @@
<dependency>
<groupId>org.mortbay.jasper</groupId>
<artifactId>apache-jsp</artifactId>
<version>8.0.3.v20140313</version>
<version>8.0.9.M1</version>
</dependency>
<dependency>
@ -907,6 +907,19 @@
<alpn.version>7.0.0.v20140317</alpn.version>
</properties>
</profile>
<profile>
<id>7u67</id>
<activation>
<property>
<name>java.version</name>
<value>1.7.0_67</value>
</property>
</activation>
<properties>
<npn.version>1.1.7.v20140316</npn.version>
<alpn.version>7.0.0.v20140317</alpn.version>
</properties>
</profile>
<profile>
<id>8u00</id>
<activation>
@ -943,6 +956,18 @@
<alpn.version>8.0.0.v20140317</alpn.version>
</properties>
</profile>
<profile>
<id>8u20</id>
<activation>
<property>
<name>java.version</name>
<value>1.8.0_20</value>
</property>
</activation>
<properties>
<alpn.version>8.0.0.v20140317</alpn.version>
</properties>
</profile>
</profiles>
</project>