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> <artifactId>javax.servlet-api</artifactId>
</dependency> </dependency>
<!-- JSP Api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
</dependency>
<!-- JSP Impl --> <!-- JSP Impl -->
<dependency> <dependency>
<groupId>org.mortbay.jasper</groupId> <groupId>org.mortbay.jasper</groupId>

View File

@ -57,11 +57,6 @@
<artifactId>spdy-http-server</artifactId> <artifactId>spdy-http-server</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-plus</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.eclipse.jetty</groupId> <groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-annotations</artifactId> <artifactId>jetty-annotations</artifactId>
@ -80,6 +75,20 @@
<groupId>org.eclipse.jetty</groupId> <groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-proxy</artifactId> <artifactId>jetty-proxy</artifactId>
<version>${project.version}</version> <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>
<dependency> <dependency>
<groupId>org.eclipse.jetty.toolchain</groupId> <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 //Create a WebApp
WebAppContext webapp = new WebAppContext(); WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/"); 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$"); webapp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/javax.servlet-[^/]*\\.jar$|.*/servlet-api-[^/]*\\.jar$");
server.setHandler(webapp); server.setHandler(webapp);

View File

@ -45,7 +45,7 @@ public class ServerWithJNDI
//Create a WebApp //Create a WebApp
WebAppContext webapp = new WebAppContext(); WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/"); 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); server.setHandler(webapp);
//Register new transaction manager in JNDI //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.LEVEL=DEBUG
#org.eclipse.jetty.io.ssl.LEVEL=DEBUG #org.eclipse.jetty.io.ssl.LEVEL=DEBUG
#org.eclipse.jetty.spdy.server.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> </goals>
<configuration> <configuration>
<instructions> <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> <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> </instructions>
</configuration> </configuration>

View File

@ -147,6 +147,13 @@ public interface Response
public interface AsyncContentListener extends ResponseListener 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); public void onContent(Response response, ByteBuffer content, Callback callback);
} }

View File

@ -302,7 +302,7 @@
<configuration> <configuration>
<includeGroupIds>org.eclipse.jetty</includeGroupIds> <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> <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> <includeTypes>jar</includeTypes>
<outputDirectory>${assembly-directory}/lib</outputDirectory> <outputDirectory>${assembly-directory}/lib</outputDirectory>
</configuration> </configuration>
@ -477,8 +477,8 @@
<goal>copy-dependencies</goal> <goal>copy-dependencies</goal>
</goals> </goals>
<configuration> <configuration>
<includeGroupIds>org.eclipse.jetty,org.eclipse.jetty.toolchain,javax.servlet.jsp,org.mortbay.jasper,org.mortbay.jasper,org.eclipse.jetty.orbit</includeGroupIds> <includeGroupIds>org.eclipse.jetty,org.eclipse.jetty.toolchain,org.mortbay.jasper,org.eclipse.jetty.orbit</includeGroupIds>
<includeArtifactIds>apache-jsp,javax.servlet.jsp-api,apache-el,org.eclipse.jdt.core</includeArtifactIds> <includeArtifactIds>apache-jsp,apache-el,org.eclipse.jdt.core</includeArtifactIds>
<includeTypes>jar</includeTypes> <includeTypes>jar</includeTypes>
<prependGroupId>true</prependGroupId> <prependGroupId>true</prependGroupId>
<outputDirectory>${assembly-directory}/lib/apache-jsp</outputDirectory> <outputDirectory>${assembly-directory}/lib/apache-jsp</outputDirectory>

View File

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

View File

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

View File

