();
+ wah.setAttribute(TagLibConfiguration.TLD_RESOURCES, tldfrags);
+ }
+ while (tldEnum.hasMoreElements())
+ {
+ URL tldUrl = tldEnum.nextElement();
+ tldfrags.add(Resource.newResource(DefaultFileLocatorHelper.getLocalURL(tldUrl)));
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ __logger.warn("Unable to locate the bundle " + frag.getBundleId(), e);
+ }
+ }
+ }
}
}
-
-
+
}
/**
@@ -644,15 +651,13 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
* @param contextFile
* @return
*/
- protected ContextHandler createContextHandler(ContextHandler handlerToConfigure,
- Bundle bundle, File contextFile, String extraClasspath,
- String overrideBundleInstallLocation, String requireTldBundle)
+ protected ContextHandler createContextHandler(ContextHandler handlerToConfigure, Bundle bundle, File contextFile, String extraClasspath,
+ String overrideBundleInstallLocation, String requireTldBundle)
{
try
{
- return createContextHandler(handlerToConfigure,bundle,
- new BufferedInputStream(new FileInputStream(contextFile)),
- extraClasspath,overrideBundleInstallLocation,requireTldBundle);
+ return createContextHandler(handlerToConfigure, bundle, new BufferedInputStream(new FileInputStream(contextFile)), extraClasspath,
+ overrideBundleInstallLocation, requireTldBundle);
}
catch (FileNotFoundException e)
{
@@ -667,9 +672,8 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
* @return
*/
@SuppressWarnings("unchecked")
- protected ContextHandler createContextHandler(ContextHandler handlerToConfigure,
- Bundle bundle, InputStream contextInputStream, String extraClasspath,
- String overrideBundleInstallLocation, String requireTldBundle)
+ protected ContextHandler createContextHandler(ContextHandler handlerToConfigure, Bundle bundle, InputStream contextInputStream, String extraClasspath,
+ String overrideBundleInstallLocation, String requireTldBundle)
{
/*
* Do something identical to what the ContextProvider would have done:
@@ -686,30 +690,30 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
{
XmlConfiguration xmlConfiguration = new XmlConfiguration(contextInputStream);
HashMap properties = new HashMap();
- properties.put("Server",_wrapper.getServer());
-
+ properties.put("Server", _wrapper.getServer());
+
// insert the bundle's location as a property.
- setThisBundleHomeProperty(bundle,properties,overrideBundleInstallLocation);
+ setThisBundleHomeProperty(bundle, properties, overrideBundleInstallLocation);
xmlConfiguration.getProperties().putAll(properties);
ContextHandler context = null;
if (handlerToConfigure == null)
{
- context = (ContextHandler)xmlConfiguration.configure();
+ context = (ContextHandler) xmlConfiguration.configure();
}
else
{
xmlConfiguration.configure(handlerToConfigure);
context = handlerToConfigure;
}
-
+
if (context instanceof WebAppContext)
{
- ((WebAppContext)context).setExtraClasspath(extraClasspath);
- ((WebAppContext)context).setParentLoaderPriority(_wrapper.getOSGiAppProvider().isParentLoaderPriority());
+ ((WebAppContext) context).setExtraClasspath(extraClasspath);
+ ((WebAppContext) context).setParentLoaderPriority(_wrapper.getOSGiAppProvider().isParentLoaderPriority());
if (_wrapper.getOSGiAppProvider().getDefaultsDescriptor() != null && _wrapper.getOSGiAppProvider().getDefaultsDescriptor().length() != 0)
{
- ((WebAppContext)context).setDefaultsDescriptor(_wrapper.getOSGiAppProvider().getDefaultsDescriptor());
+ ((WebAppContext) context).setDefaultsDescriptor(_wrapper.getOSGiAppProvider().getDefaultsDescriptor());
}
}
@@ -775,13 +779,12 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
{
if (context instanceof WebAppContext)
{
- WebAppContext webappCtxt = (WebAppContext)context;
+ WebAppContext webappCtxt = (WebAppContext) context;
context.setClassLoader(webappClassLoader);
webappClassLoader.setWebappContext(webappCtxt);
String pathsToRequiredBundles = getPathsToRequiredBundles(context, requireTldBundle);
- if (pathsToRequiredBundles != null)
- webappClassLoader.addClassPath(pathsToRequiredBundles);
+ if (pathsToRequiredBundles != null) webappClassLoader.addClassPath(pathsToRequiredBundles);
}
else
{
@@ -797,20 +800,20 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
// we use a temporary WebAppContext object.
// if this is a real webapp we will set it on it a bit later: once we
// know.
- OSGiWebappClassLoader webappClassLoader = new OSGiWebappClassLoader(
- _wrapper.getParentClassLoaderForWebapps(),new WebAppContext(),contributor,BUNDLE_CLASS_LOADER_HELPER);
- /* DEBUG
- try {
- Class c = webappClassLoader.loadClass("org.glassfish.jsp.api.ResourceInjector");
- System.err.println("LOADED org.glassfish.jsp.api.ResourceInjector from "+c.getClassLoader());
- }
- catch (Exception e) {e.printStackTrace();}
- try {
- Class c = webappClassLoader.loadClass("org.apache.jasper.xmlparser.ParserUtils");
- System.err.println("LOADED org.apache.jasper.xmlparser.ParserUtils from "+c.getClassLoader());
- }
- catch (Exception e) {e.printStackTrace();}
- */
+ OSGiWebappClassLoader webappClassLoader = new OSGiWebappClassLoader(_wrapper.getParentClassLoaderForWebapps(), new WebAppContext(), contributor,
+ BUNDLE_CLASS_LOADER_HELPER);
+ /*
+ * DEBUG try { Class c =
+ * webappClassLoader.loadClass("org.glassfish.jsp.api.ResourceInjector"
+ * );
+ * System.err.println("LOADED org.glassfish.jsp.api.ResourceInjector from "
+ * +c.getClassLoader()); } catch (Exception e) {e.printStackTrace();}
+ * try { Class c =
+ * webappClassLoader.loadClass("org.apache.jasper.xmlparser.ParserUtils"
+ * );
+ * System.err.println("LOADED org.apache.jasper.xmlparser.ParserUtils from "
+ * +c.getClassLoader()); } catch (Exception e) {e.printStackTrace();}
+ */
return webappClassLoader;
}
@@ -823,10 +826,9 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
{
try
{
- File location = overrideBundleInstallLocation != null?new File(overrideBundleInstallLocation):BUNDLE_FILE_LOCATOR_HELPER
- .getBundleInstallLocation(bundle);
- properties.put("this.bundle.install",location.getCanonicalPath());
- properties.put("this.bundle.install.url",bundle.getEntry("/").toString());
+ File location = overrideBundleInstallLocation != null ? new File(overrideBundleInstallLocation) : BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(bundle);
+ properties.put("this.bundle.install", location.getCanonicalPath());
+ properties.put("this.bundle.install.url", bundle.getEntry("/").toString());
}
catch (Throwable t)
{
@@ -834,36 +836,30 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
}
}
-
- private String getPathsToRequiredBundles (ContextHandler context, String requireTldBundle) throws Exception
+ private String getPathsToRequiredBundles(ContextHandler context, String requireTldBundle) throws Exception
{
- if (requireTldBundle == null)
- return null;
+ if (requireTldBundle == null) return null;
StringBuilder paths = new StringBuilder();
- Bundle bundle = (Bundle)context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE);
+ Bundle bundle = (Bundle) context.getAttribute(OSGiWebappConstants.JETTY_OSGI_BUNDLE);
PackageAdmin packAdmin = getBundleAdmin();
DefaultFileLocatorHelper fileLocatorHelper = new DefaultFileLocatorHelper();
-
+
String[] symbNames = requireTldBundle.split(", ");
for (String symbName : symbNames)
{
Bundle[] bs = packAdmin.getBundles(symbName, null);
- if (bs == null || bs.length == 0)
- {
- throw new IllegalArgumentException("Unable to locate the bundle '"
- + symbName + "' specified in the "
- + OSGiWebappConstants.REQUIRE_TLD_BUNDLE
- + " of the manifest of "
- + bundle.getSymbolicName());
- }
+ if (bs == null || bs.length == 0) { throw new IllegalArgumentException("Unable to locate the bundle '" + symbName
+ + "' specified in the "
+ + OSGiWebappConstants.REQUIRE_TLD_BUNDLE
+ + " of the manifest of "
+ + bundle.getSymbolicName()); }
-
File f = fileLocatorHelper.getBundleInstallLocation(bs[0]);
- if (paths.length() > 0)
+ if (paths.length() > 0)
paths.append(", ");
- System.err.println("getPathsToRequiredBundles: bundle path="+bs[0].getLocation()+" uri="+f.toURI());
+ __logger.debug("getPathsToRequiredBundles: bundle path=" + bs[0].getLocation() + " uri=" + f.toURI());
paths.append(f.toURI().toURL().toString());
}
@@ -872,12 +868,11 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
private PackageAdmin getBundleAdmin()
{
- Bundle bootBundle = ((BundleReference)OSGiWebappConstants.class.getClassLoader()).getBundle();
+ Bundle bootBundle = ((BundleReference) OSGiWebappConstants.class.getClassLoader()).getBundle();
ServiceTracker serviceTracker = new ServiceTracker(bootBundle.getBundleContext(), PackageAdmin.class.getName(), null);
serviceTracker.open();
return (PackageAdmin) serviceTracker.getService();
}
-
}
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleTrackerCustomizer.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleTrackerCustomizer.java
index 3cfea34c932..79938415305 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleTrackerCustomizer.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleTrackerCustomizer.java
@@ -24,7 +24,6 @@ import org.osgi.framework.BundleEvent;
import org.osgi.util.tracker.BundleTracker;
import org.osgi.util.tracker.BundleTrackerCustomizer;
-
/**
* Support bundles that declare the webapp directly through headers in their
* manifest.
@@ -49,133 +48,132 @@ import org.osgi.util.tracker.BundleTrackerCustomizer;
*
* @author hmalphettes
*/
-public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer {
+public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer
+{
private static final Logger LOG = Log.getLogger(WebBundleTrackerCustomizer.class);
-
+ /**
+ * A bundle is being added to the BundleTracker
.
+ *
+ *
+ * This method is called before a bundle which matched the search parameters
+ * of the BundleTracker
is added to the
+ * BundleTracker
. This method should return the object to be
+ * tracked for the specified Bundle
. The returned object is
+ * stored in the BundleTracker
and is available from the
+ * {@link BundleTracker#getObject(Bundle) getObject} method.
+ *
+ * @param bundle The Bundle
being added to the
+ * BundleTracker
.
+ * @param event The bundle event which caused this customizer method to be
+ * called or null
if there is no bundle event
+ * associated with the call to this method.
+ * @return The object to be tracked for the specified Bundle
+ * object or null
if the specified Bundle
+ * object should not be tracked.
+ */
+ public Object addingBundle(Bundle bundle, BundleEvent event)
+ {
+ if (bundle.getState() == Bundle.ACTIVE)
+ {
+ boolean isWebBundle = register(bundle);
+ return isWebBundle ? bundle : null;
+ }
+ else if (bundle.getState() == Bundle.STOPPING)
+ {
+ unregister(bundle);
+ }
+ else
+ {
+ // we should not be called in that state as
+ // we are registered only for ACTIVE and STOPPING
+ }
+ return null;
+ }
- /**
- * A bundle is being added to the BundleTracker
.
- *
- *
- * This method is called before a bundle which matched the search parameters
- * of the BundleTracker
is added to the
- * BundleTracker
. This method should return the object to be
- * tracked for the specified Bundle
. The returned object is
- * stored in the BundleTracker
and is available from the
- * {@link BundleTracker#getObject(Bundle) getObject} method.
- *
- * @param bundle The Bundle
being added to the
- * BundleTracker
.
- * @param event The bundle event which caused this customizer method to be
- * called or null
if there is no bundle event associated
- * with the call to this method.
- * @return The object to be tracked for the specified Bundle
- * object or null
if the specified Bundle
- * object should not be tracked.
- */
- public Object addingBundle(Bundle bundle, BundleEvent event)
- {
- if (bundle.getState() == Bundle.ACTIVE)
- {
- boolean isWebBundle = register(bundle);
- return isWebBundle ? bundle : null;
- }
- else if (bundle.getState() == Bundle.STOPPING)
- {
- unregister(bundle);
- }
- else
- {
- //we should not be called in that state as
- //we are registered only for ACTIVE and STOPPING
- }
- return null;
- }
+ /**
+ * A bundle tracked by the BundleTracker
has been modified.
+ *
+ *
+ * This method is called when a bundle being tracked by the
+ * BundleTracker
has had its state modified.
+ *
+ * @param bundle The Bundle
whose state has been modified.
+ * @param event The bundle event which caused this customizer method to be
+ * called or null
if there is no bundle event
+ * associated with the call to this method.
+ * @param object The tracked object for the specified bundle.
+ */
+ public void modifiedBundle(Bundle bundle, BundleEvent event, Object object)
+ {
+ // nothing the web-bundle was already track. something changed.
+ // we only reload the webapps if the bundle is stopped and restarted.
+ if (bundle.getState() == Bundle.STOPPING || bundle.getState() == Bundle.ACTIVE)
+ {
+ unregister(bundle);
+ }
+ if (bundle.getState() == Bundle.ACTIVE)
+ {
+ register(bundle);
+ }
+ }
- /**
- * A bundle tracked by the BundleTracker
has been modified.
- *
- *
- * This method is called when a bundle being tracked by the
- * BundleTracker
has had its state modified.
- *
- * @param bundle The Bundle
whose state has been modified.
- * @param event The bundle event which caused this customizer method to be
- * called or null
if there is no bundle event associated
- * with the call to this method.
- * @param object The tracked object for the specified bundle.
- */
- public void modifiedBundle(Bundle bundle, BundleEvent event,
- Object object)
- {
- //nothing the web-bundle was already track. something changed.
- //we only reload the webapps if the bundle is stopped and restarted.
-// System.err.println(bundle.getSymbolicName());
- if (bundle.getState() == Bundle.STOPPING || bundle.getState() == Bundle.ACTIVE)
- {
- unregister(bundle);
- }
- if (bundle.getState() == Bundle.ACTIVE)
- {
- register(bundle);
- }
- }
+ /**
+ * A bundle tracked by the BundleTracker
has been removed.
+ *
+ *
+ * This method is called after a bundle is no longer being tracked by the
+ * BundleTracker
.
+ *
+ * @param bundle The Bundle
that has been removed.
+ * @param event The bundle event which caused this customizer method to be
+ * called or null
if there is no bundle event
+ * associated with the call to this method.
+ * @param object The tracked object for the specified bundle.
+ */
+ public void removedBundle(Bundle bundle, BundleEvent event, Object object)
+ {
+ unregister(bundle);
+ }
- /**
- * A bundle tracked by the BundleTracker
has been removed.
- *
- *
- * This method is called after a bundle is no longer being tracked by the
- * BundleTracker
.
- *
- * @param bundle The Bundle
that has been removed.
- * @param event The bundle event which caused this customizer method to be
- * called or null
if there is no bundle event associated
- * with the call to this method.
- * @param object The tracked object for the specified bundle.
- */
- public void removedBundle(Bundle bundle, BundleEvent event,
- Object object)
- {
- unregister(bundle);
- }
-
-
- /**
- * @param bundle
- * @return true if this bundle in indeed a web-bundle.
- */
+ /**
+ * @param bundle
+ * @return true if this bundle in indeed a web-bundle.
+ */
private boolean register(Bundle bundle)
{
Dictionary, ?> dic = bundle.getHeaders();
- String warFolderRelativePath = (String)dic.get(OSGiWebappConstants.JETTY_WAR_FOLDER_PATH);
+ String warFolderRelativePath = (String) dic.get(OSGiWebappConstants.JETTY_WAR_FOLDER_PATH);
if (warFolderRelativePath != null)
{
- String contextPath = getWebContextPath(bundle, dic, false);//(String)dic.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH);
+ String contextPath = getWebContextPath(bundle, dic, false);// (String)dic.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH);
if (contextPath == null || !contextPath.startsWith("/"))
{
- LOG.warn("The manifest header '" + OSGiWebappConstants.JETTY_WAR_FOLDER_PATH +
- ": " + warFolderRelativePath + "' in the bundle " + bundle.getSymbolicName() +
- " is not valid: there is no Web-ContextPath defined in the manifest.");
- return false;
+ LOG.warn("The manifest header '" + OSGiWebappConstants.JETTY_WAR_FOLDER_PATH
+ + ": "
+ + warFolderRelativePath
+ + "' in the bundle "
+ + bundle.getSymbolicName()
+ + " is not valid: there is no Web-ContextPath defined in the manifest.");
+ return false;
}
// create the corresponding service and publish it in the context of
// the contributor bundle.
try
{
- JettyBootstrapActivator.registerWebapplication(bundle,warFolderRelativePath,contextPath);
+ JettyBootstrapActivator.registerWebapplication(bundle, warFolderRelativePath, contextPath);
return true;
}
catch (Throwable e)
{
- LOG.warn("Starting the web-bundle " + bundle.getSymbolicName() + " threw an exception.", e);
- return true;//maybe it did not work maybe it did. safer to track this bundle.
+ LOG.warn("Starting the web-bundle " + bundle.getSymbolicName() + " threw an exception.", e);
+ return true;// maybe it did not work maybe it did. safer to
+ // track this bundle.
}
}
else if (dic.get(OSGiWebappConstants.JETTY_CONTEXT_FILE_PATH) != null)
{
- String contextFileRelativePath = (String)dic.get(OSGiWebappConstants.JETTY_CONTEXT_FILE_PATH);
+ String contextFileRelativePath = (String) dic.get(OSGiWebappConstants.JETTY_CONTEXT_FILE_PATH);
if (contextFileRelativePath == null)
{
// nothing to register here.
@@ -187,7 +185,7 @@ public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer {
{
try
{
- JettyBootstrapActivator.registerContext(bundle,path.trim());
+ JettyBootstrapActivator.registerContext(bundle, path.trim());
}
catch (Throwable e)
{
@@ -203,8 +201,8 @@ public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer {
// (draft) of the spec: just a couple of posts on the
// world-wide-web.
URL rfc66Webxml = bundle.getEntry("/WEB-INF/web.xml");
- if (rfc66Webxml == null && dic.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH) == null)
- {
+ if (rfc66Webxml == null && dic.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH) == null)
+ {
return false;// no webapp in here
}
// this is risky: should we make sure that there is no classes and
@@ -215,42 +213,41 @@ public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer {
// pointing to files and folders inside WEB-INF. We should
// filter-out
// META-INF too
- String rfc66ContextPath = getWebContextPath(bundle,dic,rfc66Webxml==null);
+ String rfc66ContextPath = getWebContextPath(bundle, dic, rfc66Webxml == null);
try
{
- JettyBootstrapActivator.registerWebapplication(bundle,".",rfc66ContextPath);
+ JettyBootstrapActivator.registerWebapplication(bundle, ".", rfc66ContextPath);
return true;
}
catch (Throwable e)
{
// TODO Auto-generated catch block
e.printStackTrace();
- return true;//maybe it did not work maybe it did. safer to track this bundle.
+ return true;// maybe it did not work maybe it did. safer to
+ // track this bundle.
}
}
}
private String getWebContextPath(Bundle bundle, Dictionary, ?> dic, boolean webinfWebxmlExists)
{
- String rfc66ContextPath = (String)dic.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH);
+ String rfc66ContextPath = (String) dic.get(OSGiWebappConstants.RFC66_WEB_CONTEXTPATH);
if (rfc66ContextPath == null)
{
- if (!webinfWebxmlExists) {
- return null;
- }
+ if (!webinfWebxmlExists) { return null; }
// extract from the last token of the bundle's location:
// (really ?
// could consider processing the symbolic name as an alternative
// the location will often reflect the version.
// maybe this is relevant when the file is a war)
String location = bundle.getLocation();
- String toks[] = location.replace('\\','/').split("/");
+ String toks[] = location.replace('\\', '/').split("/");
rfc66ContextPath = toks[toks.length - 1];
// remove .jar, .war etc:
int lastDot = rfc66ContextPath.lastIndexOf('.');
if (lastDot != -1)
{
- rfc66ContextPath = rfc66ContextPath.substring(0,lastDot);
+ rfc66ContextPath = rfc66ContextPath.substring(0, lastDot);
}
}
if (!rfc66ContextPath.startsWith("/"))
@@ -259,7 +256,7 @@ public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer {
}
return rfc66ContextPath;
}
-
+
private void unregister(Bundle bundle)
{
// nothing to do: when the bundle is stopped, each one of its service
@@ -268,7 +265,4 @@ public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer {
// webapps registered in that bundle.
}
-
-
-
}
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java
index 73b127cd637..7858e574243 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java
@@ -25,6 +25,7 @@ import java.util.zip.ZipFile;
import org.eclipse.jetty.osgi.boot.utils.BundleFileLocatorHelper;
import org.eclipse.jetty.util.URIUtil;
+import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.FileResource;
import org.osgi.framework.Bundle;
@@ -43,11 +44,13 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
// The url nuxeo and felix return is created directly from the File so it
// should work.
private static Field BUNDLE_ENTRY_FIELD = null;
+
private static Field FILE_FIELD = null;
private static Field BUNDLE_FILE_FIELD_FOR_DIR_ZIP_BUNDLE_ENTRY = null;// ZipBundleFile
- // inside
- // DirZipBundleEntry
+
+ // inside
+ // DirZipBundleEntry
private static Field ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE = null;// ZipFile
@@ -56,8 +59,7 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
* spirit of OSGi but quite necessary to support self-contained webapps and
* other situations.
*
- * @param bundle
- * The bundle
+ * @param bundle The bundle
* @return Its installation location as a file.
* @throws Exception
*/
@@ -67,19 +69,23 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
// grab the MANIFEST.MF's url
// and then do what it takes.
URL url = bundle.getEntry("/META-INF/MANIFEST.MF");
-// System.err.println(url.toString() + " " + url.toURI() + " " + url.getProtocol());
+ //System.err.println(url.toString() + " " + url.toURI() + " " + url.getProtocol());
if (url.getProtocol().equals("file"))
{
// some osgi frameworks do use the file protocole directly in some
- // situations. Do use the FileResource to transform the URL into a File: URL#toURI is broken
- return new FileResource(url).getFile().getParentFile().getParentFile();
+ // situations. Do use the FileResource to transform the URL into a
+ // File: URL#toURI is broken
+ return new FileResource(url).getFile().getParentFile().getParentFile();
}
else if (url.getProtocol().equals("bundleentry"))
{
// say hello to equinox who has its own protocol.
// we use introspection like there is no tomorrow to get access to
// the File
+
URLConnection con = url.openConnection();
+ con.setUseCaches(Resource.getDefaultUseCaches()); //work around problems where url connections cache references to jars
+
if (BUNDLE_ENTRY_FIELD == null)
{
BUNDLE_ENTRY_FIELD = con.getClass().getDeclaredField("bundleEntry");
@@ -93,13 +99,16 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
FILE_FIELD = bundleEntry.getClass().getDeclaredField("file");
FILE_FIELD.setAccessible(true);
}
- File f = (File)FILE_FIELD.get(bundleEntry);
+ File f = (File) FILE_FIELD.get(bundleEntry);
return f.getParentFile().getParentFile();
}
else if (bundleEntry.getClass().getName().equals("org.eclipse.osgi.baseadaptor.bundlefile.ZipBundleEntry"))
{
url = bundle.getEntry("/");
+
con = url.openConnection();
+ con.setDefaultUseCaches(Resource.getDefaultUseCaches());
+
if (BUNDLE_ENTRY_FIELD == null)
{// this one will be a DirZipBundleEntry
BUNDLE_ENTRY_FIELD = con.getClass().getDeclaredField("bundleEntry");
@@ -117,7 +126,7 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE = zipBundleFile.getClass().getDeclaredField("zipFile");
ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE.setAccessible(true);
}
- ZipFile zipFile = (ZipFile)ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE.get(zipBundleFile);
+ ZipFile zipFile = (ZipFile) ZIP_FILE_FILED_FOR_ZIP_BUNDLE_FILE.get(zipBundleFile);
return new File(zipFile.getName());
}
else if (bundleEntry.getClass().getName().equals("org.eclipse.osgi.baseadaptor.bundlefile.DirZipBundleEntry"))
@@ -130,7 +139,7 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
{
// observed this on felix-2.0.0
String location = bundle.getLocation();
-// System.err.println("location " + location);
+ // System.err.println("location " + location);
if (location.startsWith("file:/"))
{
URI uri = new URI(URIUtil.encodePath(location));
@@ -138,27 +147,32 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
}
else if (location.startsWith("file:"))
{
- //location defined in the BundleArchive m_bundleArchive
- //it is relative to relative to the BundleArchive's m_archiveRootDir
- File res = new File(location.substring("file:".length()));
- if (!res.exists())
- {
- return null;
-// Object bundleArchive = getFelixBundleArchive(bundle);
-// File archiveRoot = getFelixBundleArchiveRootDir(bundleArchive);
-// String currentLocation = getFelixBundleArchiveCurrentLocation(bundleArchive);
-// System.err.println("Got the archive root " + archiveRoot.getAbsolutePath()
-// + " current location " + currentLocation + " is directory ?");
-// res = new File(archiveRoot, currentLocation != null
-// ? currentLocation : location.substring("file:".length()));
- }
- return res;
+ // location defined in the BundleArchive m_bundleArchive
+ // it is relative to relative to the BundleArchive's
+ // m_archiveRootDir
+ File res = new File(location.substring("file:".length()));
+ if (!res.exists())
+ {
+ return null;
+ // Object bundleArchive = getFelixBundleArchive(bundle);
+ // File archiveRoot =
+ // getFelixBundleArchiveRootDir(bundleArchive);
+ // String currentLocation =
+ // getFelixBundleArchiveCurrentLocation(bundleArchive);
+ // System.err.println("Got the archive root " +
+ // archiveRoot.getAbsolutePath()
+ // + " current location " + currentLocation +
+ // " is directory ?");
+ // res = new File(archiveRoot, currentLocation != null
+ // ? currentLocation : location.substring("file:".length()));
+ }
+ return res;
}
else if (location.startsWith("reference:file:"))
{
- location = URLDecoder.decode(location.substring("reference:".length()), "UTF-8");
- File file = new File(location.substring("file:".length()));
- return file;
+ location = URLDecoder.decode(location.substring("reference:".length()), "UTF-8");
+ File file = new File(location.substring("file:".length()));
+ return file;
}
}
return null;
@@ -179,37 +193,40 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
path = path.substring(1);
}
File bundleInstall = getBundleInstallLocation(bundle);
- File webapp = path != null && path.length() != 0?new File(bundleInstall,path):bundleInstall;
- if (!webapp.exists())
- {
- throw new IllegalArgumentException("Unable to locate " + path + " inside " + bundle.getSymbolicName() + " ("
- + (bundleInstall != null?bundleInstall.getAbsolutePath():" no_bundle_location ") + ")");
+ File webapp = path != null && path.length() != 0 ? new File(bundleInstall, path) : bundleInstall;
+ if (!webapp.exists())
+ {
+ throw new IllegalArgumentException("Unable to locate " + path
+ + " inside "
+ + bundle.getSymbolicName()
+ + " ("
+ + (bundleInstall != null ? bundleInstall.getAbsolutePath() : " no_bundle_location ")
+ + ")");
}
return webapp;
}
-
+
/**
- * Helper method equivalent to Bundle#getEntry(String entryPath) except that
- * it searches for entries in the fragments by using the Bundle#findEntries method.
- *
- * @param bundle
- * @param entryPath
- * @return null or all the entries found for that path.
- */
- public Enumeration findEntries(Bundle bundle, String entryPath)
- {
- int last = entryPath.lastIndexOf('/');
- String path = last != -1 && last < entryPath.length() -2
- ? entryPath.substring(0, last) : "/";
- if (!path.startsWith("/"))
- {
- path = "/" + path;
- }
- String pattern = last != -1 && last < entryPath.length() -2
- ? entryPath.substring(last+1) : entryPath;
- Enumeration enUrls = bundle.findEntries(path, pattern, false);
- return enUrls;
- }
+ * Helper method equivalent to Bundle#getEntry(String entryPath) except that
+ * it searches for entries in the fragments by using the Bundle#findEntries
+ * method.
+ *
+ * @param bundle
+ * @param entryPath
+ * @return null or all the entries found for that path.
+ */
+ public Enumeration findEntries(Bundle bundle, String entryPath)
+ {
+ int last = entryPath.lastIndexOf('/');
+ String path = last != -1 && last < entryPath.length() - 2 ? entryPath.substring(0, last) : "/";
+ if (!path.startsWith("/"))
+ {
+ path = "/" + path;
+ }
+ String pattern = last != -1 && last < entryPath.length() - 2 ? entryPath.substring(last + 1) : entryPath;
+ Enumeration enUrls = bundle.findEntries(path, pattern, false);
+ return enUrls;
+ }
/**
* If the bundle is a jar, returns the jar. If the bundle is a folder, look
@@ -256,76 +273,84 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
return new File[] { jasperLocation };
}
}
-
- //introspection on equinox to invoke the getLocalURL method on BundleURLConnection
- //equivalent to using the FileLocator without depending on an equinox class.
- private static Method BUNDLE_URL_CONNECTION_getLocalURL = null;
- private static Method BUNDLE_URL_CONNECTION_getFileURL = null;
- /**
- * Only useful for equinox: on felix we get the file:// or jar:// url already.
- * Other OSGi implementations have not been tested
- *
- * Get a URL to the bundle entry that uses a common protocol (i.e. file:
- * jar: or http: etc.).
- *
- * @return a URL to the bundle entry that uses a common protocol
- */
- public static URL getLocalURL(URL url) {
- if ("bundleresource".equals(url.getProtocol()) || "bundleentry".equals(url.getProtocol())) {
- try {
- URLConnection conn = url.openConnection();
- if (BUNDLE_URL_CONNECTION_getLocalURL == null &&
- conn.getClass().getName().equals(
- "org.eclipse.osgi.framework.internal.core.BundleURLConnection")) {
- BUNDLE_URL_CONNECTION_getLocalURL = conn.getClass().getMethod("getLocalURL", null);
- BUNDLE_URL_CONNECTION_getLocalURL.setAccessible(true);
- }
- if (BUNDLE_URL_CONNECTION_getLocalURL != null) {
- return (URL)BUNDLE_URL_CONNECTION_getLocalURL.invoke(conn, null);
- }
- } catch (Throwable t) {
- System.err.println("Unable to locate the OSGi url: '" + url + "'.");
- t.printStackTrace();
- }
- }
- return url;
- }
- /**
- * Only useful for equinox: on felix we get the file:// url already.
- * Other OSGi implementations have not been tested
- *
- * Get a URL to the content of the bundle entry that uses the file: protocol.
- * The content of the bundle entry may be downloaded or extracted to the local
- * file system in order to create a file: URL.
- * @return a URL to the content of the bundle entry that uses the file: protocol
- *
- */
- public static URL getFileURL(URL url)
- {
- if ("bundleresource".equals(url.getProtocol()) || "bundleentry".equals(url.getProtocol()))
- {
- try
- {
- URLConnection conn = url.openConnection();
- if (BUNDLE_URL_CONNECTION_getFileURL == null &&
- conn.getClass().getName().equals(
- "org.eclipse.osgi.framework.internal.core.BundleURLConnection"))
- {
- BUNDLE_URL_CONNECTION_getFileURL = conn.getClass().getMethod("getFileURL", null);
- BUNDLE_URL_CONNECTION_getFileURL.setAccessible(true);
- }
- if (BUNDLE_URL_CONNECTION_getFileURL != null)
- {
- return (URL)BUNDLE_URL_CONNECTION_getFileURL.invoke(conn, null);
- }
- }
- catch (Throwable t)
- {
- t.printStackTrace();
- }
- }
- return url;
- }
+ // introspection on equinox to invoke the getLocalURL method on
+ // BundleURLConnection
+ // equivalent to using the FileLocator without depending on an equinox
+ // class.
+ private static Method BUNDLE_URL_CONNECTION_getLocalURL = null;
+
+ private static Method BUNDLE_URL_CONNECTION_getFileURL = null;
+
+ /**
+ * Only useful for equinox: on felix we get the file:// or jar:// url
+ * already. Other OSGi implementations have not been tested
+ *
+ * Get a URL to the bundle entry that uses a common protocol (i.e. file:
+ * jar: or http: etc.).
+ *
+ *
+ * @return a URL to the bundle entry that uses a common protocol
+ */
+ public static URL getLocalURL(URL url)
+ {
+ if ("bundleresource".equals(url.getProtocol()) || "bundleentry".equals(url.getProtocol()))
+ {
+ try
+ {
+ URLConnection conn = url.openConnection();
+ conn.setDefaultUseCaches(Resource.getDefaultUseCaches());
+ if (BUNDLE_URL_CONNECTION_getLocalURL == null && conn.getClass().getName()
+ .equals("org.eclipse.osgi.framework.internal.core.BundleURLConnection"))
+ {
+ BUNDLE_URL_CONNECTION_getLocalURL = conn.getClass().getMethod("getLocalURL", null);
+ BUNDLE_URL_CONNECTION_getLocalURL.setAccessible(true);
+ }
+ if (BUNDLE_URL_CONNECTION_getLocalURL != null) { return (URL) BUNDLE_URL_CONNECTION_getLocalURL.invoke(conn, null); }
+ }
+ catch (Throwable t)
+ {
+ System.err.println("Unable to locate the OSGi url: '" + url + "'.");
+ t.printStackTrace();
+ }
+ }
+ return url;
+ }
+
+ /**
+ * Only useful for equinox: on felix we get the file:// url already. Other
+ * OSGi implementations have not been tested
+ *
+ * Get a URL to the content of the bundle entry that uses the file:
+ * protocol. The content of the bundle entry may be downloaded or extracted
+ * to the local file system in order to create a file: URL.
+ *
+ * @return a URL to the content of the bundle entry that uses the file:
+ * protocol
+ *
+ */
+ public static URL getFileURL(URL url)
+ {
+ if ("bundleresource".equals(url.getProtocol()) || "bundleentry".equals(url.getProtocol()))
+ {
+ try
+ {
+ URLConnection conn = url.openConnection();
+ conn.setDefaultUseCaches(Resource.getDefaultUseCaches());
+ if (BUNDLE_URL_CONNECTION_getFileURL == null && conn.getClass().getName()
+ .equals("org.eclipse.osgi.framework.internal.core.BundleURLConnection"))
+ {
+ BUNDLE_URL_CONNECTION_getFileURL = conn.getClass().getMethod("getFileURL", null);
+ BUNDLE_URL_CONNECTION_getFileURL.setAccessible(true);
+ }
+ if (BUNDLE_URL_CONNECTION_getFileURL != null) { return (URL) BUNDLE_URL_CONNECTION_getFileURL.invoke(conn, null); }
+ }
+ catch (Throwable t)
+ {
+ t.printStackTrace();
+ }
+ }
+ return url;
+ }
}
From 50f545b29a0227cbd78e05d9b8b10ca2c4e985b4 Mon Sep 17 00:00:00 2001
From: Simone Bordet
Date: Wed, 4 Apr 2012 19:21:16 +0200
Subject: [PATCH 22/36] Vastly improved queueing of FrameBytes, by appending at
the end of the queue (instead of iterating over the queue). Also, implemented
a better fix for the missing flush() in case of missing handlers: now instead
of flushing in the write completion handler (which could lead to stack
overflows), we use the same mechanism employed for FrameBytes, where we avoid
stack overflows by dispatching to a new thread after few recursive
invocations.
---
.../eclipse/jetty/spdy/StandardSession.java | 74 ++++++++++---------
1 file changed, 39 insertions(+), 35 deletions(-)
diff --git a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java
index ecf5deb1fed..dae08a4c4cd 100644
--- a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java
+++ b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java
@@ -820,15 +820,21 @@ public class StandardSession implements ISession, Parser.Listener, Handler 0)
+ {
+ FrameBytes element = queue.get(index - 1);
+ if (element.compareTo(frameBytes) >= 0)
+ break;
+ --index;
+ }
+ queue.add(index, frameBytes);
+ }
}
private void prepend(FrameBytes frameBytes)
- {
- enqueue(frameBytes, true);
- }
-
- private void enqueue(FrameBytes frameBytes, boolean prepend)
{
synchronized (queue)
{
@@ -836,8 +842,7 @@ public class StandardSession implements ISession, Parser.Listener, Handler 0 || prepend && comparison == 0)
+ if (element.compareTo(frameBytes) <= 0)
break;
++index;
}
@@ -854,7 +859,6 @@ public class StandardSession implements ISession, Parser.Listener, Handler void complete(final Handler handler, final C context)
{
- if (handler != null)
+ // Applications may send and queue up a lot of frames and
+ // if we call Handler.completed() only synchronously we risk
+ // starvation (for the last frames sent) and stack overflow.
+ // Therefore every some invocation, we dispatch to a new thread
+ Integer invocations = handlerInvocations.get();
+ if (invocations >= 4)
{
- // Applications may send and queue up a lot of frames and
- // if we call Handler.completed() only synchronously we risk
- // starvation (for the last frames sent) and stack overflow.
- // Therefore every some invocation, we dispatch to a new thread
- Integer invocations = handlerInvocations.get();
- if (invocations >= 4)
+ execute(new Runnable()
{
- execute(new Runnable()
+ @Override
+ public void run()
{
- @Override
- public void run()
- {
+ if (handler != null)
notifyHandlerCompleted(handler, context);
- flush();
- }
- });
- }
- else
- {
- handlerInvocations.set(invocations + 1);
- try
- {
- notifyHandlerCompleted(handler, context);
flush();
}
- finally
- {
- handlerInvocations.set(invocations);
- }
+ });
+ }
+ else
+ {
+ handlerInvocations.set(invocations + 1);
+ try
+ {
+ if (handler != null)
+ notifyHandlerCompleted(handler, context);
+ flush();
+ }
+ finally
+ {
+ handlerInvocations.set(invocations);
}
}
}
@@ -967,7 +970,8 @@ public class StandardSession implements ISession, Parser.Listener, Handler that.stream.priority => -1 (this.stream has less priority than that.stream)
+ return that.getStream().getPriority() - getStream().getPriority();
}
@Override
From d47d4b15ea09f7a0b33ea9121198717bc00cc512 Mon Sep 17 00:00:00 2001
From: Jan Bartel
Date: Thu, 5 Apr 2012 17:34:00 +1000
Subject: [PATCH 23/36] Added ability to use a
META-INF/jetty-webapp-context.xml file to apply a context configuration file
to a webapp. Replaced more printStackTrace with log calls; more formatting.
---
.../jetty/osgi/boot/OSGiAppProvider.java | 6 +-
.../DefaultJettyAtJettyHomeHelper.java | 15 +++--
.../JettyContextHandlerServiceTracker.java | 13 ++--
.../webapp/WebBundleDeployerHelper.java | 65 +++++++++++++------
.../webapp/WebBundleTrackerCustomizer.java | 12 ++--
.../internal/DefaultFileLocatorHelper.java | 2 +-
6 files changed, 70 insertions(+), 43 deletions(-)
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiAppProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiAppProvider.java
index 34fd8c74db4..510c09e8b67 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiAppProvider.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiAppProvider.java
@@ -349,7 +349,7 @@ public class OSGiAppProvider extends ScanningAppProvider implements AppProvider
}
catch (IOException e)
{
- e.printStackTrace();
+ LOG.warn(e);
return null;
}
}
@@ -370,11 +370,11 @@ public class OSGiAppProvider extends ScanningAppProvider implements AppProvider
}
catch (IOException e)
{
- e.printStackTrace();
+ LOG.warn(e);
return null;
}
}
-
+
public boolean isExtract()
{
return _extractWars;
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/DefaultJettyAtJettyHomeHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/DefaultJettyAtJettyHomeHelper.java
index d8491eeacbe..17ea8d22cc7 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/DefaultJettyAtJettyHomeHelper.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/serverfactory/DefaultJettyAtJettyHomeHelper.java
@@ -167,18 +167,21 @@ public class DefaultJettyAtJettyHomeHelper {
*/
private static String getJettyConfigurationURLs(File jettyhome)
{
- String jettyetc = System.getProperty(SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml");
- StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,", false);
+ String jettyetc = System.getProperty(SYS_PROP_JETTY_ETC_FILES, "etc/jetty.xml");
+ StringTokenizer tokenizer = new StringTokenizer(jettyetc, ";,", false);
StringBuilder res = new StringBuilder();
while (tokenizer.hasMoreTokens())
{
String next = tokenizer.nextToken().trim();
if (!next.startsWith("/") && next.indexOf(':') == -1)
{
- try {
+ try
+ {
next = new File(jettyhome, next).toURI().toURL().toString();
- } catch (MalformedURLException e) {
- e.printStackTrace();
+ }
+ catch (MalformedURLException e)
+ {
+ LOG.warn(e);
continue;
}
}
@@ -225,7 +228,7 @@ public class DefaultJettyAtJettyHomeHelper {
}
if (enUrls == null || !enUrls.hasMoreElements())
{
- System.err.println("Unable to locate a jetty configuration file for " + etcFile);
+ LOG.warn("Unable to locate a jetty configuration file for " + etcFile);
}
if (enUrls != null)
{
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/JettyContextHandlerServiceTracker.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/JettyContextHandlerServiceTracker.java
index 26120c1850f..0838a4850ab 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/JettyContextHandlerServiceTracker.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/JettyContextHandlerServiceTracker.java
@@ -24,6 +24,8 @@ import org.eclipse.jetty.osgi.boot.internal.serverfactory.DefaultJettyAtJettyHom
import org.eclipse.jetty.osgi.boot.internal.serverfactory.IManagedJettyServerRegistry;
import org.eclipse.jetty.osgi.boot.internal.serverfactory.ServerInstanceWrapper;
import org.eclipse.jetty.server.handler.ContextHandler;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.Scanner;
import org.eclipse.jetty.webapp.WebAppContext;
import org.osgi.framework.Bundle;
@@ -52,7 +54,8 @@ import org.osgi.framework.ServiceReference;
*/
public class JettyContextHandlerServiceTracker implements ServiceListener
{
-
+ private static Logger __logger = Log.getLogger(WebBundleDeployerHelper.class.getName());
+
/** New style: ability to manage multiple jetty instances */
private final IManagedJettyServerRegistry _registry;
@@ -149,8 +152,7 @@ public class JettyContextHandlerServiceTracker implements ServiceListener
}
catch (Exception e)
{
- // TODO Auto-generated catch block
- e.printStackTrace();
+ __logger.warn(e);
}
}
}
@@ -236,7 +238,7 @@ public class JettyContextHandlerServiceTracker implements ServiceListener
}
catch (Throwable e)
{
- e.printStackTrace();
+ __logger.warn(e);
}
}
else
@@ -270,8 +272,7 @@ public class JettyContextHandlerServiceTracker implements ServiceListener
}
catch (Throwable e)
{
- // TODO Auto-generated catch block
- e.printStackTrace();
+ __logger.warn(e);
}
}
}
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleDeployerHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleDeployerHelper.java
index 97d72cb2c38..a681396910e 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleDeployerHelper.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleDeployerHelper.java
@@ -229,6 +229,11 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
try
{
+
+
+ //apply any META-INF/context.xml file that is found to configure the webapp first
+ applyMetaInfContextXml (contributor, context);
+
// make sure we provide access to all the jetty bundles by going
// through this bundle.
OSGiWebappClassLoader composite = createWebappClassLoader(contributor);
@@ -661,7 +666,7 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
}
catch (FileNotFoundException e)
{
- e.printStackTrace();
+ __logger.warn(e);
}
return null;
}
@@ -726,18 +731,15 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
}
catch (SAXException e)
{
- // TODO Auto-generated catch block
- e.printStackTrace();
+ __logger.warn(e);
}
catch (IOException e)
{
- // TODO Auto-generated catch block
- e.printStackTrace();
+ __logger.warn(e);
}
catch (Throwable e)
{
- // TODO Auto-generated catch block
- e.printStackTrace();
+ __logger.warn(e);
}
finally
{
@@ -802,21 +804,46 @@ public class WebBundleDeployerHelper implements IWebBundleDeployerHelper
// know.
OSGiWebappClassLoader webappClassLoader = new OSGiWebappClassLoader(_wrapper.getParentClassLoaderForWebapps(), new WebAppContext(), contributor,
BUNDLE_CLASS_LOADER_HELPER);
- /*
- * DEBUG try { Class c =
- * webappClassLoader.loadClass("org.glassfish.jsp.api.ResourceInjector"
- * );
- * System.err.println("LOADED org.glassfish.jsp.api.ResourceInjector from "
- * +c.getClassLoader()); } catch (Exception e) {e.printStackTrace();}
- * try { Class c =
- * webappClassLoader.loadClass("org.apache.jasper.xmlparser.ParserUtils"
- * );
- * System.err.println("LOADED org.apache.jasper.xmlparser.ParserUtils from "
- * +c.getClassLoader()); } catch (Exception e) {e.printStackTrace();}
- */
return webappClassLoader;
}
+
+ protected void applyMetaInfContextXml (Bundle bundle, ContextHandler contextHandler)
+ throws Exception
+ {
+ if (bundle == null)
+ return;
+ if (contextHandler == null)
+ return;
+
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ __logger.info("Context classloader = "+cl);
+ try
+ {
+ Thread.currentThread().setContextClassLoader(_wrapper.getParentClassLoaderForWebapps());
+
+ //find if there is a META-INF/context.xml file
+ URL contextXmlUrl = bundle.getEntry("/META-INF/jetty-webapp-context.xml");
+ if (contextXmlUrl == null)
+ return;
+
+ //Apply it just as the standard jetty ContextProvider would do
+ __logger.info("Applying "+contextXmlUrl+" to "+contextHandler);
+
+ XmlConfiguration xmlConfiguration = new XmlConfiguration(contextXmlUrl);
+ HashMap properties = new HashMap();
+ properties.put("Server", _wrapper.getServer());
+ xmlConfiguration.getProperties().putAll(properties);
+ xmlConfiguration.configure(contextHandler);
+ }
+ finally
+ {
+ Thread.currentThread().setContextClassLoader(cl);
+ }
+ }
+
+
+
/**
* Set the property "this.bundle.install" to point to the location
* of the bundle. Useful when is
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleTrackerCustomizer.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleTrackerCustomizer.java
index 79938415305..137c49bb271 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleTrackerCustomizer.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebBundleTrackerCustomizer.java
@@ -167,8 +167,7 @@ public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer
catch (Throwable e)
{
LOG.warn("Starting the web-bundle " + bundle.getSymbolicName() + " threw an exception.", e);
- return true;// maybe it did not work maybe it did. safer to
- // track this bundle.
+ return true;// maybe it did not work maybe it did. safer to track this bundle.
}
}
else if (dic.get(OSGiWebappConstants.JETTY_CONTEXT_FILE_PATH) != null)
@@ -189,8 +188,7 @@ public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer
}
catch (Throwable e)
{
- // TODO Auto-generated catch block
- e.printStackTrace();
+ LOG.warn(e);
}
}
return true;
@@ -221,10 +219,8 @@ public class WebBundleTrackerCustomizer implements BundleTrackerCustomizer
}
catch (Throwable e)
{
- // TODO Auto-generated catch block
- e.printStackTrace();
- return true;// maybe it did not work maybe it did. safer to
- // track this bundle.
+ LOG.warn(e);
+ return true;// maybe it did not work maybe it did. safer to track this bundle.
}
}
}
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java
index 7858e574243..0e0ff3fbdae 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/internal/DefaultFileLocatorHelper.java
@@ -69,7 +69,7 @@ public class DefaultFileLocatorHelper implements BundleFileLocatorHelper
// grab the MANIFEST.MF's url
// and then do what it takes.
URL url = bundle.getEntry("/META-INF/MANIFEST.MF");
- //System.err.println(url.toString() + " " + url.toURI() + " " + url.getProtocol());
+
if (url.getProtocol().equals("file"))
{
// some osgi frameworks do use the file protocole directly in some
From eaacd69ede679f836873a44a367b20516f449191 Mon Sep 17 00:00:00 2001
From: Simone Bordet
Date: Thu, 5 Apr 2012 17:30:05 +0200
Subject: [PATCH 24/36] Moved from SLF4J to Jetty logging.
---
jetty-spdy/spdy-core/pom.xml | 5 +++--
.../main/java/org/eclipse/jetty/spdy/StandardSession.java | 6 +++---
.../main/java/org/eclipse/jetty/spdy/StandardStream.java | 6 +++---
.../org/eclipse/jetty/spdy/api/SessionFrameListener.java | 6 +++---
.../main/java/org/eclipse/jetty/spdy/parser/Parser.java | 6 +++---
.../jetty/spdy/http/ServerHTTPSPDYAsyncConnection.java | 6 +++---
.../spdy/http/ServerHTTPSPDYAsyncConnectionFactory.java | 6 +++---
.../java/org/eclipse/jetty/spdy/SPDYAsyncConnection.java | 8 ++++----
.../java/org/eclipse/jetty/spdy/SPDYServerConnector.java | 6 +++---
9 files changed, 28 insertions(+), 27 deletions(-)
diff --git a/jetty-spdy/spdy-core/pom.xml b/jetty-spdy/spdy-core/pom.xml
index 058434a1491..cfd2edf9293 100644
--- a/jetty-spdy/spdy-core/pom.xml
+++ b/jetty-spdy/spdy-core/pom.xml
@@ -12,8 +12,9 @@
- org.slf4j
- slf4j-api
+ org.eclipse.jetty
+ jetty-util
+ ${project.version}
junit
diff --git a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java
index dae08a4c4cd..4caa3df86c4 100644
--- a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java
+++ b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java
@@ -61,12 +61,12 @@ import org.eclipse.jetty.spdy.frames.SynStreamFrame;
import org.eclipse.jetty.spdy.frames.WindowUpdateFrame;
import org.eclipse.jetty.spdy.generator.Generator;
import org.eclipse.jetty.spdy.parser.Parser;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
public class StandardSession implements ISession, Parser.Listener, Handler
{
- private static final Logger logger = LoggerFactory.getLogger(Session.class);
+ private static final Logger logger = Log.getLogger(Session.class);
private static final ThreadLocal handlerInvocations = new ThreadLocal()
{
@Override
diff --git a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardStream.java b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardStream.java
index 758858d5690..d1fccff757c 100644
--- a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardStream.java
+++ b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardStream.java
@@ -39,12 +39,12 @@ import org.eclipse.jetty.spdy.frames.HeadersFrame;
import org.eclipse.jetty.spdy.frames.SynReplyFrame;
import org.eclipse.jetty.spdy.frames.SynStreamFrame;
import org.eclipse.jetty.spdy.frames.WindowUpdateFrame;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
public class StandardStream implements IStream
{
- private static final Logger logger = LoggerFactory.getLogger(Stream.class);
+ private static final Logger logger = Log.getLogger(Stream.class);
private final Map attributes = new ConcurrentHashMap<>();
private final SynStreamFrame frame;
private final ISession session;
diff --git a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/api/SessionFrameListener.java b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/api/SessionFrameListener.java
index f1d9d2c66a6..467919c29cf 100644
--- a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/api/SessionFrameListener.java
+++ b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/api/SessionFrameListener.java
@@ -18,8 +18,8 @@ package org.eclipse.jetty.spdy.api;
import java.util.EventListener;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
/**
* A {@link SessionFrameListener} is the passive counterpart of a {@link Session} and receives events happening
@@ -122,7 +122,7 @@ public interface SessionFrameListener extends EventListener
*/
public static class Adapter implements SessionFrameListener
{
- private static final Logger logger = LoggerFactory.getLogger(Adapter.class);
+ private static final Logger logger = Log.getLogger(Adapter.class);
@Override
public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
diff --git a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/parser/Parser.java b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/parser/Parser.java
index 58cb61d1c34..8cc42e18144 100644
--- a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/parser/Parser.java
+++ b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/parser/Parser.java
@@ -27,12 +27,12 @@ import org.eclipse.jetty.spdy.StreamException;
import org.eclipse.jetty.spdy.api.SessionStatus;
import org.eclipse.jetty.spdy.frames.ControlFrame;
import org.eclipse.jetty.spdy.frames.DataFrame;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
public class Parser
{
- private static final Logger logger = LoggerFactory.getLogger(Parser.class);
+ private static final Logger logger = Log.getLogger(Parser.class);
private final List listeners = new CopyOnWriteArrayList<>();
private final ControlFrameParser controlFrameParser;
private final DataFrameParser dataFrameParser;
diff --git a/jetty-spdy/spdy-jetty-http/src/main/java/org/eclipse/jetty/spdy/http/ServerHTTPSPDYAsyncConnection.java b/jetty-spdy/spdy-jetty-http/src/main/java/org/eclipse/jetty/spdy/http/ServerHTTPSPDYAsyncConnection.java
index f782d656467..2882bc43461 100644
--- a/jetty-spdy/spdy-jetty-http/src/main/java/org/eclipse/jetty/spdy/http/ServerHTTPSPDYAsyncConnection.java
+++ b/jetty-spdy/spdy-jetty-http/src/main/java/org/eclipse/jetty/spdy/http/ServerHTTPSPDYAsyncConnection.java
@@ -50,12 +50,12 @@ import org.eclipse.jetty.spdy.api.DataInfo;
import org.eclipse.jetty.spdy.api.Headers;
import org.eclipse.jetty.spdy.api.ReplyInfo;
import org.eclipse.jetty.spdy.api.Stream;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
public class ServerHTTPSPDYAsyncConnection extends AbstractHttpConnection implements AsyncConnection
{
- private static final Logger logger = LoggerFactory.getLogger(ServerHTTPSPDYAsyncConnection.class);
+ private static final Logger logger = Log.getLogger(ServerHTTPSPDYAsyncConnection.class);
private static final ByteBuffer ZERO_BYTES = ByteBuffer.allocate(0);
private static final DataInfo END_OF_CONTENT = new ByteBufferDataInfo(ZERO_BYTES, true);
diff --git a/jetty-spdy/spdy-jetty-http/src/main/java/org/eclipse/jetty/spdy/http/ServerHTTPSPDYAsyncConnectionFactory.java b/jetty-spdy/spdy-jetty-http/src/main/java/org/eclipse/jetty/spdy/http/ServerHTTPSPDYAsyncConnectionFactory.java
index 30a10a61c79..93fff9c8467 100644
--- a/jetty-spdy/spdy-jetty-http/src/main/java/org/eclipse/jetty/spdy/http/ServerHTTPSPDYAsyncConnectionFactory.java
+++ b/jetty-spdy/spdy-jetty-http/src/main/java/org/eclipse/jetty/spdy/http/ServerHTTPSPDYAsyncConnectionFactory.java
@@ -33,13 +33,13 @@ import org.eclipse.jetty.spdy.api.Stream;
import org.eclipse.jetty.spdy.api.StreamFrameListener;
import org.eclipse.jetty.spdy.api.SynInfo;
import org.eclipse.jetty.spdy.api.server.ServerSessionFrameListener;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
public class ServerHTTPSPDYAsyncConnectionFactory extends ServerSPDYAsyncConnectionFactory
{
private static final String CONNECTION_ATTRIBUTE = "org.eclipse.jetty.spdy.http.connection";
- private static final Logger logger = LoggerFactory.getLogger(ServerHTTPSPDYAsyncConnectionFactory.class);
+ private static final Logger logger = Log.getLogger(ServerHTTPSPDYAsyncConnectionFactory.class);
private final Connector connector;
diff --git a/jetty-spdy/spdy-jetty/src/main/java/org/eclipse/jetty/spdy/SPDYAsyncConnection.java b/jetty-spdy/spdy-jetty/src/main/java/org/eclipse/jetty/spdy/SPDYAsyncConnection.java
index 3ae8ccaef46..40dfecde36b 100644
--- a/jetty-spdy/spdy-jetty/src/main/java/org/eclipse/jetty/spdy/SPDYAsyncConnection.java
+++ b/jetty-spdy/spdy-jetty/src/main/java/org/eclipse/jetty/spdy/SPDYAsyncConnection.java
@@ -30,12 +30,12 @@ import org.eclipse.jetty.io.nio.NIOBuffer;
import org.eclipse.jetty.spdy.api.Handler;
import org.eclipse.jetty.spdy.api.Session;
import org.eclipse.jetty.spdy.parser.Parser;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
public class SPDYAsyncConnection extends AbstractConnection implements AsyncConnection, Controller, IdleListener
{
- private static final Logger logger = LoggerFactory.getLogger(SPDYAsyncConnection.class);
+ private static final Logger logger = Log.getLogger(SPDYAsyncConnection.class);
private final ByteBufferPool bufferPool;
private final Parser parser;
private volatile Session session;
@@ -181,7 +181,7 @@ public class SPDYAsyncConnection extends AbstractConnection implements AsyncConn
}
catch (IOException x)
{
- logger.trace("", x);
+ logger.ignore(x);
}
}
diff --git a/jetty-spdy/spdy-jetty/src/main/java/org/eclipse/jetty/spdy/SPDYServerConnector.java b/jetty-spdy/spdy-jetty/src/main/java/org/eclipse/jetty/spdy/SPDYServerConnector.java
index 2a496070f96..41412b3f0c5 100644
--- a/jetty-spdy/spdy-jetty/src/main/java/org/eclipse/jetty/spdy/SPDYServerConnector.java
+++ b/jetty-spdy/spdy-jetty/src/main/java/org/eclipse/jetty/spdy/SPDYServerConnector.java
@@ -41,14 +41,14 @@ import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.spdy.api.SPDY;
import org.eclipse.jetty.spdy.api.Session;
import org.eclipse.jetty.spdy.api.server.ServerSessionFrameListener;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.ThreadPool;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
public class SPDYServerConnector extends SelectChannelConnector
{
- private static final Logger logger = LoggerFactory.getLogger(SPDYServerConnector.class);
+ private static final Logger logger = Log.getLogger(SPDYServerConnector.class);
// Order is important on server side, so we use a LinkedHashMap
private final Map factories = new LinkedHashMap<>();
From 6ec159401010469008ca58ba5b04d2ed3ad55213 Mon Sep 17 00:00:00 2001
From: Simone Bordet
Date: Thu, 5 Apr 2012 17:33:48 +0200
Subject: [PATCH 25/36] Updated path location of the jetty config file for
SPDY.
---
jetty-spdy/spdy-jetty-http-webapp/pom.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/jetty-spdy/spdy-jetty-http-webapp/pom.xml b/jetty-spdy/spdy-jetty-http-webapp/pom.xml
index 68b571f5925..3c2c370cb9c 100644
--- a/jetty-spdy/spdy-jetty-http-webapp/pom.xml
+++ b/jetty-spdy/spdy-jetty-http-webapp/pom.xml
@@ -42,7 +42,7 @@
-Dlog4j.configuration=file://${basedir}/src/main/resources/log4j.properties
-Xbootclasspath/p:${settings.localRepository}/org/mortbay/jetty/npn/npn-boot/${project.version}/npn-boot-${project.version}.jar
- ${basedir}/src/main/config/jetty-spdy.xml
+ ${basedir}/src/main/config/etc/jetty-spdy.xml
/
From 9dfa9f9937baa85c26f475b60b554f1ba6398679 Mon Sep 17 00:00:00 2001
From: Greg Wilkins
Date: Tue, 10 Apr 2012 14:21:07 +1000
Subject: [PATCH 26/36] 370081: correctly set URI for query strings
---
.../rewrite/handler/RegexTargetHandler.java | 149 ------------
.../rewrite/handler/RewriteRegexRule.java | 19 +-
.../handler/RegexTargetHandlerTest.java | 214 ------------------
.../rewrite/handler/RewriteRegexRuleTest.java | 29 ++-
.../java/org/eclipse/jetty/util/MultiMap.java | 20 +-
5 files changed, 56 insertions(+), 375 deletions(-)
delete mode 100644 jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RegexTargetHandler.java
delete mode 100644 jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RegexTargetHandlerTest.java
diff --git a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RegexTargetHandler.java b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RegexTargetHandler.java
deleted file mode 100644
index 736f8245f9f..00000000000
--- a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RegexTargetHandler.java
+++ /dev/null
@@ -1,149 +0,0 @@
-package org.eclipse.jetty.rewrite.handler;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.eclipse.jetty.server.Request;
-import org.eclipse.jetty.server.handler.ContextHandler;
-import org.eclipse.jetty.server.handler.ContextHandler.Context;
-import org.eclipse.jetty.server.handler.ScopedHandler;
-import org.eclipse.jetty.util.component.AggregateLifeCycle;
-import org.eclipse.jetty.util.log.Log;
-import org.eclipse.jetty.util.log.Logger;
-
-
-/* ------------------------------------------------------------ */
-/** A handle that uses regular expressions to select the target.
- *
- * This handler applies a list of regex to target name mappings to the URIs of requests.
- * If the regex matches the URI, then the mapped target name is used in the nested
- * call to {@link #doScope(String, Request, HttpServletRequest, HttpServletResponse)}.
- *
- * This handler should be installed as the first handler in a Context. It can be configured
- * either with direct calls to {@link #addPatternTarget(String, String)} or by setting
- * the context init parameters "org.eclipse.jetty.rewrite.handler.REGEX_MAPPINGS" to a comma
- * separated list of strings in the format regex==target.
- */
-public class RegexTargetHandler extends ScopedHandler
-{
- private final static Logger LOG = Log.getLogger(RegexTargetHandler.class);
- public final static String REGEX_MAPPINGS="org.eclipse.jetty.rewrite.handler.REGEX_MAPPINGS";
- static class RegexMapping
- {
- RegexMapping(String regex,String target)
- {
- _pattern=Pattern.compile(regex);
- _target=target;
- }
- final Pattern _pattern;
- final String _target;
-
- public String toString()
- {
- return _pattern+"=="+_target;
- }
- }
-
- final private List _patterns = new CopyOnWriteArrayList();
-
- /* ------------------------------------------------------------ */
- /** Add a pattern to target mapping.
- * @param pattern The regular expression pattern to match.
- * @param target The target (normally servlet name) to handle the request
- */
- public void addPatternTarget(String pattern,String target)
- {
- _patterns.add(new RegexMapping(pattern,target));
- }
-
- /* ------------------------------------------------------------ */
- @Override
- protected void doStart() throws Exception
- {
- super.doStart();
-
- Context context = ContextHandler.getCurrentContext();
- if (context!=null)
- {
- String config=context.getInitParameter(REGEX_MAPPINGS);
- LOG.debug("{}={}",REGEX_MAPPINGS,config);
- String[] mappings=config.split("\\s*,\\s*");
- for (String mapping : mappings)
- {
- mapping=mapping.trim();
- String[] parts=mapping.split("\\s*==\\s*");
- if (parts.length==2)
- {
- String pattern=parts[0];
- String target=parts[1];
- addPatternTarget(pattern,target);
- }
- else
- LOG.warn("Bad regex mapping: "+mapping);
- }
- }
- }
-
- /* ------------------------------------------------------------ */
- @Override
- public void doScope(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
- {
- for (RegexTargetHandler.RegexMapping rm : _patterns)
- {
- Matcher m=rm._pattern.matcher(target);
- if (m.matches())
- {
- String new_target = rm._target;
- final String sp;
- final String pi;
-
- if (m.groupCount()==1&&target.endsWith(m.group(1)))
- {
- pi=m.group(1);
- sp=target.substring(0,target.length()-pi.length());
- }
- else
- {
- sp=target;
- pi=null;
- }
- baseRequest.setServletPath(sp);
- baseRequest.setPathInfo(pi);
- baseRequest.setAttribute("org.eclipse.jetty.servlet.REGEX_PATH",target);
- super.nextScope(new_target,baseRequest,request,response);
- return;
- }
- }
- super.nextScope(target,baseRequest,request,response);
- }
-
- /* ------------------------------------------------------------ */
- @Override
- public void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
- {
- String path=(String)baseRequest.getAttribute("org.eclipse.jetty.servlet.REGEX_PATH");
- if (path==null)
- path=target;
- else
- baseRequest.setAttribute("org.eclipse.jetty.servlet.REGEX_PATH",null);
-
- super.nextHandle(path,baseRequest,request,response);
- }
-
- /* ------------------------------------------------------------ */
- public void dump(Appendable out, String indent) throws IOException
- {
- AggregateLifeCycle.dumpObject(out,this);
- AggregateLifeCycle.dump(out,indent,_patterns,Collections.singletonList(getHandler()));
- }
-
-
-}
\ No newline at end of file
diff --git a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRule.java b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRule.java
index 49a27dcee30..6fa22b52238 100644
--- a/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRule.java
+++ b/jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRule.java
@@ -18,6 +18,7 @@ import java.util.regex.Matcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.server.Request;
/**
@@ -89,14 +90,20 @@ public class RewriteRegexRule extends RegexRule implements Rule.ApplyURI
/* ------------------------------------------------------------ */
public void applyURI(Request request, String oldTarget, String newTarget) throws IOException
{
- request.setRequestURI(newTarget);
- if (_query!=null)
+ if (_query==null)
+ {
+ request.setRequestURI(newTarget);
+ }
+ else
{
String query=(String)request.getAttribute("org.eclipse.jetty.rewrite.handler.RewriteRegexRule.Q");
- if (_queryGroup||request.getQueryString()==null)
- request.setQueryString(query);
- else
- request.setQueryString(request.getQueryString()+"&"+query);
+
+ if (!_queryGroup && request.getQueryString()!=null)
+ query=request.getQueryString()+"&"+query;
+ HttpURI uri=new HttpURI(newTarget+"?"+query);
+ request.setUri(uri);
+ request.setRequestURI(newTarget);
+ request.setQueryString(query);
}
}
diff --git a/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RegexTargetHandlerTest.java b/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RegexTargetHandlerTest.java
deleted file mode 100644
index c47937621df..00000000000
--- a/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RegexTargetHandlerTest.java
+++ /dev/null
@@ -1,214 +0,0 @@
-// ========================================================================
-// Copyright (c) 2006-2009 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.rewrite.handler;
-
-import static junit.framework.Assert.assertEquals;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.net.Socket;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.servlet.RequestDispatcher;
-import javax.servlet.Servlet;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequestWrapper;
-import javax.servlet.ServletResponseWrapper;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpServletResponseWrapper;
-
-import junit.framework.Assert;
-
-import org.eclipse.jetty.rewrite.handler.RegexTargetHandler;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.servlet.ServletContextHandler;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class RegexTargetHandlerTest
-{
- private static Server __server = new Server(0);
- private static int __port;
-
- @BeforeClass
- public static void setup() throws Exception
- {
-
- ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
- context.setContextPath("/");
- __server.setHandler(context);
-
- // Serve some hello world servlets
- context.addServlet(DispatchServletServlet.class,"/dispatch/*");
- context.addServlet(new ServletHolder("HelloAll",new HelloServlet("Hello World")),"/*");
- context.addServlet(new ServletHolder("Italian",new HelloServlet("Buongiorno Mondo")),"/it/*");
- context.addServlet(new ServletHolder("French", new HelloServlet("Bonjour le Monde")),"/fr/*");
-
- RegexTargetHandler regexHandler=new RegexTargetHandler();
- regexHandler.setHandler(context.getHandler());
- context.setHandler(regexHandler);
-
- context.getInitParams().put(RegexTargetHandler.REGEX_MAPPINGS,
- " .*\\.fr==French, \n"+
- "/ciao(/.*)$==Italian");
-
- __server.start();
-
- __port=__server.getConnectors()[0].getLocalPort();
- }
-
- @AfterClass
- public static void shutdown() throws Exception
- {
- __server.stop();
- }
-
-
- @Test
- public void testNormal() throws Exception
- {
- String[] response=getResponse("/normal");
- assertEquals("HTTP/1.1 200 OK",response[0]);
- assertEquals("Hello World",response[1]);
- assertEquals("",response[2]);
- assertEquals("/normal",response[3]);
-
- response=getResponse("/it/info");
- assertEquals("HTTP/1.1 200 OK",response[0]);
- assertEquals("Buongiorno Mondo",response[1]);
- assertEquals("/it",response[2]);
- assertEquals("/info",response[3]);
- }
-
- @Test
- public void testFullMatch() throws Exception
- {
- String[] response=getResponse("/some/thing.fr");
- assertEquals("HTTP/1.1 200 OK",response[0]);
- assertEquals("Bonjour le Monde",response[1]);
- assertEquals("/some/thing.fr",response[2]);
- assertEquals("null",response[3]);
- }
-
- @Test
- public void testCaptureMatch() throws Exception
- {
- String[] response=getResponse("/ciao/info");
- assertEquals("HTTP/1.1 200 OK",response[0]);
- assertEquals("Buongiorno Mondo",response[1]);
- assertEquals("/ciao",response[2]);
- assertEquals("/info",response[3]);
- }
-
- @Test
- public void testDispatchFullMatch() throws Exception
- {
- String[] response=getResponse("/dispatch/xxx?forward=/some/thing.fr");
- assertEquals("HTTP/1.1 200 OK",response[0]);
- assertEquals("Bonjour le Monde",response[1]);
- assertEquals("/some/thing.fr",response[2]);
- assertEquals("null",response[3]);
- }
-
- @Test
- public void testDispatchCaptureMatch() throws Exception
- {
- String[] response=getResponse("/dispatch/xxx?forward=/ciao/info");
- assertEquals("HTTP/1.1 200 OK",response[0]);
- assertEquals("Buongiorno Mondo",response[1]);
- assertEquals("/ciao",response[2]);
- assertEquals("/info",response[3]);
- }
-
-
- private String[] getResponse(String uri) throws Exception
- {
- Socket socket = new Socket("127.0.0.1",__port);
-
- PrintWriter out = new PrintWriter(socket.getOutputStream());
- out.print("GET "+uri+" HTTP/1.0\r\n\r\n");
- out.flush();
-
- BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
-
- String[] response=new String[4];
- response[0]=in.readLine();
- //System.err.println(response[0]);
-
- String line=in.readLine();
- while(line.length()>0)
- line=in.readLine();
-
- response[1]=in.readLine();
- //System.err.println(response[1]);
- response[2]=in.readLine();
- //System.err.println(response[2]);
- response[3]=in.readLine();
- //System.err.println(response[3]);
-
- socket.close();
- return response;
- }
-
-
- public static class HelloServlet extends HttpServlet implements Servlet
- {
- final String _hello;
-
- public HelloServlet(String hello)
- {
- _hello=hello;
- }
-
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
- {
- response.setStatus(200);
- response.getWriter().println(_hello);
- response.getWriter().println(request.getServletPath());
- response.getWriter().println(request.getPathInfo());
- }
- }
-
-
- public static class DispatchServletServlet extends HttpServlet implements Servlet
- {
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
- {
- RequestDispatcher dispatcher = null;
-
- if(request.getParameter("include")!=null)
- {
- dispatcher = getServletContext().getRequestDispatcher(request.getParameter("include"));
- dispatcher.include(new HttpServletRequestWrapper(request), new HttpServletResponseWrapper(response));
- }
- else if(request.getParameter("forward")!=null)
- {
- dispatcher = getServletContext().getRequestDispatcher(request.getParameter("forward"));
- dispatcher.forward(new HttpServletRequestWrapper(request), new HttpServletResponseWrapper(response));
- }
-
- }
- }
-}
diff --git a/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRuleTest.java b/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRuleTest.java
index 872bb6e5b85..a804db70c31 100644
--- a/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRuleTest.java
+++ b/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRuleTest.java
@@ -14,6 +14,10 @@ package org.eclipse.jetty.rewrite.handler;
import java.io.IOException;
+import org.eclipse.jetty.http.HttpURI;
+import org.eclipse.jetty.util.MultiMap;
+import org.eclipse.jetty.util.StringUtil;
+import org.eclipse.jetty.util.UrlEncoded;
import org.junit.Before;
import org.junit.Test;
@@ -53,20 +57,35 @@ public class RewriteRegexRuleTest extends AbstractRuleTestCase
{
for (String[] test : _tests)
{
+ reset();
+ _request.setRequestURI(null);
+
String t=test[0]+"?"+test[1]+">"+test[2]+"|"+test[3];
_rule.setRegex(test[2]);
_rule.setReplacement(test[3]);
- _request.setRequestURI(test[0]);
- _request.setQueryString(test[1]);
- _request.getAttributes().clearAttributes();
+ _request.setUri(new HttpURI(test[0]+(test[1]==null?"":("?"+test[1]))));
+ _request.getRequestURI();
+
String result = _rule.matchAndApply(test[0], _request, _response);
assertEquals(t, test[4], result);
_rule.applyURI(_request,test[0],result);
- assertEquals(t,test[4], _request.getRequestURI());
- assertEquals(t,test[5], _request.getQueryString());
+ if (result!=null)
+ {
+ assertEquals(t,test[4], _request.getRequestURI());
+ assertEquals(t,test[5], _request.getQueryString());
+ }
+
+ if (test[5]!=null)
+ {
+ MultiMap params=new MultiMap();
+ UrlEncoded.decodeTo(test[5],params,StringUtil.__UTF8);
+
+ for (String n:params.keySet())
+ assertEquals(params.getString(n),_request.getParameter(n));
+ }
}
}
diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/MultiMap.java b/jetty-util/src/main/java/org/eclipse/jetty/util/MultiMap.java
index 61f9eeaec91..2d0840da004 100644
--- a/jetty-util/src/main/java/org/eclipse/jetty/util/MultiMap.java
+++ b/jetty-util/src/main/java/org/eclipse/jetty/util/MultiMap.java
@@ -287,7 +287,25 @@ public class MultiMap implements ConcurrentMap, Serializable
*/
public Map toStringArrayMap()
{
- HashMap map = new HashMap(_map.size()*3/2);
+ HashMap map = new HashMap(_map.size()*3/2)
+ {
+ public String toString()
+ {
+ StringBuilder b=new StringBuilder();
+ b.append('{');
+ for (K k:keySet())
+ {
+ if(b.length()>1)
+ b.append(',');
+ b.append(k);
+ b.append('=');
+ b.append(Arrays.asList(get(k)));
+ }
+
+ b.append('}');
+ return b.toString();
+ }
+ };
for(Map.Entry entry: _map.entrySet())
{
From f81ea123202a1e96c0738184e101b41dfa1347be Mon Sep 17 00:00:00 2001
From: Jan Bartel
Date: Wed, 11 Apr 2012 12:37:51 +1000
Subject: [PATCH 27/36] 375709 Ensure resolveTempDirectory failure does not
deadlock; improve error message
---
.../java/org/eclipse/jetty/webapp/WebInfConfiguration.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebInfConfiguration.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebInfConfiguration.java
index d7748365c8e..fc9f3734c02 100644
--- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebInfConfiguration.java
+++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/WebInfConfiguration.java
@@ -305,7 +305,8 @@ public class WebInfConfiguration extends AbstractConfiguration
}
catch(IOException e)
{
- LOG.warn("tmpdir",e); System.exit(1);
+ tmpDir = null;
+ throw new IllegalStateException("Cannot create tmp dir in "+System.getProperty("java.io.tmpdir")+ " for context "+context,e);
}
}
}
From 4412d311a9a440572fd15663cc00392754467b79 Mon Sep 17 00:00:00 2001
From: Greg Wilkins
Date: Wed, 11 Apr 2012 17:21:02 +1000
Subject: [PATCH 28/36] 370081:fixed test reset
---
.../rewrite/handler/RewriteRegexRuleTest.java | 31 ++++++++++---------
1 file changed, 16 insertions(+), 15 deletions(-)
diff --git a/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRuleTest.java b/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRuleTest.java
index a804db70c31..adb8777f12f 100644
--- a/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRuleTest.java
+++ b/jetty-rewrite/src/test/java/org/eclipse/jetty/rewrite/handler/RewriteRegexRuleTest.java
@@ -27,21 +27,21 @@ public class RewriteRegexRuleTest extends AbstractRuleTestCase
{
private String[][] _tests=
{
- {"/foo/bar",null,".*","/replace","/replace",null},
- {"/foo/bar","n=v",".*","/replace","/replace","n=v"},
- {"/foo/bar",null,"/xxx.*","/replace",null,null},
- {"/foo/bar",null,"/(.*)/(.*)","/$2/$1/xxx","/bar/foo/xxx",null},
- {"/foo/bar",null,"/(.*)/(.*)","/test?p2=$2&p1=$1","/test","p2=bar&p1=foo"},
- {"/foo/bar","n=v","/(.*)/(.*)","/test?p2=$2&p1=$1","/test","n=v&p2=bar&p1=foo"},
- {"/foo/bar",null,"/(.*)/(.*)","/foo/bar?p2=$2&p1=$1","/foo/bar","p2=bar&p1=foo"},
- {"/foo/bar","n=v","/(.*)/(.*)","/foo/bar?p2=$2&p1=$1","/foo/bar","n=v&p2=bar&p1=foo"},
- {"/foo/bar",null,"/(foo)/(.*)(bar)","/$3/$1/xxx$2","/bar/foo/xxx",null},
- {"/foo/$bar",null,".*","/$replace","/$replace",null},
- {"/foo/$bar",null,"/foo/(.*)","/$1/replace","/$bar/replace",null},
- {"/foo/bar/info",null,"/foo/(NotHere)?([^/]*)/(.*)","/$3/other?p1=$2","/info/other","p1=bar"},
- {"/foo/bar/info",null,"/foo/(NotHere)?([^/]*)/(.*)","/$3/other?p1=$2&$Q","/info/other","p1=bar&"},
- {"/foo/bar/info","n=v","/foo/(NotHere)?([^/]*)/(.*)","/$3/other?p1=$2&$Q","/info/other","p1=bar&n=v"},
- {"/foo/bar/info","n=v","/foo/(NotHere)?([^/]*)/(.*)","/$3/other?p1=$2","/info/other","n=v&p1=bar"},
+ {"/foo0/bar",null,".*","/replace","/replace",null},
+ {"/foo1/bar","n=v",".*","/replace","/replace","n=v"},
+ {"/foo2/bar",null,"/xxx.*","/replace",null,null},
+ {"/foo3/bar",null,"/(.*)/(.*)","/$2/$1/xxx","/bar/foo3/xxx",null},
+ {"/foo4/bar",null,"/(.*)/(.*)","/test?p2=$2&p1=$1","/test","p2=bar&p1=foo4"},
+ {"/foo5/bar","n=v","/(.*)/(.*)","/test?p2=$2&p1=$1","/test","n=v&p2=bar&p1=foo5"},
+ {"/foo6/bar",null,"/(.*)/(.*)","/foo6/bar?p2=$2&p1=$1","/foo6/bar","p2=bar&p1=foo6"},
+ {"/foo7/bar","n=v","/(.*)/(.*)","/foo7/bar?p2=$2&p1=$1","/foo7/bar","n=v&p2=bar&p1=foo7"},
+ {"/foo8/bar",null,"/(foo8)/(.*)(bar)","/$3/$1/xxx$2","/bar/foo8/xxx",null},
+ {"/foo9/$bar",null,".*","/$replace","/$replace",null},
+ {"/fooA/$bar",null,"/fooA/(.*)","/$1/replace","/$bar/replace",null},
+ {"/fooB/bar/info",null,"/fooB/(NotHere)?([^/]*)/(.*)","/$3/other?p1=$2","/info/other","p1=bar"},
+ {"/fooC/bar/info",null,"/fooC/(NotHere)?([^/]*)/(.*)","/$3/other?p1=$2&$Q","/info/other","p1=bar&"},
+ {"/fooD/bar/info","n=v","/fooD/(NotHere)?([^/]*)/(.*)","/$3/other?p1=$2&$Q","/info/other","p1=bar&n=v"},
+ {"/fooE/bar/info","n=v","/fooE/(NotHere)?([^/]*)/(.*)","/$3/other?p1=$2","/info/other","n=v&p1=bar"},
};
private RewriteRegexRule _rule;
@@ -97,6 +97,7 @@ public class RewriteRegexRuleTest extends AbstractRuleTestCase
container.addRule(_rule);
for (String[] test : _tests)
{
+ reset();
String t=test[0]+"?"+test[1]+">"+test[2]+"|"+test[3];
_rule.setRegex(test[2]);
_rule.setReplacement(test[3]);
From 20a3d3c12ec8f4cb5f30747304f1ff7d4eaf1be8 Mon Sep 17 00:00:00 2001
From: Greg Wilkins
Date: Wed, 11 Apr 2012 18:21:39 +1000
Subject: [PATCH 29/36] 376424: do not recycle buffers before content consumed
asynchronously
---
.../src/main/java/org/eclipse/jetty/http/HttpParser.java | 9 ---------
1 file changed, 9 deletions(-)
diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java
index c7d7d39f88a..0b4053c15e3 100644
--- a/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java
+++ b/jetty-http/src/main/java/org/eclipse/jetty/http/HttpParser.java
@@ -260,7 +260,6 @@ public class HttpParser implements Parser
{
_state=STATE_END;
_handler.messageComplete(_contentPosition);
- returnBuffers();
return 1;
}
@@ -326,7 +325,6 @@ public class HttpParser implements Parser
if (!isComplete() && !isIdle())
throw new EofException();
- returnBuffers();
return -1;
}
length=_buffer.length();
@@ -440,7 +438,6 @@ public class HttpParser implements Parser
_state=STATE_SEEKING_EOF;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
- returnBuffers();
return 1;
}
break;
@@ -470,7 +467,6 @@ public class HttpParser implements Parser
_state=STATE_SEEKING_EOF;
_handler.headerComplete();
_handler.messageComplete(_contentPosition);
- returnBuffers();
return 1;
}
}
@@ -634,7 +630,6 @@ public class HttpParser implements Parser
_handler.headerComplete();
_state=_persistent||(_responseStatus>=100&&_responseStatus<200)?STATE_END:STATE_SEEKING_EOF;
_handler.messageComplete(_contentPosition);
- returnBuffers();
return 1;
default:
@@ -840,7 +835,6 @@ public class HttpParser implements Parser
{
_state=_persistent?STATE_END:STATE_SEEKING_EOF;
_handler.messageComplete(_contentPosition);
- returnBuffers();
return 1;
}
@@ -860,7 +854,6 @@ public class HttpParser implements Parser
{
_state=_persistent?STATE_END:STATE_SEEKING_EOF;
_handler.messageComplete(_contentPosition);
- returnBuffers();
}
// TODO adjust the _buffer to keep unconsumed content
return 1;
@@ -895,7 +888,6 @@ public class HttpParser implements Parser
_eol=_buffer.get();
_state=_persistent?STATE_END:STATE_SEEKING_EOF;
_handler.messageComplete(_contentPosition);
- returnBuffers();
return 1;
}
else
@@ -926,7 +918,6 @@ public class HttpParser implements Parser
_eol=_buffer.get();
_state=_persistent?STATE_END:STATE_SEEKING_EOF;
_handler.messageComplete(_contentPosition);
- returnBuffers();
return 1;
}
else
From 47c1587166a7951343a20c248da5b074dd70699c Mon Sep 17 00:00:00 2001
From: Simone Bordet
Date: Wed, 11 Apr 2012 10:39:23 +0200
Subject: [PATCH 30/36] Strengthen the behavior of Stream methods to throw if
they are used wrongly, for example sending DATA frames before a REPLY and so
on.
---
.../eclipse/jetty/spdy/StandardStream.java | 38 ++++++-
.../org/eclipse/jetty/spdy/APIUsageTest.java | 98 +++++++++++++++++++
.../org/eclipse/jetty/spdy/SynReplyTest.java | 35 -------
3 files changed, 132 insertions(+), 39 deletions(-)
create mode 100644 jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/APIUsageTest.java
diff --git a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardStream.java b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardStream.java
index d1fccff757c..013159d7d90 100644
--- a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardStream.java
+++ b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardStream.java
@@ -50,7 +50,7 @@ public class StandardStream implements IStream
private final ISession session;
private final AtomicInteger windowSize;
private volatile StreamFrameListener listener;
- private volatile boolean opened;
+ private volatile OpenState openState = OpenState.SYN_SENT;
private volatile boolean halfClosed;
private volatile boolean closed;
@@ -141,12 +141,12 @@ public class StandardStream implements IStream
{
case SYN_STREAM:
{
- opened = true;
+ openState = OpenState.SYN_RECV;
break;
}
case SYN_REPLY:
{
- opened = true;
+ openState = OpenState.REPLY_RECV;
SynReplyFrame synReply = (SynReplyFrame)frame;
updateCloseState(synReply.isClose());
ReplyInfo replyInfo = new ReplyInfo(synReply.getHeaders(), synReply.isClose());
@@ -183,7 +183,7 @@ public class StandardStream implements IStream
@Override
public void process(DataFrame frame, ByteBuffer data)
{
- if (!opened)
+ if (!canReceive())
{
session.rst(new RstInfo(getId(), StreamStatus.PROTOCOL_ERROR));
return;
@@ -286,6 +286,7 @@ public class StandardStream implements IStream
@Override
public void reply(ReplyInfo replyInfo, long timeout, TimeUnit unit, Handler handler)
{
+ openState = OpenState.REPLY_SENT;
updateCloseState(replyInfo.isClose());
SynReplyFrame frame = new SynReplyFrame(session.getVersion(), replyInfo.getFlags(), getId(), replyInfo.getHeaders());
session.control(this, frame, timeout, unit, handler, null);
@@ -302,6 +303,12 @@ public class StandardStream implements IStream
@Override
public void data(DataInfo dataInfo, long timeout, TimeUnit unit, Handler handler)
{
+ if (!canSend())
+ {
+ session.rst(new RstInfo(getId(), StreamStatus.PROTOCOL_ERROR));
+ throw new IllegalStateException("Cannot send DATA frames before a SYN_REPLY frame");
+ }
+
// Cannot update the close state here, because the data that we send may
// be flow controlled, so we need the stream to update the window size.
session.data(this, dataInfo, timeout, unit, handler, null);
@@ -318,6 +325,12 @@ public class StandardStream implements IStream
@Override
public void headers(HeadersInfo headersInfo, long timeout, TimeUnit unit, Handler handler)
{
+ if (!canSend())
+ {
+ session.rst(new RstInfo(getId(), StreamStatus.PROTOCOL_ERROR));
+ throw new IllegalStateException("Cannot send a HEADERS frame before a SYN_REPLY frame");
+ }
+
updateCloseState(headersInfo.isClose());
HeadersFrame frame = new HeadersFrame(session.getVersion(), headersInfo.getFlags(), getId(), headersInfo.getHeaders());
session.control(this, frame, timeout, unit, handler, null);
@@ -334,4 +347,21 @@ public class StandardStream implements IStream
{
return String.format("stream=%d v%d closed=%s", getId(), session.getVersion(), isClosed() ? "true" : isHalfClosed() ? "half" : "false");
}
+
+ private boolean canSend()
+ {
+ OpenState openState = this.openState;
+ return openState == OpenState.SYN_SENT || openState == OpenState.REPLY_RECV || openState == OpenState.REPLY_SENT;
+ }
+
+ private boolean canReceive()
+ {
+ OpenState openState = this.openState;
+ return openState == OpenState.SYN_RECV || openState == OpenState.REPLY_RECV || openState == OpenState.REPLY_SENT;
+ }
+
+ private enum OpenState
+ {
+ SYN_SENT, SYN_RECV, REPLY_SENT, REPLY_RECV
+ }
}
diff --git a/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/APIUsageTest.java b/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/APIUsageTest.java
new file mode 100644
index 00000000000..36a0a2cb7bf
--- /dev/null
+++ b/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/APIUsageTest.java
@@ -0,0 +1,98 @@
+package org.eclipse.jetty.spdy;
+
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.eclipse.jetty.spdy.api.BytesDataInfo;
+import org.eclipse.jetty.spdy.api.RstInfo;
+import org.eclipse.jetty.spdy.api.SPDY;
+import org.eclipse.jetty.spdy.api.Session;
+import org.eclipse.jetty.spdy.api.SessionFrameListener;
+import org.eclipse.jetty.spdy.api.SessionStatus;
+import org.eclipse.jetty.spdy.api.Stream;
+import org.eclipse.jetty.spdy.api.StreamFrameListener;
+import org.eclipse.jetty.spdy.api.StreamStatus;
+import org.eclipse.jetty.spdy.api.StringDataInfo;
+import org.eclipse.jetty.spdy.api.SynInfo;
+import org.eclipse.jetty.spdy.api.server.ServerSessionFrameListener;
+import org.eclipse.jetty.spdy.frames.ControlFrameType;
+import org.eclipse.jetty.spdy.frames.GoAwayFrame;
+import org.eclipse.jetty.spdy.generator.Generator;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class APIUsageTest extends AbstractTest
+{
+ @Test
+ public void testSendDataBeforeReplyIsIllegal() throws Exception
+ {
+ final CountDownLatch resetLatch = new CountDownLatch(1);
+ final CountDownLatch latch = new CountDownLatch(1);
+ Session session = startClient(startServer(new ServerSessionFrameListener.Adapter()
+ {
+ @Override
+ public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
+ {
+ try
+ {
+ stream.data(new StringDataInfo("failure", true));
+ return null;
+ }
+ catch (IllegalStateException x)
+ {
+ latch.countDown();
+ return null;
+ }
+ }
+ }), new SessionFrameListener.Adapter()
+ {
+ @Override
+ public void onRst(Session session, RstInfo rstInfo)
+ {
+ Assert.assertSame(StreamStatus.PROTOCOL_ERROR, rstInfo.getStreamStatus());
+ resetLatch.countDown();
+ }
+ });
+ session.syn(new SynInfo(true), null);
+ Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
+ Assert.assertTrue(resetLatch.await(5, TimeUnit.SECONDS));
+ }
+
+ @Test
+ public void testReceiveDataBeforeReplyIsIllegal() throws Exception
+ {
+ ServerSocketChannel server = ServerSocketChannel.open();
+ server.bind(new InetSocketAddress("localhost", 0));
+
+ Session session = startClient(new InetSocketAddress("localhost", server.socket().getLocalPort()), null);
+ session.syn(new SynInfo(true), null);
+
+ SocketChannel channel = server.accept();
+ ByteBuffer readBuffer = ByteBuffer.allocate(1024);
+ channel.read(readBuffer);
+ readBuffer.flip();
+ int streamId = readBuffer.getInt(8);
+
+ Generator generator = new Generator(new StandardByteBufferPool(), new StandardCompressionFactory.StandardCompressor());
+ byte[] bytes = new byte[1];
+ ByteBuffer writeBuffer = generator.data(streamId, bytes.length, new BytesDataInfo(bytes, true));
+ channel.write(writeBuffer);
+
+ readBuffer.clear();
+ channel.read(readBuffer);
+ readBuffer.flip();
+ Assert.assertEquals(ControlFrameType.RST_STREAM.getCode(), readBuffer.getShort(2));
+ Assert.assertEquals(streamId, readBuffer.getInt(8));
+
+ writeBuffer = generator.control(new GoAwayFrame(SPDY.V2, 0, SessionStatus.OK.getCode()));
+ channel.write(writeBuffer);
+ channel.shutdownOutput();
+ channel.close();
+
+ server.close();
+ }
+}
diff --git a/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/SynReplyTest.java b/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/SynReplyTest.java
index 7e5d67fdd2f..207e1335b03 100644
--- a/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/SynReplyTest.java
+++ b/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/SynReplyTest.java
@@ -30,12 +30,10 @@ import org.eclipse.jetty.spdy.api.DataInfo;
import org.eclipse.jetty.spdy.api.Handler;
import org.eclipse.jetty.spdy.api.Headers;
import org.eclipse.jetty.spdy.api.ReplyInfo;
-import org.eclipse.jetty.spdy.api.RstInfo;
import org.eclipse.jetty.spdy.api.Session;
import org.eclipse.jetty.spdy.api.SessionFrameListener;
import org.eclipse.jetty.spdy.api.Stream;
import org.eclipse.jetty.spdy.api.StreamFrameListener;
-import org.eclipse.jetty.spdy.api.StreamStatus;
import org.eclipse.jetty.spdy.api.StringDataInfo;
import org.eclipse.jetty.spdy.api.SynInfo;
import org.eclipse.jetty.spdy.api.server.ServerSessionFrameListener;
@@ -324,39 +322,6 @@ public class SynReplyTest extends AbstractTest
Assert.assertTrue(clientDataLatch.await(5, TimeUnit.SECONDS));
}
- @Test
- public void testSynDataRst() throws Exception
- {
- final AtomicReference ref = new AtomicReference<>();
- final CountDownLatch latch = new CountDownLatch(1);
- ServerSessionFrameListener serverSessionFrameListener = new ServerSessionFrameListener.Adapter()
- {
- @Override
- public StreamFrameListener onSyn(Stream stream, SynInfo synInfo)
- {
- // Do not send the reply, we expect a RST_STREAM
- stream.data(new StringDataInfo("foo", true));
- return null;
- }
-
- @Override
- public void onRst(Session session, RstInfo rstInfo)
- {
- ref.set(rstInfo);
- latch.countDown();
- }
- };
- Session session = startClient(startServer(serverSessionFrameListener), null);
-
- Stream stream = session.syn(new SynInfo(true), null).get(5, TimeUnit.SECONDS);
-
- Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
- RstInfo rstInfo = ref.get();
- Assert.assertNotNull(rstInfo);
- Assert.assertEquals(stream.getId(), rstInfo.getStreamId());
- Assert.assertSame(StreamStatus.PROTOCOL_ERROR, rstInfo.getStreamStatus());
- }
-
@Test
public void testSynReplyDataSynReplyData() throws Exception
{
From 5b7fe58593b3250b4f70ea6bc6c9d51a35c9b635 Mon Sep 17 00:00:00 2001
From: Thomas Becker
Date: Wed, 11 Apr 2012 10:55:32 +0200
Subject: [PATCH 31/36] 376373: GzipFilter now does not ignore _excludePath +
fix for ignored _excludeAgentPatterns if _excludeAgent is set
Change-Id: I1f0ac1b5a12d75b755a85cc9bdb4906c6b7a84a6
---
.../eclipse/jetty/servlets/GzipFilter.java | 12 +++-
.../jetty/servlets/GzipFilterDefaultTest.java | 70 +++++++++++++++++++
2 files changed, 81 insertions(+), 1 deletion(-)
diff --git a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java
index 1b993e6eedf..4428ec1e862 100644
--- a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java
+++ b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java
@@ -238,7 +238,7 @@ public class GzipFilter extends UserAgentFilter
return true;
}
}
- else if (_excludedAgentPatterns != null)
+ if (_excludedAgentPatterns != null)
{
for (Pattern pattern : _excludedAgentPatterns)
{
@@ -263,6 +263,16 @@ public class GzipFilter extends UserAgentFilter
{
if (requestURI == null)
return false;
+ if (_excludedPaths != null)
+ {
+ for (String excludedPath : _excludedPaths)
+ {
+ if (requestURI.contains(excludedPath))
+ {
+ return true;
+ }
+ }
+ }
if (_excludedPathPatterns != null)
{
for (Pattern pattern : _excludedPathPatterns)
diff --git a/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/GzipFilterDefaultTest.java b/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/GzipFilterDefaultTest.java
index 82fd54dc11f..b9f7081d138 100644
--- a/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/GzipFilterDefaultTest.java
+++ b/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/GzipFilterDefaultTest.java
@@ -25,6 +25,8 @@ public class GzipFilterDefaultTest
public static class HttpStatusServlet extends HttpServlet
{
+ private static final long serialVersionUID = 1L;
+
private int _status = 204;
public HttpStatusServlet()
@@ -159,4 +161,72 @@ public class GzipFilterDefaultTest
tester.stop();
}
}
+
+ @Test
+ public void testUserAgentExclusionByExcludedAgentPatterns() throws Exception
+ {
+ GzipTester tester = new GzipTester(testingdir);
+
+ FilterHolder holder = tester.setContentServlet(DefaultServlet.class);
+ holder.setInitParameter("excludedAgents", "bar");
+ holder.setInitParameter("excludeAgentPatterns", "fo.*");
+ tester.setUserAgent("foo");
+
+ int filesize = GzipResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
+ tester.prepareServerFile("file.txt",filesize);
+
+ try
+ {
+ tester.start();
+ tester.assertIsResponseNotGzipCompressed("file.txt", filesize, HttpStatus.OK_200);
+ }
+ finally
+ {
+ tester.stop();
+ }
+ }
+
+ @Test
+ public void testExcludePaths() throws Exception
+ {
+ GzipTester tester = new GzipTester(testingdir);
+
+ FilterHolder holder = tester.setContentServlet(DefaultServlet.class);
+ holder.setInitParameter("excludePaths", "/context/");
+
+ int filesize = GzipResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
+ tester.prepareServerFile("file.txt",filesize);
+
+ try
+ {
+ tester.start();
+ tester.assertIsResponseNotGzipCompressed("file.txt", filesize, HttpStatus.OK_200);
+ }
+ finally
+ {
+ tester.stop();
+ }
+ }
+
+ @Test
+ public void testExcludePathPatterns() throws Exception
+ {
+ GzipTester tester = new GzipTester(testingdir);
+
+ FilterHolder holder = tester.setContentServlet(DefaultServlet.class);
+ holder.setInitParameter("excludePathPatterns", "/cont.*");
+
+ int filesize = GzipResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
+ tester.prepareServerFile("file.txt",filesize);
+
+ try
+ {
+ tester.start();
+ tester.assertIsResponseNotGzipCompressed("file.txt", filesize, HttpStatus.OK_200);
+ }
+ finally
+ {
+ tester.stop();
+ }
+ }
}
From 942c8a19f56d31a9f7305b31ca3bd714518723b7 Mon Sep 17 00:00:00 2001
From: Jan Bartel
Date: Wed, 11 Apr 2012 19:53:55 +1000
Subject: [PATCH 32/36] 373269 Make ServletHandler.notFound() method impl do
nothing - override to send back 404.
---
.../src/main/java/org/eclipse/jetty/servlet/ServletHandler.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java
index b9e2c24e58f..76f360592ad 100644
--- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java
+++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java
@@ -1233,7 +1233,7 @@ public class ServletHandler extends ScopedHandler
{
if(LOG.isDebugEnabled())
LOG.debug("Not Found "+request.getRequestURI());
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
+ //Override to send an error back, eg with: response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/* ------------------------------------------------------------ */
From 972087d0684fa46341e7c6ef32dcd95c407400c1 Mon Sep 17 00:00:00 2001
From: Simone Bordet
Date: Wed, 11 Apr 2012 12:18:56 +0200
Subject: [PATCH 33/36] 376201 - HalfClosed state not handled properly.
---
.../java/org/eclipse/jetty/spdy/IStream.java | 3 +-
.../eclipse/jetty/spdy/StandardSession.java | 11 ++-
.../eclipse/jetty/spdy/StandardStream.java | 80 ++++++++++++++-----
.../eclipse/jetty/spdy/FlowControlTest.java | 2 +-
...eTest.java => ProtocolViolationsTest.java} | 68 +++++++++++++++-
5 files changed, 141 insertions(+), 23 deletions(-)
rename jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/{APIUsageTest.java => ProtocolViolationsTest.java} (58%)
diff --git a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/IStream.java b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/IStream.java
index 86e3bd98066..2291cf78b64 100644
--- a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/IStream.java
+++ b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/IStream.java
@@ -68,8 +68,9 @@ public interface IStream extends Stream
* of true puts the stream into closed state.
*
* @param close whether the close state should be updated
+ * @param local whether the close is local or remote
*/
- public void updateCloseState(boolean close);
+ public void updateCloseState(boolean close, boolean local);
/**
* Processes the given control frame,
diff --git a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java
index 4caa3df86c4..8b1a53dda42 100644
--- a/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java
+++ b/jetty-spdy/spdy-core/src/main/java/org/eclipse/jetty/spdy/StandardSession.java
@@ -398,6 +398,7 @@ public class StandardSession implements ISession, Parser.Listener, Handler frameBytes = new ControlFrameBytes<>(stream, handler, context, frame, buffer);
if (timeout > 0)
frameBytes.task = scheduler.schedule(frameBytes, timeout, unit);
- append(frameBytes);
+
+ // Special handling for PING frames, they must be sent as soon as possible
+ if (ControlFrameType.PING == frame.getType())
+ prepend(frameBytes);
+ else
+ append(frameBytes);
}
flush();
@@ -1089,7 +1096,7 @@ public class StandardSession implements ISession, Parser.Listener, Handler handler)
{
openState = OpenState.REPLY_SENT;
- updateCloseState(replyInfo.isClose());
+ updateCloseState(replyInfo.isClose(), true);
SynReplyFrame frame = new SynReplyFrame(session.getVersion(), replyInfo.getFlags(), getId(), replyInfo.getHeaders());
session.control(this, frame, timeout, unit, handler, null);
}
@@ -306,7 +329,12 @@ public class StandardStream implements IStream
if (!canSend())
{
session.rst(new RstInfo(getId(), StreamStatus.PROTOCOL_ERROR));
- throw new IllegalStateException("Cannot send DATA frames before a SYN_REPLY frame");
+ throw new IllegalStateException("Protocol violation: cannot send a DATA frame before a SYN_REPLY frame");
+ }
+ if (isLocallyClosed())
+ {
+ session.rst(new RstInfo(getId(), StreamStatus.PROTOCOL_ERROR));
+ throw new IllegalStateException("Protocol violation: cannot send a DATA frame on a closed stream");
}
// Cannot update the close state here, because the data that we send may
@@ -328,10 +356,15 @@ public class StandardStream implements IStream
if (!canSend())
{
session.rst(new RstInfo(getId(), StreamStatus.PROTOCOL_ERROR));
- throw new IllegalStateException("Cannot send a HEADERS frame before a SYN_REPLY frame");
+ throw new IllegalStateException("Protocol violation: cannot send a HEADERS frame before a SYN_REPLY frame");
+ }
+ if (isLocallyClosed())
+ {
+ session.rst(new RstInfo(getId(), StreamStatus.PROTOCOL_ERROR));
+ throw new IllegalStateException("Protocol violation: cannot send a HEADERS frame on a closed stream");
}
- updateCloseState(headersInfo.isClose());
+ updateCloseState(headersInfo.isClose(), true);
HeadersFrame frame = new HeadersFrame(session.getVersion(), headersInfo.getFlags(), getId(), headersInfo.getHeaders());
session.control(this, frame, timeout, unit, handler, null);
}
@@ -339,13 +372,19 @@ public class StandardStream implements IStream
@Override
public boolean isClosed()
{
- return closed;
+ return closeState == CloseState.CLOSED;
+ }
+
+ private boolean isLocallyClosed()
+ {
+ CloseState closeState = this.closeState;
+ return closeState == CloseState.LOCALLY_CLOSED || closeState == CloseState.CLOSED;
}
@Override
public String toString()
{
- return String.format("stream=%d v%d closed=%s", getId(), session.getVersion(), isClosed() ? "true" : isHalfClosed() ? "half" : "false");
+ return String.format("stream=%d v%d %s", getId(), session.getVersion(), closeState);
}
private boolean canSend()
@@ -364,4 +403,9 @@ public class StandardStream implements IStream
{
SYN_SENT, SYN_RECV, REPLY_SENT, REPLY_RECV
}
+
+ private enum CloseState
+ {
+ OPENED, LOCALLY_CLOSED, REMOTELY_CLOSED, CLOSED
+ }
}
diff --git a/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/FlowControlTest.java b/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/FlowControlTest.java
index 6e246409d58..f1908e73bcc 100644
--- a/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/FlowControlTest.java
+++ b/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/FlowControlTest.java
@@ -307,7 +307,7 @@ public class FlowControlTest extends AbstractTest
Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS));
- Stream stream = session.syn(new SynInfo(true), null).get(5, TimeUnit.SECONDS);
+ Stream stream = session.syn(new SynInfo(false), null).get(5, TimeUnit.SECONDS);
final int length = 5 * windowSize;
stream.data(new BytesDataInfo(new byte[length], true));
diff --git a/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/APIUsageTest.java b/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/ProtocolViolationsTest.java
similarity index 58%
rename from jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/APIUsageTest.java
rename to jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/ProtocolViolationsTest.java
index 36a0a2cb7bf..92e642f2b13 100644
--- a/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/APIUsageTest.java
+++ b/jetty-spdy/spdy-jetty/src/test/java/org/eclipse/jetty/spdy/ProtocolViolationsTest.java
@@ -8,6 +8,9 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.spdy.api.BytesDataInfo;
+import org.eclipse.jetty.spdy.api.DataInfo;
+import org.eclipse.jetty.spdy.api.Headers;
+import org.eclipse.jetty.spdy.api.HeadersInfo;
import org.eclipse.jetty.spdy.api.RstInfo;
import org.eclipse.jetty.spdy.api.SPDY;
import org.eclipse.jetty.spdy.api.Session;
@@ -21,11 +24,12 @@ import org.eclipse.jetty.spdy.api.SynInfo;
import org.eclipse.jetty.spdy.api.server.ServerSessionFrameListener;
import org.eclipse.jetty.spdy.frames.ControlFrameType;
import org.eclipse.jetty.spdy.frames.GoAwayFrame;
+import org.eclipse.jetty.spdy.frames.SynReplyFrame;
import org.eclipse.jetty.spdy.generator.Generator;
import org.junit.Assert;
import org.junit.Test;
-public class APIUsageTest extends AbstractTest
+public class ProtocolViolationsTest extends AbstractTest
{
@Test
public void testSendDataBeforeReplyIsIllegal() throws Exception
@@ -95,4 +99,66 @@ public class APIUsageTest extends AbstractTest
server.close();
}
+
+ @Test(expected = IllegalStateException.class)
+ public void testSendDataAfterCloseIsIllegal() throws Exception
+ {
+ Session session = startClient(startServer(null), null);
+ Stream stream = session.syn(new SynInfo(true), null).get(5, TimeUnit.SECONDS);
+ stream.data(new StringDataInfo("test", true));
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void testSendHeadersAfterCloseIsIllegal() throws Exception
+ {
+ Session session = startClient(startServer(null), null);
+ Stream stream = session.syn(new SynInfo(true), null).get(5, TimeUnit.SECONDS);
+ stream.headers(new HeadersInfo(new Headers(), true));
+ }
+
+ @Test
+ public void testDataSentAfterCloseIsDiscardedByRecipient() throws Exception
+ {
+ ServerSocketChannel server = ServerSocketChannel.open();
+ server.bind(new InetSocketAddress("localhost", 0));
+
+ Session session = startClient(new InetSocketAddress("localhost", server.socket().getLocalPort()), null);
+ final CountDownLatch dataLatch = new CountDownLatch(2);
+ session.syn(new SynInfo(true), new StreamFrameListener.Adapter()
+ {
+ @Override
+ public void onData(Stream stream, DataInfo dataInfo)
+ {
+ dataLatch.countDown();
+ }
+ });
+
+ SocketChannel channel = server.accept();
+ ByteBuffer readBuffer = ByteBuffer.allocate(1024);
+ channel.read(readBuffer);
+ readBuffer.flip();
+ int streamId = readBuffer.getInt(8);
+
+ Generator generator = new Generator(new StandardByteBufferPool(), new StandardCompressionFactory.StandardCompressor());
+
+ ByteBuffer writeBuffer = generator.control(new SynReplyFrame(SPDY.V2, (byte)0, streamId, new Headers()));
+ channel.write(writeBuffer);
+
+ byte[] bytes = new byte[1];
+ writeBuffer = generator.data(streamId, bytes.length, new BytesDataInfo(bytes, true));
+ channel.write(writeBuffer);
+
+ // Write again to simulate the faulty condition
+ writeBuffer.flip();
+ channel.write(writeBuffer);
+
+ Assert.assertFalse(dataLatch.await(1, TimeUnit.SECONDS));
+
+ writeBuffer = generator.control(new GoAwayFrame(SPDY.V2, 0, SessionStatus.OK.getCode()));
+ channel.write(writeBuffer);
+ channel.shutdownOutput();
+ channel.close();
+
+ server.close();
+ }
}
From 543d2a18caf3d10c2b3a91014d8fe93124ce7f69 Mon Sep 17 00:00:00 2001
From: Thomas Becker
Date: Wed, 11 Apr 2012 13:03:33 +0200
Subject: [PATCH 34/36] 376373: GzipFilter now does not ignore _excludePath +
fix for ignored _excludeAgentPatterns if _excludeAgent is set
Change-Id: I8d3d0fd62677c3a54cbe93febf4cde49aa24cc74
---
.../src/main/java/org/eclipse/jetty/servlets/GzipFilter.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java
index db36f51f220..94d50dee76d 100644
--- a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java
+++ b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java
@@ -350,7 +350,7 @@ public class GzipFilter extends UserAgentFilter
{
for (String excludedPath : _excludedPaths)
{
- if (requestURI.contains(excludedPath))
+ if (requestURI.startsWith(excludedPath))
{
return true;
}
From 08573701efc447fb95da22bfc711f79b6908a60e Mon Sep 17 00:00:00 2001
From: Thomas Becker
Date: Wed, 11 Apr 2012 14:47:28 +0200
Subject: [PATCH 35/36] 376373: GzipFilter now does not ignore _excludePath +
fix for ignored _excludeAgentPatterns if _excludeAgent is set
Change-Id: Ie9940141f9b92b267f4b405ef4ec3ab5dee43be5
---
.../eclipse/jetty/servlets/GzipFilter.java | 6 +-
.../jetty/servlets/GzipFilterDefaultTest.java | 79 +++++++++----------
2 files changed, 42 insertions(+), 43 deletions(-)
diff --git a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java
index 94d50dee76d..650632b7f38 100644
--- a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java
+++ b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/GzipFilter.java
@@ -303,7 +303,7 @@ public class GzipFilter extends UserAgentFilter
}
/**
- * Checks to see if the UserAgent is excluded
+ * Checks to see if the userAgent is excluded
*
* @param ua
* the user agent
@@ -336,9 +336,9 @@ public class GzipFilter extends UserAgentFilter
}
/**
- * Checks to see if the Path is excluded
+ * Checks to see if the path is excluded
*
- * @param ua
+ * @param requestURI
* the request uri
* @return boolean true if excluded
*/
diff --git a/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/GzipFilterDefaultTest.java b/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/GzipFilterDefaultTest.java
index 89f2f458534..05f53c97e3e 100644
--- a/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/GzipFilterDefaultTest.java
+++ b/jetty-servlets/src/test/java/org/eclipse/jetty/servlets/GzipFilterDefaultTest.java
@@ -31,11 +31,10 @@ public class GzipFilterDefaultTest
public static Collection data()
{
String[][] data = new String[][]
- {
- { GzipFilter.GZIP },
- { GzipFilter.DEFLATE }
- };
-
+ {
+ { GzipFilter.GZIP },
+ { GzipFilter.DEFLATE } };
+
return Arrays.asList(data);
}
@@ -166,88 +165,88 @@ public class GzipFilterDefaultTest
@Test
public void testUserAgentExclusion() throws Exception
{
- GzipTester tester = new GzipTester(testingdir, compressionType);
-
+ GzipTester tester = new GzipTester(testingdir,compressionType);
+
FilterHolder holder = tester.setContentServlet(DefaultServlet.class);
- holder.setInitParameter("excludedAgents", "foo");
+ holder.setInitParameter("excludedAgents","foo");
tester.setUserAgent("foo");
-
+
int filesize = CompressedResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
tester.prepareServerFile("file.txt",filesize);
-
+
try
{
tester.start();
- tester.assertIsResponseNotGzipCompressed("file.txt", filesize, HttpStatus.OK_200);
- }
+ tester.assertIsResponseNotGzipCompressed("file.txt",filesize,HttpStatus.OK_200);
+ }
finally
{
tester.stop();
}
}
-
+
@Test
public void testUserAgentExclusionByExcludedAgentPatterns() throws Exception
{
- GzipTester tester = new GzipTester(testingdir);
-
+ GzipTester tester = new GzipTester(testingdir,compressionType);
+
FilterHolder holder = tester.setContentServlet(DefaultServlet.class);
- holder.setInitParameter("excludedAgents", "bar");
- holder.setInitParameter("excludeAgentPatterns", "fo.*");
+ holder.setInitParameter("excludedAgents","bar");
+ holder.setInitParameter("excludeAgentPatterns","fo.*");
tester.setUserAgent("foo");
-
- int filesize = GzipResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
+
+ int filesize = CompressedResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
tester.prepareServerFile("file.txt",filesize);
-
+
try
{
tester.start();
- tester.assertIsResponseNotGzipCompressed("file.txt", filesize, HttpStatus.OK_200);
- }
+ tester.assertIsResponseNotGzipCompressed("file.txt",filesize,HttpStatus.OK_200);
+ }
finally
{
tester.stop();
}
}
-
+
@Test
public void testExcludePaths() throws Exception
{
- GzipTester tester = new GzipTester(testingdir);
-
+ GzipTester tester = new GzipTester(testingdir,compressionType);
+
FilterHolder holder = tester.setContentServlet(DefaultServlet.class);
- holder.setInitParameter("excludePaths", "/context/");
-
- int filesize = GzipResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
+ holder.setInitParameter("excludePaths","/context/");
+
+ int filesize = CompressedResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
tester.prepareServerFile("file.txt",filesize);
-
+
try
{
tester.start();
- tester.assertIsResponseNotGzipCompressed("file.txt", filesize, HttpStatus.OK_200);
- }
+ tester.assertIsResponseNotGzipCompressed("file.txt",filesize,HttpStatus.OK_200);
+ }
finally
{
tester.stop();
}
}
-
+
@Test
public void testExcludePathPatterns() throws Exception
{
- GzipTester tester = new GzipTester(testingdir);
-
+ GzipTester tester = new GzipTester(testingdir,compressionType);
+
FilterHolder holder = tester.setContentServlet(DefaultServlet.class);
- holder.setInitParameter("excludePathPatterns", "/cont.*");
-
- int filesize = GzipResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
+ holder.setInitParameter("excludePathPatterns","/cont.*");
+
+ int filesize = CompressedResponseWrapper.DEFAULT_BUFFER_SIZE * 4;
tester.prepareServerFile("file.txt",filesize);
-
+
try
{
tester.start();
- tester.assertIsResponseNotGzipCompressed("file.txt", filesize, HttpStatus.OK_200);
- }
+ tester.assertIsResponseNotGzipCompressed("file.txt",filesize,HttpStatus.OK_200);
+ }
finally
{
tester.stop();
From c9ce3eb108a1362b73ed54a4c6d24fa47edd002f Mon Sep 17 00:00:00 2001
From: Greg Wilkins
Date: Thu, 12 Apr 2012 11:32:28 +1000
Subject: [PATCH 36/36] 362113: fixed StdErrLog so that it does not hold a copy
of System.err and thus avoid being redirected if System.err is redirected
---
.../org/eclipse/jetty/util/log/StdErrLog.java | 18 +++++++++---------
1 file changed, 9 insertions(+), 9 deletions(-)
diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/log/StdErrLog.java b/jetty-util/src/main/java/org/eclipse/jetty/util/log/StdErrLog.java
index 1848e7ad8c6..7636bd870dc 100644
--- a/jetty-util/src/main/java/org/eclipse/jetty/util/log/StdErrLog.java
+++ b/jetty-util/src/main/java/org/eclipse/jetty/util/log/StdErrLog.java
@@ -77,7 +77,7 @@ public class StdErrLog extends AbstractLogger
private int _level = LEVEL_INFO;
// Level that this Logger was configured as (remembered in special case of .setDebugEnabled())
private int _configuredLevel;
- private PrintStream _stderr = System.err;
+ private PrintStream _stderr = null;
private boolean _source = __source;
// Print the long form names, otherwise use abbreviated
private boolean _printLongNames = __long;
@@ -271,7 +271,7 @@ public class StdErrLog extends AbstractLogger
{
StringBuilder buffer = new StringBuilder(64);
format(buffer,":WARN:",msg,args);
- _stderr.println(buffer);
+ (_stderr==null?System.err:_stderr).println(buffer);
}
}
@@ -286,7 +286,7 @@ public class StdErrLog extends AbstractLogger
{
StringBuilder buffer = new StringBuilder(64);
format(buffer,":WARN:",msg,thrown);
- _stderr.println(buffer);
+ (_stderr==null?System.err:_stderr).println(buffer);
}
}
@@ -296,7 +296,7 @@ public class StdErrLog extends AbstractLogger
{
StringBuilder buffer = new StringBuilder(64);
format(buffer,":INFO:",msg,args);
- _stderr.println(buffer);
+ (_stderr==null?System.err:_stderr).println(buffer);
}
}
@@ -311,7 +311,7 @@ public class StdErrLog extends AbstractLogger
{
StringBuilder buffer = new StringBuilder(64);
format(buffer,":INFO:",msg,thrown);
- _stderr.println(buffer);
+ (_stderr==null?System.err:_stderr).println(buffer);
}
}
@@ -369,7 +369,7 @@ public class StdErrLog extends AbstractLogger
public void setStdErrStream(PrintStream stream)
{
- this._stderr = stream;
+ this._stderr = stream==System.err?null:stream;
}
public void debug(String msg, Object... args)
@@ -378,7 +378,7 @@ public class StdErrLog extends AbstractLogger
{
StringBuilder buffer = new StringBuilder(64);
format(buffer,":DBUG:",msg,args);
- _stderr.println(buffer);
+ (_stderr==null?System.err:_stderr).println(buffer);
}
}
@@ -393,7 +393,7 @@ public class StdErrLog extends AbstractLogger
{
StringBuilder buffer = new StringBuilder(64);
format(buffer,":DBUG:",msg,thrown);
- _stderr.println(buffer);
+ (_stderr==null?System.err:_stderr).println(buffer);
}
}
@@ -616,7 +616,7 @@ public class StdErrLog extends AbstractLogger
{
StringBuilder buffer = new StringBuilder(64);
format(buffer,":IGNORED:","",ignored);
- _stderr.println(buffer);
+ (_stderr==null?System.err:_stderr).println(buffer);
}
}
}