@ -168,5 +168,11 @@ public interface HttpContent
{ {
_resource.close(); _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) if (DEBUG)
LOG.debug("flushed {}", flushed); LOG.debug("flushed {}", flushed);
// Are we complete? // if we are incomplete?
for (ByteBuffer b : buffers) if (!flushed)
{ {
if (!flushed||BufferUtil.hasContent(b)) PendingState pending=new PendingState(buffers, callback);
{ if (updateState(__WRITING,pending))
PendingState pending=new PendingState(buffers, callback); onIncompleteFlushed();
if (updateState(__WRITING,pending)) else
onIncompleteFlushed(); fail(pending);
else return;
fail(pending);
return;
}
} }
// If updateState didn't succeed, we don't care as our buffers have been written // 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) if (DEBUG)
LOG.debug("flushed {}", flushed); LOG.debug("flushed {}", flushed);
// Are we complete? // if we are incomplete?
for (ByteBuffer b : buffers) if (!flushed)
{ {
if (!flushed || BufferUtil.hasContent(b)) if (updateState(__COMPLETING,pending))
{ onIncompleteFlushed();
if (updateState(__COMPLETING,pending)) else
onIncompleteFlushed(); fail(pending);
else return;
fail(pending);
return;
}
} }
// If updateState didn't succeed, we don't care as our buffers have been written // 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) if (DEBUG)
LOG.debug("{} renegotiation denied", SslConnection.this); LOG.debug("{} renegotiation denied", SslConnection.this);
shutdownOutput(); getEndPoint().shutdownOutput();
return allConsumed; return allConsumed;
} }

View File

@ -211,21 +211,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo
*/ */
protected boolean dumpOnStart; 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; 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; public abstract void restartWebApp(boolean reconfigureScanner) throws Exception;
@ -472,14 +469,8 @@ public abstract class AbstractJettyMojo extends AbstractMojo
try try
{ {
getLog().debug("Starting Jetty Server ..."); getLog().debug("Starting Jetty Server ...");
if(stopPort>0 && stopKey!=null) configureMonitor();
{
ShutdownMonitor monitor = ShutdownMonitor.getInstance();
monitor.setPort(stopPort);
monitor.setKey(stopKey);
monitor.setExitVm(!daemon);
}
printSystemProperties(); printSystemProperties();
@ -558,7 +549,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo
startConsoleScanner(); startConsoleScanner();
// keep the thread going if not in daemon mode // keep the thread going if not in daemon mode
if (!daemon ) if (!nonblocking )
{ {
server.join(); server.join();
} }
@ -569,7 +560,7 @@ public abstract class AbstractJettyMojo extends AbstractMojo
} }
finally finally
{ {
if (!daemon ) if (!nonblocking )
{ {
getLog().info("Jetty server exiting."); 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; package org.eclipse.jetty.maven.plugin;
import java.io.File;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/** /**
* <p> * <p>
* This goal is used to run Jetty with a pre-assembled war. * 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 * 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. * 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 * 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>
* <p> * <p>
* This goal is useful e.g. for launching a web app in Jetty as a target for unit-tested * 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 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() * @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. * This goal is used to assemble your webapp into an exploded war and automatically deploy it to Jetty.
* </p> * </p>
* <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. * to WEB-INF/web.xml, WEB-INF/classes or WEB-INF/lib and hot redeploy when a change is detected.
* </p> * </p>
* <p> * <p>
* You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration. * 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. * This can be used, for example, to deploy a static webapp that is not part of your maven build.
* </p> * </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 *@goal run-exploded
*@requiresDependencyResolution compile+runtime *@requiresDependencyResolution compile+runtime
@ -56,7 +52,7 @@ public class JettyRunWarExplodedMojo extends AbstractJettyMojo
/** /**
* The location of the war file. * 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 * @required
*/ */
private File war; 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. * This goal is used to assemble your webapp into a war and automatically deploy it to Jetty.
* </p> * </p>
* <p> * <p>
* Once invoked, the plugin can be configured to run continuously, scanning for changes in the project and to the * Once invoked, the plugin runs continuously and can be configured to scan for changes in the project and to the
* war file and automatically performing a * war file and automatically perform a hot redeploy when necessary.
* hot redeploy when necessary.
* </p> * </p>
* <p> * <p>
* You may also specify the location of a jetty.xml file whose contents will be applied before any plugin configuration. * 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. * This can be used, for example, to deploy a static webapp that is not part of your maven build.
* </p> * </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 * @goal run-war
* @requiresDependencyResolution compile+runtime * @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 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 class JettyServer extends org.eclipse.jetty.server.Server
{ {
public static final JettyServer __instance = new JettyServer();
private RequestLog requestLog; private RequestLog requestLog;
private ContextHandlerCollection contexts; private ContextHandlerCollection contexts;
@ -57,7 +55,6 @@ public class JettyServer extends org.eclipse.jetty.server.Server
public JettyServer() public JettyServer()
{ {
super(); super();
setStopAtShutdown(true);
//make sure Jetty does not use URLConnection caches with the plugin //make sure Jetty does not use URLConnection caches with the plugin
Resource.setDefaultUseCaches(false); Resource.setDefaultUseCaches(false);
} }

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.maven.plugin; package org.eclipse.jetty.maven.plugin;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/** /**
* <p> * <p>
@ -37,4 +40,20 @@ package org.eclipse.jetty.maven.plugin;
*/ */
public class JettyStartMojo extends JettyRunMojo 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; protected int stopWait;
public void execute() throws MojoExecutionException, MojoFailureException public void execute() throws MojoExecutionException, MojoFailureException
{ {
@ -71,13 +75,17 @@ public class JettyStopMojo extends AbstractMojo
if (stopKey == null) if (stopKey == null)
throw new MojoExecutionException("Please specify a valid stopKey"); 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 try
{ {
Socket s=new Socket(InetAddress.getByName("127.0.0.1"),stopPort); Socket s=new Socket(InetAddress.getByName("127.0.0.1"),stopPort);
s.setSoLinger(false, 0); s.setSoLinger(false, 0);
OutputStream out=s.getOutputStream(); OutputStream out=s.getOutputStream();
out.write((stopKey+"\r\nstop\r\n").getBytes()); out.write((stopKey+"\r\n"+command+"\r\n").getBytes());
out.flush(); out.flush();
if (stopWait > 0) if (stopWait > 0)

View File

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

View File

@ -176,71 +176,63 @@ public abstract class NoSqlSessionManager extends AbstractSessionManager impleme
@Override @Override
protected boolean removeSession(String idInCluster) protected boolean removeSession(String idInCluster)
{ {
synchronized (this) NoSqlSession session = _sessions.remove(idInCluster);
try
{ {
NoSqlSession session = _sessions.remove(idInCluster); if (session != null)
try
{ {
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 ) 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);
//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);
} }
if (session != null)
session.timeout();
}
catch (Exception e)
{
__log.warn("Problem expiring session {}", idInCluster,e);
} }
} }
public void invalidateSession (String idInCluster) public void invalidateSession (String idInCluster)
{ {
synchronized (this) NoSqlSession session = _sessions.get(idInCluster);
try
{ {
NoSqlSession session = _sessions.get(idInCluster); __log.debug("invalidating session {}", idInCluster);
try if (session != null)
{ {
__log.debug("invalidating session {}", idInCluster); session.invalidate();
if (session != null)
{
session.invalidate();
}
}
catch (Exception e)
{
__log.warn("Problem invalidating session {}", idInCluster,e);
} }
} }
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.net.URL;
import java.util.Comparator; import java.util.Comparator;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.TreeSet; 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.osgi.boot.utils.BundleFileLocatorHelper;
import org.eclipse.jetty.util.ConcurrentHashSet; import org.eclipse.jetty.util.ConcurrentHashSet;
import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.resource.Resource;
import org.objectweb.asm.Opcodes;
import org.osgi.framework.Bundle; import org.osgi.framework.Bundle;
import org.osgi.framework.Constants; 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<Resource, Bundle> _resourceToBundle = new ConcurrentHashMap<Resource, Bundle>();
private ConcurrentHashMap<Bundle,URI> _bundleToUri = new ConcurrentHashMap<Bundle, URI>(); 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. * 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()); scanClass(handlers, getResource(bundle), classUrl.openStream());
} }
} }
} }

View File

@ -164,24 +164,10 @@
<dependency> <dependency>
<groupId>org.apache.aries.spifly</groupId> <groupId>org.apache.aries.spifly</groupId>
<artifactId>org.apache.aries.spifly.dynamic.bundle</artifactId> <artifactId>org.apache.aries.spifly.dynamic.bundle</artifactId>
<version>1.0.0</version> <version>1.0.1</version>
<scope>test</scope> <scope>test</scope>
</dependency> </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 --> <!-- Jetty Deps -->
@ -189,20 +175,6 @@
<groupId>org.eclipse.jetty</groupId> <groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-annotations</artifactId> <artifactId>jetty-annotations</artifactId>
<scope>runtime</scope> <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>
<dependency> <dependency>
<groupId>org.eclipse.jetty</groupId> <groupId>org.eclipse.jetty</groupId>
@ -362,31 +334,6 @@
</dependency> </dependency>
<!-- Eclipse OSGi Deps --> <!-- 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> <dependency>
<groupId>org.eclipse.jetty</groupId> <groupId>org.eclipse.jetty</groupId>
<artifactId>test-jetty-webapp</artifactId> <artifactId>test-jetty-webapp</artifactId>

View File

@ -31,13 +31,12 @@ import javax.inject.Inject;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.MavenUtils; import org.ops4j.pax.exam.MavenUtils;
import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.options.MavenUrlReference.VersionResolver; import org.ops4j.pax.exam.options.MavenUrlReference.VersionResolver;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext; 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("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.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.LEVEL").value(LOG_LEVEL))));
options.addAll(Arrays.asList(options(systemProperty("org.eclipse.jetty.annotations.LEVEL").value("DEBUG"))));
return options.toArray(new Option[options.size()]); return options.toArray(new Option[options.size()]);
} }
@ -82,20 +81,12 @@ public class TestJettyOSGiBootCore
public static List<Option> coreJettyDependencies() public static List<Option> coreJettyDependencies()
{ {
List<Option> res = new ArrayList<Option>(); 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" ).versionAsInProject().start()); res.add(mavenBundle().groupId( "org.ow2.asm" ).artifactId( "asm-tree" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.ow2.asm" ).artifactId( "asm-commons" ).versionAsInProject().start()); res.add(mavenBundle().groupId( "org.apache.aries" ).artifactId( "org.apache.aries.util" ).versionAsInProject().start());
res.add(mavenBundle().groupId( "org.ow2.asm" ).artifactId( "asm-tree" ).versionAsInProject().start()); res.add(mavenBundle().groupId( "org.apache.aries.spifly" ).artifactId( "org.apache.aries.spifly.dynamic.bundle" ).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( "javax.servlet" ).artifactId( "javax.servlet-api" ).versionAsInProject().noStart()); res.add(mavenBundle().groupId( "javax.servlet" ).artifactId( "javax.servlet-api" ).versionAsInProject().noStart());
res.add(mavenBundle().groupId( "javax.annotation" ).artifactId( "javax.annotation-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-client" ).versionAsInProject().noStart());
res.add(mavenBundle().groupId( "org.eclipse.jetty" ).artifactId( "jetty-jndi" ).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()); 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-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-common" ).versionAsInProject().noStart());
res.add(mavenBundle().groupId( "org.eclipse.jetty.websocket" ).artifactId( "websocket-servlet" ).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) catch (Throwable x)
{ {
callback.failed(x); callback.failed(x);
onResponseFailure(request, response, proxyResponse, x); proxyResponse.abort(x);
} }
} }
@ -279,8 +279,7 @@ public class AsyncProxyServlet extends ProxyServlet
@Override @Override
public void onError(Throwable failure) public void onError(Throwable failure)
{ {
HttpServletResponse response = (HttpServletResponse)request.getAsyncContext().getResponse(); proxyResponse.abort(failure);
onResponseFailure(request, response, proxyResponse, failure);
} }
} }

View File

@ -354,7 +354,7 @@ public class ProxyServletTest
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()) ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.method(HttpMethod.POST) .method(HttpMethod.POST)
.content(new BytesContentProvider(content)) .content(new BytesContentProvider(content))
.timeout(555, TimeUnit.SECONDS) .timeout(5, TimeUnit.SECONDS)
.send(); .send();
Assert.assertEquals(200, response.getStatus()); 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.HttpChannelState.Action;
import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ErrorHandler; import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.SharedBlockingCallback.Blocker; import org.eclipse.jetty.util.SharedBlockingCallback.Blocker;
import org.eclipse.jetty.util.URIUtil; import org.eclipse.jetty.util.URIUtil;
@ -360,7 +361,10 @@ public class HttpChannel<T> implements HttpParser.RequestHandler<T>, Runnable, H
else else
{ {
error=true; error=true;
throw e; LOG.warn(String.valueOf(_uri), e);
_state.error(e);
_request.setHandled(true);
handleException(e);
} }
} }
catch (Exception e) catch (Exception e)
@ -484,10 +488,11 @@ public class HttpChannel<T> implements HttpParser.RequestHandler<T>, Runnable, H
@Override @Override
public String toString() 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(), getClass().getSimpleName(),
hashCode(), hashCode(),
_requests, _requests,
_committed.get(),
_state.getState(), _state.getState(),
_state.getState()==HttpChannelState.State.IDLE?"-":_request.getRequestURI() _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) 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); boolean committing = _committed.compareAndSet(false, true);
if (committing) if (committing)
{ {
@ -732,7 +736,7 @@ public class HttpChannel<T> implements HttpParser.RequestHandler<T>, Runnable, H
if (info==null) if (info==null)
info = _response.newResponseInfo(); info = _response.newResponseInfo();
// wrap callback to process 100 or 500 responses // wrap callback to process 100 responses
final int status=info.getStatus(); final int status=info.getStatus();
final Callback committed = (status<200&&status>=100)?new Commit100Callback(callback):new CommitCallback(callback); 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 @Override
public void succeeded() public void succeeded()
{ {
_committed.set(false); if (_committed.compareAndSet(true, false))
super.succeeded(); 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 // then we can't be persistent
_generator.setPersistent(false); _generator.setPersistent(false);
_sendCallback.reset(info,content,lastContent,callback); if(_sendCallback.reset(info,content,lastContent,callback))
_sendCallback.iterate(); _sendCallback.iterate();
} }
@Override @Override
public void send(ByteBuffer content, boolean lastContent, Callback callback) public void send(ByteBuffer content, boolean lastContent, Callback callback)
{ {
_sendCallback.reset(null,content,lastContent,callback); if (!lastContent && BufferUtil.isEmpty(content))
_sendCallback.iterate(); callback.succeeded();
else if (_sendCallback.reset(null,content,lastContent,callback))
_sendCallback.iterate();
} }
protected class HttpChannelOverHttp extends HttpChannel<ByteBuffer> protected class HttpChannelOverHttp extends HttpChannel<ByteBuffer>
@ -565,7 +567,7 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
super(true); 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()) if (reset())
{ {
@ -575,15 +577,14 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
_callback = callback; _callback = callback;
_header = null; _header = null;
_shutdownOut = false; _shutdownOut = false;
return true;
} }
else if (isClosed())
{ if (isClosed())
callback.failed(new EofException()); callback.failed(new EofException());
}
else else
{
callback.failed(new WritePendingException()); callback.failed(new WritePendingException());
} return false;
} }
@Override @Override
@ -651,7 +652,9 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
getEndPoint().write(this, _content); getEndPoint().write(this, _content);
} }
else else
continue; {
succeeded(); // nothing to write
}
return Action.SCHEDULED; return Action.SCHEDULED;
} }
case SHUTDOWN_OUT: case SHUTDOWN_OUT:
@ -661,7 +664,6 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
} }
case DONE: case DONE:
{ {
releaseHeader();
return Action.SUCCEEDED; return Action.SUCCEEDED;
} }
case CONTINUE: case CONTINUE:

View File

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

View File

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

View File

@ -504,7 +504,7 @@ public class ResourceCache
@Override @Override
public String toString() 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; package org.eclipse.jetty.server;
import java.awt.geom.PathIterator;
import java.io.IOException; import java.io.IOException;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.net.InetAddress; 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.Jetty;
import org.eclipse.jetty.util.MultiException; import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.URIUtil; 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.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.util.annotation.Name;
@ -145,7 +143,8 @@ public class Server extends HandlerWrapper implements Attributes
{ {
return _stopAtShutdown; return _stopAtShutdown;
} }
/* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */
/** /**
* Set a graceful stop time. * Set a graceful stop time.
@ -313,11 +312,16 @@ public class Server extends HandlerWrapper implements Attributes
@Override @Override
protected void doStart() throws Exception protected void doStart() throws Exception
{ {
//If the Server should be stopped when the jvm exits, register
//with the shutdown handler thread.
if (getStopAtShutdown()) if (getStopAtShutdown())
{
ShutdownThread.register(this); 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 ShutdownMonitor.getInstance().start(); // initialize
LOG.info("jetty-" + getVersion()); LOG.info("jetty-" + getVersion());
@ -455,6 +459,11 @@ public class Server extends HandlerWrapper implements Attributes
if (getStopAtShutdown()) if (getStopAtShutdown())
ShutdownThread.deregister(this); 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(); mex.ifExceptionThrow();

View File

@ -26,8 +26,15 @@ import java.net.InetAddress;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Properties; 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; import org.eclipse.jetty.util.thread.ShutdownThread;
/** /**
@ -42,6 +49,8 @@ import org.eclipse.jetty.util.thread.ShutdownThread;
*/ */
public class ShutdownMonitor public class ShutdownMonitor
{ {
private final Set<LifeCycle> _lifeCycles = new CopyOnWriteArraySet<LifeCycle>();
// Implementation of safe lazy init, using Initialization on Demand Holder technique. // Implementation of safe lazy init, using Initialization on Demand Holder technique.
static class Holder static class Holder
{ {
@ -52,6 +61,26 @@ public class ShutdownMonitor
{ {
return Holder.instance; 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 * ShutdownMonitorRunnable
@ -95,29 +124,38 @@ public class ShutdownMonitor
String cmd = lin.readLine(); String cmd = lin.readLine();
debug("command=%s",cmd); debug("command=%s",cmd);
if ("stop".equals(cmd)) if ("stop".equalsIgnoreCase(cmd)) //historic, for backward compatibility
{ {
// Graceful Shutdown //Stop the lifecycles, only if they are registered with the ShutdownThread, only destroying if vm is exiting
debug("Issuing graceful shutdown.."); debug("Issuing stop...");
ShutdownThread.getInstance().run();
//Stop accepting any more
close(serverSocket);
serverSocket = null;
//Shutdown input from client for (LifeCycle l:_lifeCycles)
shutdownInput(socket); {
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 // Reply to client
debug("Informing client that we are stopped."); debug("Informing client that we are stopped.");
out.write("Stopped\r\n".getBytes(StandardCharsets.UTF_8)); informClient(out, "Stopped\r\n");
out.flush();
// Shutdown Monitor //Stop the output and close the monitor socket
socket.shutdownOutput(); stopOutput(socket);
close(socket);
socket = null;
debug("Shutting down monitor");
if (exitVm) if (exitVm)
{ {
@ -126,11 +164,59 @@ public class ShutdownMonitor
System.exit(0); 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 // Reply to client
out.write("OK\r\n".getBytes(StandardCharsets.UTF_8)); informClient(out, "OK\r\n");
out.flush();
} }
} }
catch (Exception e) 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() public void startListenSocket()
{ {
if (port < 0) if (port < 0)
@ -309,6 +446,9 @@ public class ShutdownMonitor
this.DEBUG = flag; this.DEBUG = flag;
} }
/**
* @param exitVm
*/
public void setExitVm(boolean exitVm) public void setExitVm(boolean exitVm)
{ {
synchronized (this) synchronized (this)

View File

@ -66,6 +66,9 @@ public class RequestLogHandler extends HandlerWrapper
@Override @Override
public void onError(AsyncEvent event) throws IOException 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); super.handle(target, baseRequest, request, response);
} }
catch(Error|IOException|ServletException|RuntimeException e)
{
if (!response.isCommitted() && !baseRequest.getHttpChannelState().isAsync())
response.setStatus(500);
throw e;
}
finally finally
{ {
if (_requestLog != null && baseRequest.getDispatcherType().equals(DispatcherType.REQUEST)) 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 static org.junit.Assert.assertTrue;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; 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.HttpHeader;
import org.eclipse.jetty.http.HttpParser; import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ErrorHandler; import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.log.Logger;
@ -49,6 +51,7 @@ import org.hamcrest.Matchers;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
/** /**
@ -69,7 +72,7 @@ public class HttpConnectionTest
http.getHttpConfiguration().setResponseHeaderSize(1024); http.getHttpConfiguration().setResponseHeaderSize(1024);
connector = new LocalConnector(server,http,null); connector = new LocalConnector(server,http,null);
connector.setIdleTimeout(500); connector.setIdleTimeout(5000);
server.addConnector(connector); server.addConnector(connector);
server.setHandler(new DumpHandler()); server.setHandler(new DumpHandler());
ErrorHandler eh=new ErrorHandler(); ErrorHandler eh=new ErrorHandler();
@ -324,6 +327,31 @@ public class HttpConnectionTest
offset = checkContains(response,offset,"/R1"); offset = checkContains(response,offset,"/R1");
offset = checkContains(response,offset,"12345"); 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 @Test
public void testCharset() throws Exception public void testCharset() throws Exception
@ -431,6 +459,7 @@ public class HttpConnectionTest
@Test @Test
public void testUnconsumedTimeout() throws Exception public void testUnconsumedTimeout() throws Exception
{ {
connector.setIdleTimeout(500);
String response=null; String response=null;
String requests=null; String requests=null;
int offset=0; int offset=0;

View File

@ -28,6 +28,7 @@ import java.net.InetAddress;
import java.net.Socket; import java.net.Socket;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.util.thread.ShutdownThread;
import org.junit.Test; import org.junit.Test;
/** /**
@ -35,8 +36,34 @@ import org.junit.Test;
*/ */
public class ShutdownMonitorTest 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 @Test
public void testShutdown() throws Exception public void testShutdownMonitor() throws Exception
{ {
// test port and key assignment // test port and key assignment
ShutdownMonitor.getInstance().setPort(0); ShutdownMonitor.getInstance().setPort(0);
@ -48,7 +75,7 @@ public class ShutdownMonitorTest
// try starting a 2nd time (should be ignored) // try starting a 2nd time (should be ignored)
ShutdownMonitor.getInstance().start(); ShutdownMonitor.getInstance().start();
stop(port,key,true); stop("stop", port,key,true);
assertTrue(!ShutdownMonitor.getInstance().isAlive()); assertTrue(!ShutdownMonitor.getInstance().isAlive());
// should be able to change port and key because it is stopped // should be able to change port and key because it is stopped
@ -60,19 +87,113 @@ public class ShutdownMonitorTest
port = ShutdownMonitor.getInstance().getPort(); port = ShutdownMonitor.getInstance().getPort();
assertTrue(ShutdownMonitor.getInstance().isAlive()); assertTrue(ShutdownMonitor.getInstance().isAlive());
stop(port,key,true); stop("stop", port,key,true);
assertTrue(!ShutdownMonitor.getInstance().isAlive()); 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)) try (Socket s = new Socket(InetAddress.getByName("127.0.0.1"),port))
{ {
// send stop command // send stop command
try (OutputStream out = s.getOutputStream()) try (OutputStream out = s.getOutputStream())
{ {
out.write((key + "\r\nstop\r\n").getBytes()); out.write((key + "\r\n"+command+"\r\n").getBytes());
out.flush(); out.flush();
if (check) if (check)

View File

@ -494,7 +494,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
} }
if (LOG.isDebugEnabled()) 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 // Handle resource
if (resource==null || !resource.exists()) if (resource==null || !resource.exists())
@ -863,7 +863,7 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
throws IOException throws IOException
{ {
final long content_length = (content==null)?resource.length():content.getContentLength(); final long content_length = (content==null)?resource.length():content.getContentLength();
// Get the output stream (or writer) // Get the output stream (or writer)
OutputStream out =null; OutputStream out =null;
boolean written; boolean written;
@ -881,6 +881,9 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
out = new WriterOutputStream(response.getWriter()); out = new WriterOutputStream(response.getWriter());
written=true; // there may be data in writer buffer, so assume written 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) if ( reqRanges == null || !reqRanges.hasMoreElements() || content_length<0)
{ {
@ -935,6 +938,12 @@ public class DefaultServlet extends HttpServlet implements ResourceFactory
LOG.warn(x); LOG.warn(x);
context.complete(); context.complete();
} }
@Override
public String toString()
{
return String.format("DefaultServlet@%x$CB", DefaultServlet.this.hashCode());
}
}); });
} }
// otherwise write content blocking // 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); private static final Logger LOG = Log.getLogger(GzipFilter.class);
public final static String GZIP = "gzip"; public final static String GZIP = "gzip";
public static final String DEFLATE = "deflate"; 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 String ETAG = "o.e.j.s.GzipFilter.ETag";
public final static int DEFAULT_MIN_GZIP_SIZE=256; public final static int DEFAULT_MIN_GZIP_SIZE=256;
protected ServletContext _context; protected ServletContext _context;
protected final Set<String> _mimeTypes=new HashSet<>(); protected final Set<String> _mimeTypes=new HashSet<>();
protected boolean _excludeMimeTypes; protected boolean _excludeMimeTypes;
protected int _bufferSize=8192; protected int _bufferSize=32*1024;
protected int _minGzipSize=DEFAULT_MIN_GZIP_SIZE; protected int _minGzipSize=DEFAULT_MIN_GZIP_SIZE;
protected int _deflateCompressionLevel=Deflater.DEFAULT_COMPRESSION; protected int _deflateCompressionLevel=Deflater.DEFAULT_COMPRESSION;
protected boolean _deflateNoWrap = true; protected boolean _deflateNoWrap = true;
@ -363,9 +364,8 @@ public class AsyncGzipFilter extends UserAgentFilter implements GzipFactory
String etag = request.getHeader("If-None-Match"); String etag = request.getHeader("If-None-Match");
if (etag!=null) if (etag!=null)
{ {
int dd=etag.indexOf("--"); if (etag.contains(ETAG_GZIP))
if (dd>0) request.setAttribute(ETAG,etag.replace(ETAG_GZIP,""));
request.setAttribute(ETAG,etag.substring(0,dd)+(etag.endsWith("\"")?"\"":""));
} }
HttpChannel<?> channel = HttpChannel.getCurrentHttpChannel(); HttpChannel<?> channel = HttpChannel.getCurrentHttpChannel();

View File

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

View File

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

View File

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

View File

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

View File

@ -186,16 +186,7 @@ public class SharedBlockingCallback
try try
{ {
while (_state == null) while (_state == null)
{ _complete.await();
// 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;
}
}
if (_state == SUCCEEDED) if (_state == SUCCEEDED)
return; return;
@ -241,7 +232,11 @@ public class SharedBlockingCallback
if (_state == IDLE) if (_state == IDLE)
throw new IllegalStateException("IDLE"); throw new IllegalStateException("IDLE");
if (_state == null) if (_state == null)
LOG.debug("Blocker not complete",new Throwable()); {
LOG.warn("Blocker not complete {}",this);
if (LOG.isDebugEnabled())
LOG.debug(new Throwable());
}
} }
finally finally
{ {
@ -249,6 +244,7 @@ public class SharedBlockingCallback
{ {
_state = IDLE; _state = IDLE;
_idle.signalAll(); _idle.signalAll();
_complete.signalAll();
} }
finally finally
{ {
@ -263,7 +259,7 @@ public class SharedBlockingCallback
_lock.lock(); _lock.lock();
try try
{ {
return String.format("%s@%x{%s}",SharedBlockingCallback.class.getSimpleName(),hashCode(),_state); return String.format("%s@%x{%s}",Blocker.class.getSimpleName(),hashCode(),_state);
} }
finally finally
{ {

View File

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

View File

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

View File

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

View File

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

27
pom.xml
View File

@ -540,7 +540,7 @@
<dependency> <dependency>
<groupId>org.mortbay.jasper</groupId> <groupId>org.mortbay.jasper</groupId>
<artifactId>apache-jsp</artifactId> <artifactId>apache-jsp</artifactId>
<version>8.0.3.v20140313</version> <version>8.0.9.M1</version>
</dependency> </dependency>
<dependency> <dependency>
@ -907,6 +907,19 @@
<alpn.version>7.0.0.v20140317</alpn.version> <alpn.version>7.0.0.v20140317</alpn.version>
</properties> </properties>
</profile> </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> <profile>
<id>8u00</id> <id>8u00</id>
<activation> <activation>
@ -943,6 +956,18 @@
<alpn.version>8.0.0.v20140317</alpn.version> <alpn.version>8.0.0.v20140317</alpn.version>
</properties> </properties>
</profile> </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> </profiles>
</project> </project>