Jetty 10.0.x reformat (#3812)

* Removing Legacy Method Separators
* Restyling branch `jetty-9.4.x`
* Applying changes highlighted by checkstyle
* Removing Legacy Method Separators
* Restyling branch `jetty-10.0.x`
* Applying checkstyle changes
* Applying checkstyle changes
* Applying XML restyling
* Restyling XML in branch `jetty-10.0.x`
* Fixing XML codestyle for IntelliJ
* Fixing XML style mistakes
* Fixing XML restyling in branch `jetty-10.0.x`
* Revert "Applying XML restyling"
* Updating checkstyle for XML codestyle
* Revert "Restyling XML in branch `jetty-10.0.x`"

# Conflicts:
#	jetty-xml/src/test/resources/org/eclipse/jetty/xml/configureWithAttr.xml
#	jetty-xml/src/test/resources/org/eclipse/jetty/xml/configureWithElements.xml

* Adding back build-resources
* Reformatting pom.xml files
* Disabling Checkstyle job
* fixed empty string on line wrap
* reformatted with latest intellij style
* misc checkstyle fixes

Signed-off-by: Joakim Erdfelt <joakim.erdfelt@gmail.com>
Signed-off-by: Greg Wilkins <gregw@webtide.com>
This commit is contained in:
Greg Wilkins 2019-06-24 17:42:39 +02:00 committed by GitHub
parent 804419bf89
commit b7a7a53a18
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2314 changed files with 62953 additions and 67347 deletions

5
Jenkinsfile vendored
View File

@ -60,6 +60,7 @@ pipeline {
}
}
*/
/*
stage("Checkstyle ") {
agent { node { label 'linux' } }
options { timeout(time: 30, unit: 'MINUTES') }
@ -67,11 +68,11 @@ pipeline {
mavenBuild("jdk11", "install checkstyle:checkstyle -DskipTests", "maven3", true)
recordIssues(
enabledForFailure: true, aggregatingResults: true,
tools: [java(), checkStyle(pattern: '**/target/checkstyle-result.xml', reportEncoding: 'UTF-8')]
tools: [java(), checkStyle(pattern: '** /target/checkstyle-result.xml', reportEncoding: 'UTF-8')]
)
}
}
*/
}
}
}

View File

@ -63,8 +63,7 @@
</goals>
<configuration>
<archive>
<manifest>
</manifest>
<manifest></manifest>
<manifestEntries>
<mode>development</mode>
<url>http://eclipse.org/jetty</url>

View File

@ -1,5 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-project</artifactId>
@ -24,11 +23,9 @@
<instructions>
<Bundle-Description>Jetty-specific ServletContainerInitializer for Jasper</Bundle-Description>
<Export-Package>
org.eclipse.jetty.apache.jsp.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}",
org.eclipse.jetty.jsp.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}"
org.eclipse.jetty.apache.jsp.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}", org.eclipse.jetty.jsp.*;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}"
</Export-Package>
<Require-Capability>osgi.extender;
filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional
<Require-Capability>osgi.extender; filter:="(osgi.extender=osgi.serviceloader.registrar)";resolution:=optional
</Require-Capability>
<Provide-Capability>
osgi.serviceloader;osgi.serviceloader=javax.servlet.ServletContainerInitializer,osgi.serviceloader;osgi.serviceloader=org.apache.juli.logging.Log

View File

@ -23,7 +23,6 @@ import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.jasper.servlet.JasperInitializer;
@ -38,6 +37,7 @@ import org.xml.sax.SAXException;
public class JettyJasperInitializer extends JasperInitializer
{
private static final Log LOG = LogFactory.getLog(JasperInitializer.class);
/**
* NullTldScanner
*
@ -47,10 +47,7 @@ public class JettyJasperInitializer extends JasperInitializer
private final class NullTldScanner extends TldScanner
{
/**
* @param context
* @param namespaceAware
* @param validation
* @param blockExternal
*
*/
private NullTldScanner(ServletContext context, boolean namespaceAware, boolean validation, boolean blockExternal)
{
@ -93,20 +90,23 @@ public class JettyJasperInitializer extends JasperInitializer
public TldScanner newTldScanner(ServletContext context, boolean namespaceAware, boolean validate, boolean blockExternal)
{
String tmp = context.getInitParameter("org.eclipse.jetty.jsp.precompiled");
if (tmp!=null && !tmp.equals("") && Boolean.valueOf(tmp))
if (tmp != null && !tmp.equals("") && Boolean.valueOf(tmp))
{
if (LOG.isDebugEnabled()) LOG.debug("Jsp precompilation detected");
if (LOG.isDebugEnabled())
LOG.debug("Jsp precompilation detected");
return new NullTldScanner(context, namespaceAware, validate, blockExternal);
}
Collection<URL> tldUrls = (Collection<URL>)context.getAttribute("org.eclipse.jetty.tlds");
if (tldUrls != null)
{
if (LOG.isDebugEnabled()) LOG.debug("Tld pre-scan detected");
return new JettyTldPreScanned(context,namespaceAware,validate,blockExternal,tldUrls);
if (LOG.isDebugEnabled())
LOG.debug("Tld pre-scan detected");
return new JettyTldPreScanned(context, namespaceAware, validate, blockExternal, tldUrls);
}
if (LOG.isDebugEnabled()) LOG.debug("Defaulting to jasper tld scanning");
if (LOG.isDebugEnabled())
LOG.debug("Defaulting to jasper tld scanning");
return super.newTldScanner(context, namespaceAware, validate, blockExternal);
}
}

View File

@ -16,12 +16,10 @@
// ========================================================================
//
package org.eclipse.jetty.apache.jsp;
import java.net.URL;
import java.util.Collection;
import javax.servlet.ServletContext;
import org.apache.jasper.servlet.TldPreScanned;
@ -39,7 +37,6 @@ import org.apache.tomcat.util.descriptor.tld.TldResourcePath;
* may be in the reactor at the same time as a webapp being run with the
* plugin. That means that the tlds will be used from their location in
* the file system, rather than from their assembled jar.
*
*/
public class JettyTldPreScanned extends TldPreScanned
{
@ -65,7 +62,7 @@ public class JettyTldPreScanned extends TldPreScanned
int a = str.indexOf("jar:");
int b = str.indexOf("META-INF");
if (b < 0)
throw new IllegalStateException("Bad tld url: "+str);
throw new IllegalStateException("Bad tld url: " + str);
String path = str.substring(b);
if (a >= 0)
@ -95,5 +92,4 @@ public class JettyTldPreScanned extends TldPreScanned
}
}
}
}

View File

@ -30,14 +30,14 @@ public class JuliLog implements org.apache.juli.logging.Log
public JuliLog()
{
_logger=org.eclipse.jetty.util.log.Log.getRootLogger();
_stdErrLog=(_logger instanceof org.eclipse.jetty.util.log.StdErrLog) ? (org.eclipse.jetty.util.log.StdErrLog)_logger:null;
_logger = org.eclipse.jetty.util.log.Log.getRootLogger();
_stdErrLog = (_logger instanceof org.eclipse.jetty.util.log.StdErrLog) ? (org.eclipse.jetty.util.log.StdErrLog)_logger : null;
}
public JuliLog(String name)
{
_logger=org.eclipse.jetty.util.log.Log.getLogger(name);
_stdErrLog=(_logger instanceof org.eclipse.jetty.util.log.StdErrLog) ? (org.eclipse.jetty.util.log.StdErrLog)_logger:null;
_logger = org.eclipse.jetty.util.log.Log.getLogger(name);
_stdErrLog = (_logger instanceof org.eclipse.jetty.util.log.StdErrLog) ? (org.eclipse.jetty.util.log.StdErrLog)_logger : null;
}
@Override
@ -49,31 +49,31 @@ public class JuliLog implements org.apache.juli.logging.Log
@Override
public boolean isErrorEnabled()
{
return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN;
return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN;
}
@Override
public boolean isFatalEnabled()
{
return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN;
return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN;
}
@Override
public boolean isInfoEnabled()
{
return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_INFO;
return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_INFO;
}
@Override
public boolean isTraceEnabled()
{
return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_DEBUG;
return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_DEBUG;
}
@Override
public boolean isWarnEnabled()
{
return _stdErrLog==null?true:_stdErrLog.getLevel()<=org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN;
return _stdErrLog == null ? true : _stdErrLog.getLevel() <= org.eclipse.jetty.util.log.StdErrLog.LEVEL_WARN;
}
@Override
@ -82,16 +82,16 @@ public class JuliLog implements org.apache.juli.logging.Log
if (message instanceof String)
_logger.debug((String)message);
else
_logger.debug("{}",message);
_logger.debug("{}", message);
}
@Override
public void trace(Object message, Throwable t)
{
if (message instanceof String)
_logger.debug((String)message,t);
_logger.debug((String)message, t);
else
_logger.debug("{}",message,t);
_logger.debug("{}", message, t);
}
@Override
@ -100,16 +100,16 @@ public class JuliLog implements org.apache.juli.logging.Log
if (message instanceof String)
_logger.debug((String)message);
else
_logger.debug("{}",message);
_logger.debug("{}", message);
}
@Override
public void debug(Object message, Throwable t)
{
if (message instanceof String)
_logger.debug((String)message,t);
_logger.debug((String)message, t);
else
_logger.debug("{}",message,t);
_logger.debug("{}", message, t);
}
@Override
@ -118,16 +118,16 @@ public class JuliLog implements org.apache.juli.logging.Log
if (message instanceof String)
_logger.info((String)message);
else
_logger.info("{}",message);
_logger.info("{}", message);
}
@Override
public void info(Object message, Throwable t)
{
if (message instanceof String)
_logger.info((String)message,t);
_logger.info((String)message, t);
else
_logger.info("{}",message,t);
_logger.info("{}", message, t);
}
@Override
@ -136,16 +136,16 @@ public class JuliLog implements org.apache.juli.logging.Log
if (message instanceof String)
_logger.warn((String)message);
else
_logger.warn("{}",message);
_logger.warn("{}", message);
}
@Override
public void warn(Object message, Throwable t)
{
if (message instanceof String)
_logger.warn((String)message,t);
_logger.warn((String)message, t);
else
_logger.warn("{}",message,t);
_logger.warn("{}", message, t);
}
@Override
@ -154,16 +154,16 @@ public class JuliLog implements org.apache.juli.logging.Log
if (message instanceof String)
_logger.warn((String)message);
else
_logger.warn("{}",message);
_logger.warn("{}", message);
}
@Override
public void error(Object message, Throwable t)
{
if (message instanceof String)
_logger.warn((String)message,t);
_logger.warn((String)message, t);
else
_logger.warn("{}",message,t);
_logger.warn("{}", message, t);
}
@Override
@ -172,16 +172,16 @@ public class JuliLog implements org.apache.juli.logging.Log
if (message instanceof String)
_logger.warn((String)message);
else
_logger.warn("{}",message);
_logger.warn("{}", message);
}
@Override
public void fatal(Object message, Throwable t)
{
if (message instanceof String)
_logger.warn((String)message,t);
_logger.warn((String)message, t);
else
_logger.warn("{}",message,t);
_logger.warn("{}", message, t);
}
}

View File

@ -22,7 +22,6 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -30,7 +29,6 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.jasper.servlet.JspServlet;
/**
* JettyJspServlet
*
@ -46,10 +44,6 @@ public class JettyJspServlet extends JspServlet
*/
private static final long serialVersionUID = -5387857473125086791L;
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
@ -59,16 +53,16 @@ public class JettyJspServlet extends JspServlet
else
throw new ServletException("Request not HttpServletRequest");
String servletPath=null;
String pathInfo=null;
if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI)!=null)
String servletPath = null;
String pathInfo = null;
if (request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null)
{
servletPath=(String)request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
pathInfo=(String)request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
if (servletPath==null)
servletPath = (String)request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
pathInfo = (String)request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
if (servletPath == null)
{
servletPath=request.getServletPath();
pathInfo=request.getPathInfo();
servletPath = request.getServletPath();
pathInfo = request.getPathInfo();
}
}
else
@ -77,7 +71,7 @@ public class JettyJspServlet extends JspServlet
pathInfo = request.getPathInfo();
}
String pathInContext = addPaths(servletPath,pathInfo);
String pathInContext = addPaths(servletPath, pathInfo);
String jspFile = getInitParameter("jspFile");
@ -122,9 +116,9 @@ public class JettyJspServlet extends JspServlet
if (servletPath.isEmpty())
return pathInfo;
if (pathInfo==null)
if (pathInfo == null)
return servletPath;
return servletPath+pathInfo;
return servletPath + pathInfo;
}
}

View File

@ -22,7 +22,6 @@ import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -72,11 +71,10 @@ public class TestJettyJspServlet
resp.setContentType("html/text");
resp.getOutputStream().println("This.Is.The.Default.");
}
}
@BeforeEach
public void setUp () throws Exception
public void setUp() throws Exception
{
JspFactory.setDefaultFactory(new JspFactoryImpl());
_dir = MavenTestingUtils.getTestResourceDir("base");
@ -88,7 +86,7 @@ public class TestJettyJspServlet
_tester.getContext().setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
ServletHolder dfltHolder = new ServletHolder();
dfltHolder.setName("default");
dfltHolder.setHeldClass( DfltServlet.class);
dfltHolder.setHeldClass(DfltServlet.class);
_tester.getContext().addServlet(dfltHolder, "/");
_tester.start();
@ -105,7 +103,7 @@ public class TestJettyJspServlet
public void testWithJsp() throws Exception
{
//test that an ordinary jsp is served by jsp servlet
String request = "" +
String request =
"GET /context/foo.jsp HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Connection: close\r\n" +
@ -116,12 +114,11 @@ public class TestJettyJspServlet
assertThat(response.toString(), response.getContent(), not(containsString("This.Is.The.Default.")));
}
@Test
public void testWithDirectory() throws Exception
{
//test that a dir is served by the default servlet
String request = "" +
String request =
"GET /context/dir HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Connection: close\r\n" +

View File

@ -16,11 +16,8 @@
// ========================================================================
//
package org.eclipse.jetty.jsp;
import static org.junit.jupiter.api.Assertions.*;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
@ -34,10 +31,12 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
/**
* TestJettyTldPreScanned
*
*
*/
public class TestJettyTldPreScanned
{
@ -53,15 +52,15 @@ public class TestJettyTldPreScanned
File tld = MavenTestingUtils.getTestResourceFile("META-INF/foo-taglib.tld");
List<URL> list = new ArrayList<>();
list.add(new URL("jar:"+jar.toURI().toURL().toString()+"!/META-INF/bar-taglib.tld"));
list.add(new URL("jar:" + jar.toURI().toURL().toString() + "!/META-INF/bar-taglib.tld"));
list.add(tld.toURI().toURL());
JettyTldPreScanned preScanned = new JettyTldPreScanned(new ServletContextHandler().getServletContext(),false,false,false,list);
JettyTldPreScanned preScanned = new JettyTldPreScanned(new ServletContextHandler().getServletContext(), false, false, false, list);
preScanned.scanJars();
Map<TldResourcePath, TaglibXml> map = preScanned.getTldResourcePathTaglibXmlMap();
assertNotNull(map);
assertEquals(2, map.size());
for (TldResourcePath p: map.keySet())
for (TldResourcePath p : map.keySet())
{
URL u = p.getUrl();
TaglibXml tlx = map.get(p);
@ -70,5 +69,4 @@ public class TestJettyTldPreScanned
fail("unknown tag");
}
}
}

View File

@ -18,12 +18,11 @@
package org.eclipse.jetty.jsp;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestJspFileNameToClass
{
@ -33,7 +32,6 @@ public class TestJspFileNameToClass
ServletHolder h = new ServletHolder();
h.setName("test");
assertEquals(null, h.getClassNameForJsp(null));
assertEquals(null, h.getClassNameForJsp(""));
@ -56,5 +54,4 @@ public class TestJspFileNameToClass
assertEquals("org.apache.jsp.a.b.c.blah_jsp", h.getClassNameForJsp("a/b/c/blah.jsp"));
}
}

View File

@ -18,10 +18,6 @@
package org.eclipse.jetty.jstl;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@ -37,7 +33,6 @@ import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.IO;
import org.eclipse.jetty.toolchain.test.JAR;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.Configurations;
import org.eclipse.jetty.webapp.JettyWebXmlConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
@ -45,6 +40,10 @@ import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
public class JspIncludeTest
{
private static Server server;
@ -69,7 +68,7 @@ public class JspIncludeTest
JAR.create(testTagLibDir, new File(libDir, "testtaglib.jar"));
// Configure WebAppContext
Configurations.setServerDefault(server).add(new JettyWebXmlConfiguration(),new AnnotationConfiguration());
Configurations.setServerDefault(server).add(new JettyWebXmlConfiguration(), new AnnotationConfiguration());
WebAppContext context = new WebAppContext();
context.setContextPath("/");
@ -111,7 +110,7 @@ public class JspIncludeTest
try
{
connection = (HttpURLConnection) uri.toURL().openConnection();
connection = (HttpURLConnection)uri.toURL().openConnection();
connection.connect();
if (HttpURLConnection.HTTP_OK != connection.getResponseCode())
{

View File

@ -18,18 +18,12 @@
package org.eclipse.jetty.jstl;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import javax.servlet.jsp.JspException;
import org.eclipse.jetty.annotations.AnnotationConfiguration;
@ -39,12 +33,16 @@ import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.JAR;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
public class JstlTest
{
private static Server server;
@ -66,7 +64,7 @@ public class JstlTest
File libDir = new File(testWebAppDir, "WEB-INF/lib");
FS.ensureDirExists(libDir);
File testTagLibDir = MavenTestingUtils.getProjectDir("src/test/taglibjar");
JAR.create(testTagLibDir,new File(libDir, "testtaglib.jar"));
JAR.create(testTagLibDir, new File(libDir, "testtaglib.jar"));
// Configure WebAppCont
WebAppContext context = new WebAppContext();
@ -74,11 +72,10 @@ public class JstlTest
File scratchDir = MavenTestingUtils.getTargetFile("tests/" + JstlTest.class.getSimpleName() + "-scratch");
FS.ensureEmpty(scratchDir);
JspConfig.init(context,testWebAppDir.toURI(),scratchDir);
JspConfig.init(context, testWebAppDir.toURI(), scratchDir);
context.addConfiguration(new AnnotationConfiguration());
server.setHandler(context);
// Start Server
@ -91,7 +88,7 @@ public class JstlTest
host = "localhost";
}
int port = connector.getLocalPort();
baseUri = new URI(String.format("http://%s:%d/",host,port));
baseUri = new URI(String.format("http://%s:%d/", host, port));
}
@AfterAll
@ -104,9 +101,9 @@ public class JstlTest
@Test
public void testUrlsBasic() throws IOException
{
HttpURLConnection http = (HttpURLConnection) baseUri.resolve("/urls.jsp").toURL().openConnection();
HttpURLConnection http = (HttpURLConnection)baseUri.resolve("/urls.jsp").toURL().openConnection();
assertThat("http response", http.getResponseCode(), is(200));
try(InputStream input = http.getInputStream())
try (InputStream input = http.getInputStream())
{
String resp = IO.toString(input, StandardCharsets.UTF_8);
assertThat("Response should be JSP processed", resp, not(containsString("<c:url")));
@ -118,9 +115,9 @@ public class JstlTest
@Test
public void testCatchBasic() throws IOException
{
HttpURLConnection http = (HttpURLConnection) baseUri.resolve("/catch-basic.jsp").toURL().openConnection();
HttpURLConnection http = (HttpURLConnection)baseUri.resolve("/catch-basic.jsp").toURL().openConnection();
assertThat("http response", http.getResponseCode(), is(200));
try(InputStream input = http.getInputStream())
try (InputStream input = http.getInputStream())
{
String resp = IO.toString(input, StandardCharsets.UTF_8);
assertThat("Response should be JSP processed", resp, not(containsString("<c:catch")));
@ -132,9 +129,9 @@ public class JstlTest
@Test
public void testCatchTaglib() throws IOException
{
HttpURLConnection http = (HttpURLConnection) baseUri.resolve("/catch-taglib.jsp").toURL().openConnection();
HttpURLConnection http = (HttpURLConnection)baseUri.resolve("/catch-taglib.jsp").toURL().openConnection();
assertThat("http response", http.getResponseCode(), is(200));
try(InputStream input = http.getInputStream())
try (InputStream input = http.getInputStream())
{
String resp = IO.toString(input, StandardCharsets.UTF_8);
assertThat("Response should be JSP processed", resp, not(containsString("<c:catch>")));

View File

@ -1,4 +1,5 @@
<code_scheme name="Jetty" version="173">
<code_scheme name="Jetty-StyleChecked" version="173">
<option name="AUTODETECT_INDENTS" value="false" />
<option name="LINE_SEPARATOR" value="&#xA;" />
<option name="RIGHT_MARGIN" value="128" />
<AndroidXmlCodeStyleSettings>
@ -8,6 +9,7 @@
<option name="HTML_ATTRIBUTE_WRAP" value="0" />
</HTMLCodeStyleSettings>
<JavaCodeStyleSettings>
<option name="FIELD_NAME_PREFIX" value="_" />
<option name="USE_EXTERNAL_ANNOTATIONS" value="true" />
<option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />
<option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />
@ -36,6 +38,13 @@
<option name="RIGHT_MARGIN" value="72" />
</MarkdownNavigatorCodeStyleSettings>
<XML>
<option name="XML_ATTRIBUTE_WRAP" value="0" />
<option name="XML_TEXT_WRAP" value="0" />
<option name="XML_KEEP_LINE_BREAKS" value="false" />
<option name="XML_KEEP_LINE_BREAKS_IN_TEXT" value="false" />
<option name="XML_KEEP_BLANK_LINES" value="1" />
<option name="XML_ALIGN_ATTRIBUTES" value="false" />
<option name="XML_SPACE_INSIDE_EMPTY_TAG" value="true" />
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
</XML>
<codeStyleSettings language="Groovy">
@ -61,7 +70,6 @@
<option name="ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION" value="true" />
<option name="SPACE_AFTER_TYPE_CAST" value="false" />
<option name="RESOURCE_LIST_WRAP" value="2" />
<option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
<option name="KEEP_SIMPLE_LAMBDAS_IN_ONE_LINE" value="true" />
<option name="KEEP_SIMPLE_CLASSES_IN_ONE_LINE" value="true" />
<option name="ARRAY_INITIALIZER_WRAP" value="1" />
@ -72,7 +80,6 @@
<option name="FOR_BRACE_FORCE" value="3" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
<option name="USE_RELATIVE_INDENTS" value="true" />
</indentOptions>
<arrangement>
<rules>
@ -362,6 +369,7 @@
</arrangement>
</codeStyleSettings>
<codeStyleSettings language="XML">
<option name="RIGHT_MARGIN" value="256" />
<option name="FORCE_REARRANGE_MODE" value="1" />
<indentOptions>
<option name="INDENT_SIZE" value="2" />

View File

@ -2,7 +2,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.eclipse.jetty</groupId>
<artifactId>build-resources</artifactId>
<version>9.4.19-SNAPSHOT</version>
<version>10.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Jetty :: Build Resources</name>

View File

@ -1,5 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>example-async-rest</artifactId>

View File

@ -42,18 +42,18 @@ import javax.servlet.http.HttpServletResponse;
*/
public class AbstractRestServlet extends HttpServlet
{
protected final static String __DEFAULT_APPID = "Webtide81-adf4-4f0a-ad58-d91e41bbe85";
protected final static String STYLE =
"<style type='text/css'>"+
" img.thumb:hover {height:50px}"+
" img.thumb {vertical-align:text-top}"+
" span.red {color: #ff0000}"+
" span.green {color: #00ff00}"+
" iframe {border: 0px}"+
protected static final String __DEFAULT_APPID = "Webtide81-adf4-4f0a-ad58-d91e41bbe85";
protected static final String STYLE =
"<style type='text/css'>" +
" img.thumb:hover {height:50px}" +
" img.thumb {vertical-align:text-top}" +
" span.red {color: #ff0000}" +
" span.green {color: #00ff00}" +
" iframe {border: 0px}" +
"</style>";
protected final static String ITEMS_PARAM = "items";
protected final static String APPID_PARAM = "appid";
protected static final String ITEMS_PARAM = "items";
protected static final String APPID_PARAM = "appid";
protected String _appid;
@ -93,15 +93,15 @@ public class AbstractRestServlet extends HttpServlet
{
return ("http://open.api.ebay.com/shopping?MaxEntries=3&appid=" + _appid +
"&version=573&siteid=0&callname=FindItems&responseencoding=JSON&QueryKeywords=" +
URLEncoder.encode(item,"UTF-8"));
URLEncoder.encode(item, "UTF-8"));
}
catch(Exception e)
catch (Exception e)
{
throw new RuntimeException(e);
}
}
protected String generateThumbs(Queue<Map<String,String>> results)
protected String generateThumbs(Queue<Map<String, String>> results)
{
StringBuilder thumbs = new StringBuilder();
for (Map<String, String> m : results)
@ -109,10 +109,10 @@ public class AbstractRestServlet extends HttpServlet
if (!m.containsKey("GalleryURL"))
continue;
thumbs.append("<a href=\""+m.get("ViewItemURLForNaturalSearch")+"\">");
thumbs.append("<img class='thumb' border='1px' height='25px'"+
" src='"+m.get("GalleryURL")+"'"+
" title='"+m.get("Title")+"'"+
thumbs.append("<a href=\"" + m.get("ViewItemURLForNaturalSearch") + "\">");
thumbs.append("<img class='thumb' border='1px' height='25px'" +
" src='" + m.get("GalleryURL") + "'" +
" title='" + m.get("Title") + "'" +
"/>");
thumbs.append("</a>&nbsp;");
}
@ -122,14 +122,14 @@ public class AbstractRestServlet extends HttpServlet
protected String ms(long nano)
{
BigDecimal dec = new BigDecimal(nano);
return dec.divide(new BigDecimal(1000000L)).setScale(1,RoundingMode.UP).toString();
return dec.divide(new BigDecimal(1000000L)).setScale(1, RoundingMode.UP).toString();
}
protected int width(long nano)
{
int w=(int)((nano+999999L)/5000000L);
if (w==0)
w=2;
int w = (int)((nano + 999999L) / 5000000L);
if (w == 0)
w = 2;
return w;
}
@ -138,5 +138,4 @@ public class AbstractRestServlet extends HttpServlet
{
doGet(request, response);
}
}

View File

@ -25,7 +25,6 @@ import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.AsyncContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
@ -52,9 +51,9 @@ import org.eclipse.jetty.util.ajax.JSON;
*/
public class AsyncRestServlet extends AbstractRestServlet
{
final static String RESULTS_ATTR = "org.eclipse.jetty.demo.client";
final static String DURATION_ATTR = "org.eclipse.jetty.demo.duration";
final static String START_ATTR = "org.eclispe.jetty.demo.start";
static final String RESULTS_ATTR = "org.eclipse.jetty.demo.client";
static final String DURATION_ATTR = "org.eclipse.jetty.demo.duration";
static final String START_ATTR = "org.eclispe.jetty.demo.start";
HttpClient _client;
@ -78,17 +77,17 @@ public class AsyncRestServlet extends AbstractRestServlet
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Long start=System.nanoTime();
Long start = System.nanoTime();
// Do we have results yet?
Queue<Map<String, String>> results = (Queue<Map<String, String>>) request.getAttribute(RESULTS_ATTR);
Queue<Map<String, String>> results = (Queue<Map<String, String>>)request.getAttribute(RESULTS_ATTR);
// If no results, this must be the first dispatch, so send the REST request(s)
if (results==null)
if (results == null)
{
// define results data structures
final Queue<Map<String, String>> resultsQueue = new ConcurrentLinkedQueue<>();
request.setAttribute(RESULTS_ATTR, results=resultsQueue);
request.setAttribute(RESULTS_ATTR, results = resultsQueue);
// suspend the request
// This is done before scheduling async handling to avoid race of
@ -97,24 +96,25 @@ public class AsyncRestServlet extends AbstractRestServlet
async.setTimeout(30000);
// extract keywords to search for
String[] keywords=sanitize(request.getParameter(ITEMS_PARAM)).split(",");
final AtomicInteger outstanding=new AtomicInteger(keywords.length);
String[] keywords = sanitize(request.getParameter(ITEMS_PARAM)).split(",");
final AtomicInteger outstanding = new AtomicInteger(keywords.length);
// Send request each keyword
for (final String item:keywords)
for (final String item : keywords)
{
_client.newRequest(restURL(item)).method(HttpMethod.GET).send(
new AsyncRestRequest()
{
@Override
void onAuctionFound(Map<String,String> auction)
void onAuctionFound(Map<String, String> auction)
{
resultsQueue.add(auction);
}
@Override
void onComplete()
{
if (outstanding.decrementAndGet()<=0)
if (outstanding.decrementAndGet() <= 0)
async.dispatch();
}
});
@ -138,23 +138,23 @@ public class AsyncRestServlet extends AbstractRestServlet
out.println(STYLE);
out.println("</head><body><small>");
long initial = (Long) request.getAttribute(DURATION_ATTR);
long start0 = (Long) request.getAttribute(START_ATTR);
long initial = (Long)request.getAttribute(DURATION_ATTR);
long start0 = (Long)request.getAttribute(START_ATTR);
long now = System.nanoTime();
long total=now-start0;
long generate=now-start;
long thread=initial+generate;
long total = now - start0;
long generate = now - start;
long thread = initial + generate;
out.print("<b>Asynchronous: "+sanitize(request.getParameter(ITEMS_PARAM))+"</b><br/>");
out.print("Total Time: "+ms(total)+"ms<br/>");
out.print("<b>Asynchronous: " + sanitize(request.getParameter(ITEMS_PARAM)) + "</b><br/>");
out.print("Total Time: " + ms(total) + "ms<br/>");
out.print("Thread held (<span class='red'>red</span>): "+ms(thread)+"ms (" + ms(initial) + " initial + " + ms(generate) + " generate )<br/>");
out.print("Async wait (<span class='green'>green</span>): "+ms(total-thread)+"ms<br/>");
out.print("Thread held (<span class='red'>red</span>): " + ms(thread) + "ms (" + ms(initial) + " initial + " + ms(generate) + " generate )<br/>");
out.print("Async wait (<span class='green'>green</span>): " + ms(total - thread) + "ms<br/>");
out.println("<img border='0px' src='asyncrest/red.png' height='20px' width='"+width(initial)+"px'>"+
"<img border='0px' src='asyncrest/green.png' height='20px' width='"+width(total-thread)+"px'>"+
"<img border='0px' src='asyncrest/red.png' height='20px' width='"+width(generate)+"px'>");
out.println("<img border='0px' src='asyncrest/red.png' height='20px' width='" + width(initial) + "px'>" +
"<img border='0px' src='asyncrest/green.png' height='20px' width='" + width(total - thread) + "px'>" +
"<img border='0px' src='asyncrest/red.png' height='20px' width='" + width(generate) + "px'>");
out.println("<hr />");
out.println(thumbs);
@ -175,27 +175,28 @@ public class AsyncRestServlet extends AbstractRestServlet
public void onContent(Response response, ByteBuffer content)
{
byte[] bytes = BufferUtil.toArray(content);
_content.append(bytes,0,bytes.length);
_content.append(bytes, 0, bytes.length);
}
@Override
public void onComplete(Result result)
{
// extract auctions from the results
Map<String,?> query = (Map<String,?>) JSON.parse(_content.toString());
Object[] auctions = (Object[]) query.get("Item");
Map<String, ?> query = (Map<String, ?>)JSON.parse(_content.toString());
Object[] auctions = (Object[])query.get("Item");
if (auctions != null)
{
for (Object o : auctions)
onAuctionFound((Map<String,String>)o);
{
onAuctionFound((Map<String, String>)o);
}
}
onComplete();
}
abstract void onAuctionFound(Map<String,String> details);
abstract void onComplete();
abstract void onAuctionFound(Map<String, String> details);
abstract void onComplete();
}
@Override

View File

@ -27,7 +27,6 @@ import java.net.URL;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -45,9 +44,8 @@ public class SerialRestServlet extends AbstractRestServlet
{
long start = System.nanoTime();
String[] keywords=sanitize(request.getParameter(ITEMS_PARAM)).split(",");
Queue<Map<String,String>> results = new LinkedList<Map<String,String>>();
String[] keywords = sanitize(request.getParameter(ITEMS_PARAM)).split(",");
Queue<Map<String, String>> results = new LinkedList<Map<String, String>>();
// make all requests serially
for (String itemName : keywords)
@ -58,17 +56,18 @@ public class SerialRestServlet extends AbstractRestServlet
connection.setRequestMethod("GET");
Map query = (Map)JSON.parse(new BufferedReader(new InputStreamReader(connection.getInputStream())));
Object[] auctions = (Object[]) query.get("Item");
Object[] auctions = (Object[])query.get("Item");
if (auctions != null)
{
for (Object o : auctions)
results.add((Map) o);
{
results.add((Map)o);
}
}
}
// Generate the response
String thumbs=generateThumbs(results);
String thumbs = generateThumbs(results);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
@ -77,22 +76,19 @@ public class SerialRestServlet extends AbstractRestServlet
out.println("</head><body><small>");
long now = System.nanoTime();
long total=now-start;
long total = now - start;
out.print("<b>Blocking: "+sanitize(request.getParameter(ITEMS_PARAM))+"</b><br/>");
out.print("Total Time: "+ms(total)+"ms<br/>");
out.print("Thread held (<span class='red'>red</span>): "+ms(total)+"ms<br/>");
out.print("<b>Blocking: " + sanitize(request.getParameter(ITEMS_PARAM)) + "</b><br/>");
out.print("Total Time: " + ms(total) + "ms<br/>");
out.print("Thread held (<span class='red'>red</span>): " + ms(total) + "ms<br/>");
out.println("<img border='0px' src='asyncrest/red.png' height='20px' width='"+width(total)+"px'>");
out.println("<img border='0px' src='asyncrest/red.png' height='20px' width='" + width(total) + "px'>");
out.println("<hr />");
out.println(thumbs);
out.println("</small>");
out.println("</body></html>");
out.close();
}
/**
@ -104,5 +100,4 @@ public class SerialRestServlet extends AbstractRestServlet
{
doGet(request, response);
}
}

View File

@ -1,5 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>example-async-rest</artifactId>

View File

@ -18,15 +18,13 @@
package org.eclipse.jetty.example.asyncrest;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.ClassMatcher;
import org.eclipse.jetty.webapp.WebAppContext;
import javax.servlet.http.HttpServlet;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class AsyncRestServer
{
public static void main(String[] args)
@ -34,7 +32,7 @@ public class AsyncRestServer
{
// Find the async-reset webapp based on common IDE working directories
// TODO import webapp as maven artifact
Path home = FileSystems.getDefault().getPath(System.getProperty("jetty.home",".")).toAbsolutePath();
Path home = FileSystems.getDefault().getPath(System.getProperty("jetty.home", ".")).toAbsolutePath();
Path war = home.resolve("../async-rest-webapp/target/async-rest/");
if (!Files.exists(war))
war = home.resolve("examples/async-rest/async-rest-webapp/target/async-rest/");
@ -42,7 +40,7 @@ public class AsyncRestServer
throw new IllegalArgumentException("Cannot find async-rest webapp");
// Build a demo server
Server server = new Server(Integer.getInteger("jetty.http.port",8080).intValue());
Server server = new Server(Integer.getInteger("jetty.http.port", 8080).intValue());
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar(war.toAbsolutePath().toString());

View File

@ -1,5 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>example-async-rest</artifactId>

View File

@ -1,5 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty.examples</groupId>
<artifactId>examples-parent</artifactId>

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.embedded;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
@ -31,7 +30,6 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AsyncEchoServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
@ -100,13 +98,13 @@ public class AsyncEchoServlet extends HttpServlet
break;
int read = input.read(buffer);
if (read<0)
if (read < 0)
{
if (complete.compareAndSet(false,true))
if (complete.compareAndSet(false, true))
asyncContext.complete();
break;
}
else if (read>0)
else if (read > 0)
{
output.write(buffer, 0, read);
}
@ -116,7 +114,7 @@ public class AsyncEchoServlet extends HttpServlet
@Override
public void onError(Throwable failure)
{
new Throwable("onError",failure).printStackTrace();
new Throwable("onError", failure).printStackTrace();
asyncContext.complete();
}
}

View File

@ -20,8 +20,6 @@ package org.eclipse.jetty.embedded;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -30,9 +28,8 @@ import javax.servlet.http.HttpServletResponse;
public class DumpServlet extends HttpServlet
{
@Override
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
IOException
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
@ -51,8 +48,7 @@ public class DumpServlet extends HttpServlet
String r = request.getParameter("resource");
if (r != null)
{
out.println("resource(" + r + ")="
+ getServletContext().getResource(r));
out.println("resource(" + r + ")=" + getServletContext().getResource(r));
}
out.println("</pre>");

View File

@ -28,13 +28,13 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
public class ExampleServer
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
server.setConnectors(new Connector[] { connector });
server.setConnectors(new Connector[]{connector});
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
@ -42,7 +42,7 @@ public class ExampleServer
context.addServlet(AsyncEchoServlet.class, "/echo/*");
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
handlers.setHandlers(new Handler[]{context, new DefaultHandler()});
server.setHandler(handlers);
server.start();

View File

@ -29,7 +29,7 @@ import org.eclipse.jetty.xml.XmlConfiguration;
*/
public class ExampleServerXml
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// Find Jetty XML (in classpath) that configures and starts Server.
Resource serverXml = Resource.newSystemResource("exampleserver.xml");

View File

@ -58,14 +58,15 @@ import org.eclipse.jetty.util.resource.Resource;
*/
public class FastFileServer
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] {
handlers.setHandlers(new Handler[]{
new FastFileHandler(new File(System.getProperty("user.dir"))),
new DefaultHandler() });
new DefaultHandler()
});
server.setHandler(handlers);
server.start();
@ -77,16 +78,16 @@ public class FastFileServer
private final MimeTypes mimeTypes = new MimeTypes();
private final File dir;
private FastFileHandler( File dir )
private FastFileHandler(File dir)
{
this.dir = dir;
}
@Override
public void handle( String target,
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
HttpServletResponse response) throws IOException,
ServletException
{
// define small medium and large.
@ -110,7 +111,7 @@ public class FastFileServer
{
if (!request.getPathInfo().endsWith(URIUtil.SLASH))
{
response.sendRedirect(response.encodeRedirectURL(request.getRequestURI()+URIUtil.SLASH));
response.sendRedirect(response.encodeRedirectURL(request.getRequestURI() + URIUtil.SLASH));
return;
}
String listing = Resource.newResource(file).getListHTML(
@ -134,7 +135,7 @@ public class FastFileServer
if (file.length() < SMALL)
{
// need to caste to Jetty output stream for best API
((HttpOutput) response.getOutputStream())
((HttpOutput)response.getOutputStream())
.sendContent(FileChannel.open(file.toPath(),
StandardOpenOption.READ));
return;
@ -153,7 +154,7 @@ public class FastFileServer
}
@Override
public void failed( Throwable x )
public void failed(Throwable x)
{
// log error and complete async response;
x.printStackTrace();
@ -165,7 +166,7 @@ public class FastFileServer
if (file.length() < MEDIUM)
{
// the file channel is closed by the async send
((HttpOutput) response.getOutputStream())
((HttpOutput)response.getOutputStream())
.sendContent(FileChannel.open(file.toPath(),
StandardOpenOption.READ), completionCB);
return;
@ -176,7 +177,7 @@ public class FastFileServer
// can be hard to GC on some JVMs. But for this example we will
// create a new buffer per file
ByteBuffer buffer;
try ( RandomAccessFile raf = new RandomAccessFile(file, "r"); )
try (RandomAccessFile raf = new RandomAccessFile(file, "r");)
{
buffer = raf.getChannel().map(MapMode.READ_ONLY, 0,
raf.length());
@ -188,7 +189,7 @@ public class FastFileServer
// send the content as a buffer with a callback to complete the
// async request need to caste to Jetty output stream for best API
((HttpOutput) response.getOutputStream()).sendContent(buffer,
((HttpOutput)response.getOutputStream()).sendContent(buffer,
completionCB);
}
}

View File

@ -39,17 +39,17 @@ public class FileServer
// Create the ResourceHandler. It is the object that will actually handle the request for a given file. It is
// a Jetty Handler object so it is suitable for chaining with other handlers as you will see in other examples.
ResourceHandler resource_handler = new ResourceHandler();
ResourceHandler resourceHandler = new ResourceHandler();
// Configure the ResourceHandler. Setting the resource base indicates where the files should be served out of.
// In this example it is the current directory but it can be configured to anything that the jvm has access to.
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[]{ "index.html" });
resource_handler.setResourceBase(".");
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resourceHandler.setResourceBase(".");
// Add the ResourceHandler to the server.
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
handlers.setHandlers(new Handler[]{resourceHandler, new DefaultHandler()});
server.setHandler(handlers);
// Start things up! By using the server.join() the server thread will join with the current thread.

View File

@ -34,11 +34,11 @@ import org.eclipse.jetty.xml.XmlConfiguration;
*/
public class FileServerXml
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Resource fileServerXml = Resource.newSystemResource("fileserver.xml");
XmlConfiguration configuration = new XmlConfiguration(fileServerXml);
Server server = (Server) configuration.configure();
Server server = (Server)configuration.configure();
server.start();
server.join();
}

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.embedded;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -38,22 +37,22 @@ public class HelloHandler extends AbstractHandler
this("Hello World");
}
public HelloHandler( String greeting )
public HelloHandler(String greeting)
{
this(greeting, null);
}
public HelloHandler( String greeting, String body )
public HelloHandler(String greeting, String body)
{
this.greeting = greeting;
this.body = body;
}
@Override
public void handle( String target,
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
HttpServletResponse response) throws IOException,
ServletException
{
response.setContentType("text/html; charset=utf-8");

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.embedded;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -35,14 +34,14 @@ public class HelloServlet extends HttpServlet
this("Hello");
}
public HelloServlet( String greeting )
public HelloServlet(String greeting)
{
this.greeting = greeting;
}
@Override
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.embedded;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -30,16 +29,18 @@ import javax.servlet.http.HttpSession;
@SuppressWarnings("serial")
public class HelloSessionServlet extends HttpServlet
{
public HelloSessionServlet() {}
public HelloSessionServlet()
{
}
@Override
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader("Cache-Control","no-cache");
response.addHeader("Cache-Control", "no-cache");
HttpSession session = request.getSession();
String message;
@ -73,12 +74,10 @@ public class HelloSessionServlet extends HttpServlet
out.println("<h1>" + greeting + " from HelloSessionServlet</h1>");
out.println("<p>" + message + "</p>");
out.println("<pre>");
out.println("session.getId() = " +session.getId());
out.println("session.isNew() = " +session.isNew());
out.println("session.getId() = " + session.getId());
out.println("session.isNew() = " + session.isNew());
out.println("</pre>");
out.println("<p>" + link + "</p>");
}
}

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.embedded;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -31,10 +30,10 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
public class HelloWorld extends AbstractHandler
{
@Override
public void handle( String target,
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
HttpServletResponse response) throws IOException,
ServletException
{
// Declare response encoding and types
@ -50,7 +49,7 @@ public class HelloWorld extends AbstractHandler
baseRequest.setHandled(true);
}
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
server.setHandler(new HelloWorld());

View File

@ -16,7 +16,6 @@
// ========================================================================
//
package org.eclipse.jetty.embedded;
import java.io.File;
@ -27,7 +26,6 @@ import java.util.Date;
import java.util.EnumSet;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
@ -70,57 +68,57 @@ public class Http2Server
ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
ServletContextHandler context = new ServletContextHandler(server, "/",ServletContextHandler.SESSIONS);
ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
String docroot = "src/main/resources/docroot";
if (!new File(docroot).exists())
docroot = "examples/embedded/src/main/resources/docroot";
context.setResourceBase(docroot);
context.addFilter(PushCacheFilter.class,"/*",EnumSet.of(DispatcherType.REQUEST));
context.addFilter(PushCacheFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
// context.addFilter(PushSessionCacheFilter.class,"/*",EnumSet.of(DispatcherType.REQUEST));
context.addFilter(PushedTilesFilter.class,"/*",EnumSet.of(DispatcherType.REQUEST));
context.addFilter(PushedTilesFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
context.addServlet(new ServletHolder(servlet), "/test/*");
context.addServlet(DefaultServlet.class, "/").setInitParameter("maxCacheSize","81920");
context.addServlet(DefaultServlet.class, "/").setInitParameter("maxCacheSize", "81920");
server.setHandler(context);
// HTTP Configuration
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setSendXPoweredBy(true);
http_config.setSendServerVersion(true);
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(8443);
httpConfig.setSendXPoweredBy(true);
httpConfig.setSendServerVersion(true);
// HTTP Connector
ServerConnector http = new ServerConnector(server,new HttpConnectionFactory(http_config), new HTTP2CServerConnectionFactory(http_config));
ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig), new HTTP2CServerConnectionFactory(httpConfig));
http.setPort(8080);
server.addConnector(http);
// SSL Context Factory for HTTPS and HTTP/2
String jetty_distro = System.getProperty("jetty.distro","../../jetty-distribution/target/distribution");
if (!new File(jetty_distro).exists())
jetty_distro = "jetty-distribution/target/distribution";
String jettyDistro = System.getProperty("jetty.distro", "../../jetty-distribution/target/distribution");
if (!new File(jettyDistro).exists())
jettyDistro = "jetty-distribution/target/distribution";
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath(jetty_distro + "/demo-base/etc/keystore");
sslContextFactory.setKeyStorePath(jettyDistro + "/demo-base/etc/keystore");
sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);
// sslContextFactory.setProvider("Conscrypt");
// HTTPS Configuration
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
// HTTP/2 Connection Factory
HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(https_config);
HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpsConfig);
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
alpn.setDefaultProtocol(http.getDefaultProtocol());
// SSL Connection Factory
SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory,alpn.getProtocol());
SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, alpn.getProtocol());
// HTTP/2 Connector
ServerConnector http2Connector =
new ServerConnector(server,ssl,alpn,h2,new HttpConnectionFactory(https_config));
new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(httpsConfig));
http2Connector.setPort(8443);
server.addConnector(http2Connector);
@ -140,14 +138,14 @@ public class Http2Server
{
Request baseRequest = Request.getBaseRequest(request);
if (baseRequest.isPush() && baseRequest.getRequestURI().contains("tiles") )
if (baseRequest.isPush() && baseRequest.getRequestURI().contains("tiles"))
{
String uri = baseRequest.getRequestURI().replace("tiles","pushed").substring(baseRequest.getContextPath().length());
request.getRequestDispatcher(uri).forward(request,response);
String uri = baseRequest.getRequestURI().replace("tiles", "pushed").substring(baseRequest.getContextPath().length());
request.getRequestDispatcher(uri).forward(request, response);
return;
}
chain.doFilter(request,response);
chain.doFilter(request, response);
}
@Override
@ -163,20 +161,20 @@ public class Http2Server
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException
{
String code=request.getParameter("code");
if (code!=null)
String code = request.getParameter("code");
if (code != null)
response.setStatus(Integer.parseInt(code));
HttpSession session = request.getSession(true);
if (session.isNew())
response.addCookie(new Cookie("bigcookie",
"This is a test cookies that was created on "+new Date()+" and is used by the jetty http/2 test servlet."));
response.setHeader("Custom","Value");
"This is a test cookies that was created on " + new Date() + " and is used by the jetty http/2 test servlet."));
response.setHeader("Custom", "Value");
response.setContentType("text/plain");
String content = "Hello from Jetty using "+request.getProtocol() +"\n";
content+="uri="+request.getRequestURI()+"\n";
content+="session="+session.getId()+(session.isNew()?"(New)\n":"\n");
content+="date="+new Date()+"\n";
String content = "Hello from Jetty using " + request.getProtocol() + "\n";
content += "uri=" + request.getRequestURI() + "\n";
content += "session=" + session.getId() + (session.isNew() ? "(New)\n" : "\n");
content += "date=" + new Date() + "\n";
content += Optional.ofNullable(request.getCookies())
.stream()

View File

@ -28,6 +28,7 @@ import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.Resource;
/**
*
*/
public class JarServer
{
@ -42,7 +43,7 @@ public class JarServer
context.addServlet(new ServletHolder(new DefaultServlet()), "/");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
handlers.setHandlers(new Handler[]{context, new DefaultHandler()});
server.setHandler(handlers);
server.start();

View File

@ -35,27 +35,27 @@ import org.eclipse.jetty.util.log.Logger;
*/
public class JettyDistribution
{
private final static Logger LOG = Log.getLogger(JettyDistribution.class);
public final static Path DISTRIBUTION;
private static final Logger LOG = Log.getLogger(JettyDistribution.class);
public static final Path DISTRIBUTION;
static
{
Path distro = asJettyDistribution(System.getProperty("jetty.home"));
if (distro==null)
if (distro == null)
distro = asJettyDistribution(System.getenv().get("JETTY_HOME"));
if (distro==null)
if (distro == null)
{
try
{
Path working = new File(".").getAbsoluteFile().getCanonicalFile().toPath();
while(distro == null && working !=null )
while (distro == null && working != null)
{
distro = asJettyDistribution(working.resolve("jetty-distribution/target/distribution").toString());
working = working.getParent();
}
}
catch(Throwable th)
catch (Throwable th)
{
LOG.warn(th);
}
@ -80,7 +80,7 @@ public class JettyDistribution
return null;
}
File demoBase = new File(dir,"demo-base");
File demoBase = new File(dir, "demo-base");
if (!demoBase.exists() || !demoBase.isDirectory())
{
LOG.info("asJettyDistribution {} has no demo-base", test);
@ -90,7 +90,7 @@ public class JettyDistribution
LOG.info("asJettyDistribution {}", dir);
return dir.getAbsoluteFile().getCanonicalFile().toPath();
}
catch(Exception e)
catch (Exception e)
{
LOG.ignore(e);
}

View File

@ -59,7 +59,7 @@ import org.eclipse.jetty.webapp.Configurations;
*/
public class LikeJettyXml
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// Path to as-built jetty-distribution directory
String jettyHomeBuild = JettyDistribution.DISTRIBUTION.toString();
@ -72,10 +72,10 @@ public class LikeJettyXml
File baseDir = new File(basePath);
// Configure jetty.home and jetty.base system properties
String jetty_home = homeDir.getAbsolutePath();
String jetty_base = baseDir.getAbsolutePath();
System.setProperty("jetty.home", jetty_home);
System.setProperty("jetty.base", jetty_base);
String jettyHome = homeDir.getAbsolutePath();
String jettyBase = baseDir.getAbsolutePath();
System.setProperty("jetty.home", jettyHome);
System.setProperty("jetty.base", jettyBase);
// === jetty.xml ===
// Setup Threadpool
@ -86,23 +86,23 @@ public class LikeJettyXml
Server server = new Server(threadPool);
// Scheduler
server.addBean(new ScheduledExecutorScheduler(null,false));
server.addBean(new ScheduledExecutorScheduler(null, false));
// HTTP Configuration
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setOutputBufferSize(32768);
http_config.setRequestHeaderSize(8192);
http_config.setResponseHeaderSize(8192);
http_config.setSendServerVersion(true);
http_config.setSendDateHeader(false);
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(8443);
httpConfig.setOutputBufferSize(32768);
httpConfig.setRequestHeaderSize(8192);
httpConfig.setResponseHeaderSize(8192);
httpConfig.setSendServerVersion(true);
httpConfig.setSendDateHeader(false);
// httpConfig.addCustomizer(new ForwardedRequestCustomizer());
// Handler Structure
HandlerCollection handlers = new HandlerCollection();
ContextHandlerCollection contexts = new ContextHandlerCollection();
handlers.setHandlers(new Handler[] { contexts, new DefaultHandler() });
handlers.setHandlers(new Handler[]{contexts, new DefaultHandler()});
server.setHandler(handlers);
// Extra options
@ -115,22 +115,20 @@ public class LikeJettyXml
ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
// === jetty-http.xml ===
ServerConnector http = new ServerConnector(server,
new HttpConnectionFactory(http_config));
new HttpConnectionFactory(httpConfig));
http.setPort(8080);
http.setIdleTimeout(30000);
server.addConnector(http);
// === jetty-https.xml ===
// SSL Context Factory
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath(jetty_home + "/../../../jetty-server/src/test/config/etc/keystore");
sslContextFactory.setKeyStorePath(jettyHome + "/../../../jetty-server/src/test/config/etc/keystore");
sslContextFactory.setKeyStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setKeyManagerPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
sslContextFactory.setTrustStorePath(jetty_home + "/../../../jetty-server/src/test/config/etc/keystore");
sslContextFactory.setTrustStorePath(jettyHome + "/../../../jetty-server/src/test/config/etc/keystore");
sslContextFactory.setTrustStorePassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA",
"SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA",
@ -140,17 +138,16 @@ public class LikeJettyXml
"SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
// SSL HTTP Configuration
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
// SSL Connector
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(https_config));
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(8443);
server.addConnector(sslConnector);
// === jetty-deploy.xml ===
DeploymentManager deployer = new DeploymentManager();
//DebugListener debug = new DebugListener(System.out,true,true,true);
@ -161,14 +158,14 @@ public class LikeJettyXml
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/jetty-servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$");
WebAppProvider webapp_provider = new WebAppProvider();
webapp_provider.setMonitoredDirName(jetty_base + "/webapps");
webapp_provider.setDefaultsDescriptor(jetty_home + "/etc/webdefault.xml");
webapp_provider.setScanInterval(1);
webapp_provider.setExtractWars(true);
webapp_provider.setConfigurationManager(new PropertiesConfigurationManager());
WebAppProvider webAppProvider = new WebAppProvider();
webAppProvider.setMonitoredDirName(jettyBase + "/webapps");
webAppProvider.setDefaultsDescriptor(jettyHome + "/etc/webdefault.xml");
webAppProvider.setScanInterval(1);
webAppProvider.setExtractWars(true);
webAppProvider.setConfigurationManager(new PropertiesConfigurationManager());
deployer.addAppProvider(webapp_provider);
deployer.addAppProvider(webAppProvider);
server.addBean(deployer);
// === setup jetty plus ==
@ -188,16 +185,15 @@ public class LikeJettyXml
rewrite.addRule(new ValidUrlRule());
// === jetty-requestlog.xml ===
AsyncRequestLogWriter logWriter = new AsyncRequestLogWriter(jetty_home + "/logs/yyyy_mm_dd.request.log");
AsyncRequestLogWriter logWriter = new AsyncRequestLogWriter(jettyHome + "/logs/yyyy_mm_dd.request.log");
CustomRequestLog requestLog = new CustomRequestLog(logWriter, CustomRequestLog.EXTENDED_NCSA_FORMAT + " \"%C\"");
logWriter.setFilenameDateFormat("yyyy_MM_dd");
logWriter.setRetainDays(90);
logWriter.setTimeZone("GMT");
server.setRequestLog(requestLog);
// === jetty-lowresources.xml ===
LowResourceMonitor lowResourcesMonitor=new LowResourceMonitor(server);
LowResourceMonitor lowResourcesMonitor = new LowResourceMonitor(server);
lowResourcesMonitor.setPeriod(1000);
lowResourcesMonitor.setLowResourcesIdleTimeout(200);
lowResourcesMonitor.setMonitorThreads(true);
@ -205,11 +201,10 @@ public class LikeJettyXml
lowResourcesMonitor.setMaxLowResourcesTime(5000);
server.addBean(lowResourcesMonitor);
// === test-realm.xml ===
HashLoginService login = new HashLoginService();
login.setName("Test Realm");
login.setConfig(jetty_base + "/etc/realm.properties");
login.setConfig(jettyBase + "/etc/realm.properties");
login.setHotReload(false);
server.addBean(login);

View File

@ -36,7 +36,7 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
*/
public class ManyConnectors
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// Since this example shows off SSL configuration, we need a keystore
// with the appropriate key. These lookup of jetty.home is purely a hack
@ -65,10 +65,10 @@ public class ManyConnectors
// <code>http</code> of course, as the default for secured http is
// <code>https</code> but we show setting the scheme to show it can be
// done. The port for secured communication is also set here.
HttpConfiguration http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
http_config.setSecurePort(8443);
http_config.setOutputBufferSize(32768);
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSecureScheme("https");
httpConfig.setSecurePort(8443);
httpConfig.setOutputBufferSize(32768);
// HTTP connector
// The first server connector we create is the one for http, passing in
@ -76,7 +76,7 @@ public class ManyConnectors
// the output buffer size, etc. We also set the port (8080) and
// configure an idle timeout.
ServerConnector http = new ServerConnector(server,
new HttpConnectionFactory(http_config));
new HttpConnectionFactory(httpConfig));
http.setPort(8080);
http.setIdleTimeout(30000);
@ -105,19 +105,19 @@ public class ManyConnectors
// SecureRequestCustomizer which is how a new connector is able to
// resolve the https connection before handing control over to the Jetty
// Server.
HttpConfiguration https_config = new HttpConfiguration(http_config);
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
SecureRequestCustomizer src = new SecureRequestCustomizer();
src.setStsMaxAge(2000);
src.setStsIncludeSubDomains(true);
https_config.addCustomizer(src);
httpsConfig.addCustomizer(src);
// HTTPS connector
// We create a second ServerConnector, passing in the http configuration
// we just made along with the previously created ssl context factory.
// Next we set the port and a longer idle timeout.
ServerConnector https = new ServerConnector(server,
new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(https_config));
new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
new HttpConnectionFactory(httpsConfig));
https.setPort(8443);
https.setIdleTimeout(500000);
@ -128,7 +128,7 @@ public class ManyConnectors
// has something to pass requests off to.
// Set the connectors
server.setConnectors(new Connector[] { http, https });
server.setConnectors(new Connector[]{http, https});
// Set a handler
server.setHandler(new HelloHandler());

View File

@ -25,7 +25,7 @@ import org.eclipse.jetty.server.handler.ContextHandlerCollection;
public class ManyContexts
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
@ -40,12 +40,14 @@ public class ManyContexts
contextIT.setHandler(new HelloHandler("Bongiorno"));
ContextHandler contextV = new ContextHandler("/");
contextV.setVirtualHosts(new String[] { "127.0.0.2" });
contextV.setVirtualHosts(new String[]{"127.0.0.2"});
contextV.setHandler(new HelloHandler("Virtual Hello"));
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { context, contextFR, contextIT,
contextV });
contexts.setHandlers(new Handler[]{
context, contextFR, contextIT,
contextV
});
server.setHandler(contexts);

View File

@ -21,7 +21,6 @@ package org.eclipse.jetty.embedded;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -72,10 +71,10 @@ public class ManyHandlers
public static class ParamHandler extends AbstractHandler
{
@Override
public void handle( String target,
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
HttpServletResponse response) throws IOException,
ServletException
{
Map<String, String[]> params = request.getParameterMap();
@ -94,10 +93,10 @@ public class ManyHandlers
public static class WelcomeWrapHandler extends HandlerWrapper
{
@Override
public void handle( String target,
public void handle(String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response ) throws IOException,
HttpServletResponse response) throws IOException,
ServletException
{
request.setAttribute("welcome", "Hello");
@ -105,7 +104,7 @@ public class ManyHandlers
}
}
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
@ -126,8 +125,8 @@ public class ManyHandlers
// link them all together
wrapper.setHandler(hello);
list.setHandlers(new Handler[] { param, new GzipHandler() });
handlers.setHandlers(new Handler[] { list, dft });
list.setHandlers(new Handler[]{param, new GzipHandler()});
handlers.setHandlers(new Handler[]{list, dft});
server.setHandler(handlers);

View File

@ -29,7 +29,7 @@ import org.eclipse.jetty.servlet.ServletHolder;
public class ManyServletContexts
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.embedded;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -30,7 +29,7 @@ import org.eclipse.jetty.servlet.ServletHandler;
public class MinimalServlets
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// Create a basic jetty server object that will listen on port 8080.
// Note that if you set this to port 0 then a randomly available port
@ -66,8 +65,8 @@ public class MinimalServlets
public static class HelloServlet extends HttpServlet
{
@Override
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");

View File

@ -26,7 +26,7 @@ import org.eclipse.jetty.server.ServerConnector;
*/
public class OneConnector
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// The Server
Server server = new Server();

View File

@ -23,18 +23,18 @@ import org.eclipse.jetty.server.handler.ContextHandler;
public class OneContext
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server( 8080 );
Server server = new Server(8080);
// Add a single handler on context "/hello"
ContextHandler context = new ContextHandler();
context.setContextPath( "/hello" );
context.setHandler( new HelloHandler() );
context.setContextPath("/hello");
context.setHandler(new HelloHandler());
// Can be accessed using http://localhost:8080/hello
server.setHandler( context );
server.setHandler(context);
// Start the server
server.start();

View File

@ -22,7 +22,7 @@ import org.eclipse.jetty.server.Server;
public class OneHandler
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
server.setHandler(new HelloHandler());

View File

@ -18,11 +18,8 @@
package org.eclipse.jetty.embedded;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ListenerHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import java.io.IOException;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
@ -34,12 +31,15 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.EnumSet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ListenerHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class OneServletContext
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
@ -56,9 +56,9 @@ public class OneServletContext
context.addServlet(HelloServlet.class, "/hello/*");
context.addServlet(DefaultServlet.class, "/");
context.addFilter(TestFilter.class,"/*", EnumSet.of(DispatcherType.REQUEST));
context.addFilter(TestFilter.class,"/test", EnumSet.of(DispatcherType.REQUEST,DispatcherType.ASYNC));
context.addFilter(TestFilter.class,"*.test", EnumSet.of(DispatcherType.REQUEST,DispatcherType.INCLUDE,DispatcherType.FORWARD));
context.addFilter(TestFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
context.addFilter(TestFilter.class, "/test", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
context.addFilter(TestFilter.class, "*.test", EnumSet.of(DispatcherType.REQUEST, DispatcherType.INCLUDE, DispatcherType.FORWARD));
context.getServletHandler().addListener(new ListenerHolder(InitListener.class));
context.getServletHandler().addListener(new ListenerHolder(RequestListener.class));
@ -68,7 +68,6 @@ public class OneServletContext
server.join();
}
public static class TestFilter implements Filter
{
@Override
@ -103,7 +102,6 @@ public class OneServletContext
}
}
public static class RequestListener implements ServletRequestListener
{
@Override

View File

@ -28,7 +28,7 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
public class OneServletContextJmxStats
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
// Add JMX tracking to Server

View File

@ -25,7 +25,6 @@ import org.eclipse.jetty.server.session.SessionCache;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class OneServletContextWithSession
{
public static void main(String[] args) throws Exception

View File

@ -28,7 +28,7 @@ import org.eclipse.jetty.webapp.WebAppContext;
public class OneWebApp
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// Create a basic jetty server object that will listen on port 8080.
// Note that if you set this to port 0 then a randomly available port

View File

@ -29,19 +29,19 @@ import org.eclipse.jetty.webapp.WebAppContext;
public class OneWebAppWithJsp
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// Create a basic jetty server object that will listen on port 8080.
// Note that if you set this to port 0 then
// a randomly available port will be assigned that you can either look
// in the logs for the port,
// or programmatically obtain it for use in test cases.
Server server = new Server( 8080 );
Server server = new Server(8080);
// Setup JMX
MBeanContainer mbContainer = new MBeanContainer(
ManagementFactory.getPlatformMBeanServer() );
server.addBean( mbContainer );
ManagementFactory.getPlatformMBeanServer());
server.addBean(mbContainer);
// The WebAppContext is the entity that controls the environment in
// which a web application lives and
@ -53,18 +53,16 @@ public class OneWebAppWithJsp
// the webapp (through
// PlusConfiguration) to choosing where the webapp will unpack itself.
WebAppContext webapp = new WebAppContext();
webapp.setContextPath( "/" );
webapp.setContextPath("/");
File warFile = new File(
"jetty-distribution/target/distribution/demo-base/webapps/test.war" );
"jetty-distribution/target/distribution/demo-base/webapps/test.war");
if (!warFile.exists())
{
throw new RuntimeException( "Unable to find WAR File: "
+ warFile.getAbsolutePath() );
throw new RuntimeException("Unable to find WAR File: " + warFile.getAbsolutePath());
}
webapp.setWar( warFile.getAbsolutePath() );
webapp.setWar(warFile.getAbsolutePath());
webapp.setExtractWAR(true);
// This webapp will use jsps and jstl. We need to enable the
// AnnotationConfiguration in order to correctly
// set up the jsp container
@ -76,12 +74,12 @@ public class OneWebAppWithJsp
// scan for them instead.
webapp.setAttribute(
"org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
".*/jetty-servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
".*/jetty-servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$");
// A WebAppContext is a ContextHandler as well so it needs to be set to
// the server so it is aware of where to
// send the appropriate requests.
server.setHandler( webapp );
server.setHandler(webapp);
// Configure a LoginService.
// Since this example is for our test webapp, we need to setup a
@ -92,9 +90,9 @@ public class OneWebAppWithJsp
// can be started and stopped according to the lifecycle of the server
// itself.
HashLoginService loginService = new HashLoginService();
loginService.setName( "Test Realm" );
loginService.setConfig( "examples/embedded/src/test/resources/realm.properties" );
server.addBean( loginService );
loginService.setName("Test Realm");
loginService.setConfig("examples/embedded/src/test/resources/realm.properties");
server.addBean(loginService);
// Start things up!
server.start();

View File

@ -27,7 +27,7 @@ import org.eclipse.jetty.servlet.ServletHolder;
public class ProxyServer
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
@ -47,5 +47,4 @@ public class ProxyServer
server.start();
}
}

View File

@ -28,16 +28,16 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
public class RewriteServer
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
HttpConfiguration config=server.getConnectors()[0].getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
HttpConfiguration config = server.getConnectors()[0].getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
RewriteCustomizer rewrite = new RewriteCustomizer();
config.addCustomizer(rewrite);
rewrite.addRule(new CompactPathRule());
rewrite.addRule(new RewriteRegexRule("(.*)foo(.*)","$1FOO$2"));
rewrite.addRule(new RewriteRegexRule("(.*)foo(.*)", "$1FOO$2"));
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);

View File

@ -30,7 +30,7 @@ import org.eclipse.jetty.util.security.Constraint;
public class SecuredHelloHandler
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// Create a basic jetty server object that will listen on port 8080.
// Note that if you set this to port 0 then a randomly available port
@ -65,7 +65,7 @@ public class SecuredHelloHandler
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate(true);
constraint.setRoles(new String[] { "user", "admin" });
constraint.setRoles(new String[]{"user", "admin"});
// Binds a url pattern with the previously created constraint. The roles
// for this constraing mapping are mined from the Constraint itself

View File

@ -36,7 +36,7 @@ import org.eclipse.jetty.webapp.WebAppContext;
*/
public class ServerWithAnnotations
{
public static final void main( String args[] ) throws Exception
public static final void main(String[] args) throws Exception
{
// Create the server
Server server = new Server(8080);
@ -45,7 +45,7 @@ public class ServerWithAnnotations
WebAppContext webapp = new WebAppContext();
// Enable parsing of jndi-related parts of web.xml and jetty-env.xml
webapp.addConfiguration(new EnvConfiguration(),new PlusConfiguration(),new AnnotationConfiguration());
webapp.addConfiguration(new EnvConfiguration(), new PlusConfiguration(), new AnnotationConfiguration());
webapp.setContextPath("/");
File warFile = JettyDistribution.resolve("demo-base/webapps/test-spec.war").toFile();
@ -75,10 +75,8 @@ public class ServerWithAnnotations
loginService.setConfig("examples/embedded/src/test/resources/realm.properties");
server.addBean(loginService);
server.start();
server.dumpStdErr();
server.join();
}
}

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.embedded;
import java.lang.management.ManagementFactory;
import javax.management.remote.JMXServiceURL;
import org.eclipse.jetty.jmx.ConnectorServer;
@ -31,7 +30,7 @@ import org.eclipse.jetty.server.Server;
*/
public class ServerWithJMX
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// === jetty-jmx.xml ===
MBeanContainer mbContainer = new MBeanContainer(

View File

@ -31,7 +31,7 @@ import org.eclipse.jetty.webapp.WebAppContext;
*/
public class ServerWithJNDI
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// Create the server
@ -46,7 +46,7 @@ public class ServerWithJNDI
server.setHandler(webapp);
// Enable parsing of jndi-related parts of web.xml and jetty-env.xml
webapp.addConfiguration(new EnvConfiguration(),new PlusConfiguration());
webapp.addConfiguration(new EnvConfiguration(), new PlusConfiguration());
// Register new transaction manager in JNDI
// At runtime, the webapp accesses this as java:comp/UserTransaction

View File

@ -25,7 +25,7 @@ import org.eclipse.jetty.server.Server;
*/
public class SimplestServer
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
server.start();

View File

@ -37,7 +37,7 @@ import org.eclipse.jetty.util.resource.Resource;
*/
public class SplitFileServer
{
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
// Create the Server object and a corresponding ServerConnector and then
// set the port for the connector. In this example the server will
@ -47,7 +47,7 @@ public class SplitFileServer
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8090);
server.setConnectors(new Connector[] { connector });
server.setConnectors(new Connector[]{connector});
// Create a Context Handler and ResourceHandler. The ContextHandler is
// getting set to "/" path but this could be anything you like for
@ -77,7 +77,7 @@ public class SplitFileServer
// This will let jetty process urls against the declared contexts in
// order to match up content.
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { context0, context1 });
contexts.setHandlers(new Handler[]{context0, context1});
server.setHandler(contexts);

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.embedded;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;
import org.eclipse.jetty.server.Server;
@ -41,13 +40,13 @@ public class WebSocketJsrServer
public static class EchoJsrSocket
{
@OnMessage
public void onMessage( Session session, String message )
public void onMessage(Session session, String message)
{
session.getAsyncRemote().sendText(message);
}
}
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
@ -61,7 +60,7 @@ public class WebSocketJsrServer
server.setHandler(handlers);
// Enable javax.websocket configuration for the context
JavaxWebSocketServletContainerInitializer.configure(contextHandler, (context, container)->
JavaxWebSocketServletContainerInitializer.configure(contextHandler, (context, container) ->
container.addEndpoint(EchoJsrSocket.class));
server.start();

View File

@ -42,7 +42,7 @@ public class WebSocketServer
public static class EchoSocket
{
@OnWebSocketMessage
public void onMessage( Session session, String message )
public void onMessage(Session session, String message)
{
session.getRemote().sendString(message, WriteCallback.NOOP);
}
@ -57,11 +57,11 @@ public class WebSocketServer
@Override
public void configure(JettyWebSocketServletFactory factory)
{
factory.addMapping("/", (req,res)->new EchoSocket());
factory.addMapping("/", (req, res) -> new EchoSocket());
}
}
public static void main( String[] args ) throws Exception
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);

View File

@ -24,7 +24,7 @@ public class TestXml
{
public static void main(String[] args) throws Exception
{
System.setProperty("jetty.home","../jetty-distribution/target/distribution");
System.setProperty("jetty.home", "../jetty-distribution/target/distribution");
XmlConfiguration.main("../jetty-jmx/src/main/config/etc/jetty-jmx.xml",
"../jetty-server/src/main/config/etc/jetty.xml");
}

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-project</artifactId>

View File

@ -21,7 +21,6 @@ package org.eclipse.jetty.alpn.client;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import javax.net.ssl.SSLEngine;
import org.eclipse.jetty.io.ClientConnectionFactory;

View File

@ -24,7 +24,6 @@ import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.Executor;
import javax.net.ssl.SSLEngine;
import org.eclipse.jetty.io.ClientConnectionFactory;
@ -55,14 +54,14 @@ public class ALPNClientConnectionFactory extends NegotiatingClientConnectionFact
IllegalStateException failure = new IllegalStateException("No Client ALPNProcessors!");
// Use a for loop on iterator so load exceptions can be caught and ignored
for (Iterator<Client> i = ServiceLoader.load(Client.class).iterator(); i.hasNext();)
for (Iterator<Client> i = ServiceLoader.load(Client.class).iterator(); i.hasNext(); )
{
Client processor;
try
{
processor = i.next();
}
catch(Throwable x)
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug(x);

View File

@ -1,7 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-alpn-parent</artifactId>
@ -84,8 +83,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
@{argLine} ${jetty.surefire.argLine}
--add-reads org.eclipse.jetty.alpn.conscrypt.server=org.eclipse.jetty.server
@{argLine} ${jetty.surefire.argLine} --add-reads org.eclipse.jetty.alpn.conscrypt.server=org.eclipse.jetty.server
</argLine>
</configuration>
</plugin>

View File

@ -76,7 +76,6 @@ public class ConscryptServerALPNProcessor implements ALPNProcessor.Server
{
private final ALPNServerConnection alpnConnection;
private ALPNCallback(ALPNServerConnection connection)
{
alpnConnection = connection;

View File

@ -1,7 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.alpn.java.client;
import java.util.List;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
@ -39,15 +38,15 @@ public class JDK9ClientALPNProcessor implements ALPNProcessor.Client
@Override
public void init()
{
if (JavaVersion.VERSION.getPlatform()<9)
throw new IllegalStateException(this + " not applicable for java "+JavaVersion.VERSION);
if (JavaVersion.VERSION.getPlatform() < 9)
throw new IllegalStateException(this + " not applicable for java " + JavaVersion.VERSION);
}
@Override
public boolean appliesTo(SSLEngine sslEngine)
{
Module module = sslEngine.getClass().getModule();
return module!=null && "java.base".equals(module.getName());
return module != null && "java.base".equals(module.getName());
}
@Override

View File

@ -1,7 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-alpn-parent</artifactId>
@ -22,8 +20,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
@{argLine} ${jetty.surefire.argLine}
--add-reads org.eclipse.jetty.alpn.java.server=org.eclipse.jetty.server
@{argLine} ${jetty.surefire.argLine} --add-reads org.eclipse.jetty.alpn.java.server=org.eclipse.jetty.server
</argLine>
</configuration>
</plugin>

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.alpn.java.server;
import java.util.List;
import java.util.function.BiFunction;
import javax.net.ssl.SSLEngine;
import org.eclipse.jetty.alpn.server.ALPNServerConnection;
@ -39,15 +38,15 @@ public class JDK9ServerALPNProcessor implements ALPNProcessor.Server, SslHandsha
@Override
public void init()
{
if (JavaVersion.VERSION.getPlatform()<9)
throw new IllegalStateException(this + " not applicable for java "+JavaVersion.VERSION);
if (JavaVersion.VERSION.getPlatform() < 9)
throw new IllegalStateException(this + " not applicable for java " + JavaVersion.VERSION);
}
@Override
public boolean appliesTo(SSLEngine sslEngine)
{
Module module = sslEngine.getClass().getModule();
return module!=null && "java.base".equals(module.getName());
return module != null && "java.base".equals(module.getName());
}
@Override
@ -56,7 +55,7 @@ public class JDK9ServerALPNProcessor implements ALPNProcessor.Server, SslHandsha
sslEngine.setHandshakeApplicationProtocolSelector(new ALPNCallback((ALPNServerConnection)connection));
}
private final class ALPNCallback implements BiFunction<SSLEngine,List<String>,String>, SslHandshakeListener
private final class ALPNCallback implements BiFunction<SSLEngine, List<String>, String>, SslHandshakeListener
{
private final ALPNServerConnection alpnConnection;
@ -81,7 +80,7 @@ public class JDK9ServerALPNProcessor implements ALPNProcessor.Server, SslHandsha
String protocol = alpnConnection.getProtocol();
if (LOG.isDebugEnabled())
LOG.debug("TLS handshake succeeded, protocol={} for {}", protocol, alpnConnection);
if (protocol ==null)
if (protocol == null)
alpnConnection.unsupported();
}

View File

@ -23,7 +23,6 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
@ -105,7 +104,7 @@ public class JDK9ALPNTest
client.startHandshake();
OutputStream output = client.getOutputStream();
output.write(("" +
output.write((
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Connection: close\r\n" +
@ -150,7 +149,7 @@ public class JDK9ALPNTest
client.startHandshake();
OutputStream output = client.getOutputStream();
output.write(("" +
output.write((
"GET / HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"Connection: close\r\n" +

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.alpn.server;
import java.util.Collections;
import java.util.List;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;

View File

@ -23,7 +23,6 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;
import javax.net.ssl.SSLEngine;
import org.eclipse.jetty.io.AbstractConnection;
@ -52,14 +51,14 @@ public class ALPNServerConnectionFactory extends NegotiatingServerConnectionFact
IllegalStateException failure = new IllegalStateException("No Server ALPNProcessors!");
// Use a for loop on iterator so load exceptions can be caught and ignored
for (Iterator<Server> i = ServiceLoader.load(Server.class).iterator(); i.hasNext();)
for (Iterator<Server> i = ServiceLoader.load(Server.class).iterator(); i.hasNext(); )
{
Server processor;
try
{
processor = i.next();
}
catch(Throwable x)
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug(x);
@ -108,7 +107,7 @@ public class ALPNServerConnectionFactory extends NegotiatingServerConnectionFact
}
if (LOG.isDebugEnabled())
LOG.debug("No ALPNProcessor: {} {}",engine,endPoint);
LOG.debug("No ALPNProcessor: {} {}", engine, endPoint);
throw new IllegalStateException("Connection rejected: No ALPN Processor for " + engine.getClass().getName() + " from " + processors);
}
}

View File

@ -1,6 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-project</artifactId>

View File

@ -1,5 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-project</artifactId>
@ -21,8 +20,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
@{argLine} ${jetty.surefire.argLine}
--add-opens org.eclipse.jetty.annotations/org.eclipse.jetty.annotations.resources=org.eclipse.jetty.plus
@{argLine} ${jetty.surefire.argLine} --add-opens org.eclipse.jetty.annotations/org.eclipse.jetty.annotations.resources=org.eclipse.jetty.plus
</argLine>
</configuration>
</plugin>
@ -33,9 +31,7 @@
<configuration>
<instructions>
<Import-Package>org.objectweb.asm;version="5",*</Import-Package>
<Require-Capability>osgi.serviceloader;
filter:="(osgi.serviceloader=javax.servlet.ServletContainerInitializer)";resolution:=optional;cardinality:=multiple,
osgi.extender; filter:="(osgi.extender=osgi.serviceloader.processor)";resolution:=optional
<Require-Capability>osgi.serviceloader; filter:="(osgi.serviceloader=javax.servlet.ServletContainerInitializer)";resolution:=optional;cardinality:=multiple, osgi.extender; filter:="(osgi.extender=osgi.serviceloader.processor)";resolution:=optional
</Require-Capability>
</instructions>
</configuration>

View File

@ -26,22 +26,18 @@ import org.eclipse.jetty.webapp.WebAppContext;
* DiscoverableAnnotationHandler
*
* Base class for handling the discovery of an annotation.
*
*/
public abstract class AbstractDiscoverableAnnotationHandler extends AbstractHandler
{
protected WebAppContext _context;
public AbstractDiscoverableAnnotationHandler(WebAppContext context)
{
_context = context;
}
public void addAnnotation (DiscoveredAnnotation a)
public void addAnnotation(DiscoveredAnnotation a)
{
_context.getMetaData().addDiscoveredAnnotation(a);
}
}

View File

@ -79,7 +79,6 @@ public class AnnotationConfiguration extends AbstractConfiguration
public static final String MULTI_THREADED = "org.eclipse.jetty.annotations.multiThreaded";
public static final String MAX_SCAN_WAIT = "org.eclipse.jetty.annotations.maxWait";
public static final int DEFAULT_MAX_SCAN_WAIT = 60; /* time in sec */
public static final boolean DEFAULT_MULTI_THREADED = true;
@ -107,19 +106,18 @@ public class AnnotationConfiguration extends AbstractConfiguration
* TimeStatistic
*
* Simple class to capture elapsed time of an operation.
*
*/
public class TimeStatistic
{
public long _start = 0;
public long _end = 0;
public void start ()
public void start()
{
_start = System.nanoTime();
}
public void end ()
public void end()
{
_end = System.nanoTime();
}
@ -129,23 +127,21 @@ public class AnnotationConfiguration extends AbstractConfiguration
return _start;
}
public long getEnd ()
public long getEnd()
{
return _end;
}
public long getElapsed ()
public long getElapsed()
{
return (_end > _start?(_end-_start):0);
return (_end > _start ? (_end - _start) : 0);
}
}
/**
* ParserTask
*
* Task to executing scanning of a resource for annotations.
*
*/
public class ParserTask implements Callable<Void>
{
@ -155,7 +151,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
protected final Resource _resource;
protected TimeStatistic _stat;
public ParserTask (AnnotationParser parser, Set<? extends Handler>handlers, Resource resource)
public ParserTask(AnnotationParser parser, Set<? extends Handler> handlers, Resource resource)
{
_parser = parser;
_handlers = handlers;
@ -190,7 +186,6 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
}
/**
* ServletContainerInitializerOrdering
*
@ -205,7 +200,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
private Integer _star = null;
private String _ordering = null;
public ServletContainerInitializerOrdering (String ordering)
public ServletContainerInitializerOrdering(String ordering)
{
if (ordering != null)
{
@ -213,17 +208,16 @@ public class AnnotationConfiguration extends AbstractConfiguration
String[] tmp = StringUtil.csvSplit(ordering);
for (int i=0; i<tmp.length; i++)
for (int i = 0; i < tmp.length; i++)
{
String s = tmp[i].trim();
_indexMap.put(s, i);
if ("*".equals(s))
{
if (_star != null)
throw new IllegalArgumentException("Duplicate wildcards in ServletContainerInitializer ordering "+ordering);
throw new IllegalArgumentException("Duplicate wildcards in ServletContainerInitializer ordering " + ordering);
_star = i;
}
}
}
}
@ -249,17 +243,18 @@ public class AnnotationConfiguration extends AbstractConfiguration
/**
* @return true if the ordering contains a single value of "*"
*/
public boolean isDefaultOrder ()
public boolean isDefaultOrder()
{
return (getSize() == 1 && hasWildcard());
}
/**
* Get the order index of the given classname
*
* @param name the classname to look up
* @return the index of the class name (or -1 if not found)
*/
public int getIndexOf (String name)
public int getIndexOf(String name)
{
Integer i = _indexMap.get(name);
if (i == null)
@ -269,6 +264,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
/**
* Get the number of elements of the ordering
*
* @return the size of the index
*/
public int getSize()
@ -285,22 +281,20 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
}
/**
* ServletContainerInitializerComparator
*
* Comparator impl that orders a set of ServletContainerInitializers according to the
* list of classnames (optionally containing a "*" wildcard character) established in a
* ServletContainerInitializerOrdering.
*
* @see ServletContainerInitializerOrdering
*/
public class ServletContainerInitializerComparator implements Comparator<ServletContainerInitializer>
{
private ServletContainerInitializerOrdering _ordering;
public ServletContainerInitializerComparator (ServletContainerInitializerOrdering ordering)
public ServletContainerInitializerComparator(ServletContainerInitializerOrdering ordering)
{
_ordering = ordering;
}
@ -308,8 +302,8 @@ public class AnnotationConfiguration extends AbstractConfiguration
@Override
public int compare(ServletContainerInitializer sci1, ServletContainerInitializer sci2)
{
String c1 = (sci1 != null? sci1.getClass().getName() : null);
String c2 = (sci2 != null? sci2.getClass().getName() : null);
String c1 = (sci1 != null ? sci1.getClass().getName() : null);
String c2 = (sci2 != null ? sci2.getClass().getName() : null);
if (c1 == null && c2 == null)
return 0;
@ -329,7 +323,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
public void preConfigure(final WebAppContext context) throws Exception
{
String tmp = (String)context.getAttribute(SERVLET_CONTAINER_INITIALIZER_EXCLUSION_PATTERN);
_sciExcludePattern = (tmp==null?null:Pattern.compile(tmp));
_sciExcludePattern = (tmp == null ? null : Pattern.compile(tmp));
}
public void addDiscoverableAnnotationHandler(AbstractDiscoverableAnnotationHandler handler)
@ -366,14 +360,15 @@ public class AnnotationConfiguration extends AbstractConfiguration
// Resolve container initializers
List<ContainerInitializer> initializers =
(List<ContainerInitializer>)context.getAttribute(AnnotationConfiguration.CONTAINER_INITIALIZERS);
if (initializers != null && initializers.size()>0)
if (initializers != null && initializers.size() > 0)
{
Map<String, Set<String>> map = ( Map<String, Set<String>>) context.getAttribute(AnnotationConfiguration.CLASS_INHERITANCE_MAP);
Map<String, Set<String>> map = (Map<String, Set<String>>)context.getAttribute(AnnotationConfiguration.CLASS_INHERITANCE_MAP);
for (ContainerInitializer i : initializers)
i.resolveClasses(context,map);
{
i.resolveClasses(context, map);
}
}
}
/**
* @see org.eclipse.jetty.webapp.AbstractConfiguration#postConfigure(org.eclipse.jetty.webapp.WebAppContext)
@ -417,27 +412,24 @@ public class AnnotationConfiguration extends AbstractConfiguration
super.postConfigure(context);
}
/**
* Perform scanning of classes for annotations
*
* @param context the context for the scan
* @throws Exception if unable to scan
*/
protected void scanForAnnotations (WebAppContext context)
protected void scanForAnnotations(WebAppContext context)
throws Exception
{
int javaPlatform = 0;
Object target = context.getAttribute(JavaVersion.JAVA_TARGET_PLATFORM);
if (target!=null)
if (target != null)
javaPlatform = Integer.parseInt(target.toString());
AnnotationParser parser = createAnnotationParser(javaPlatform);
_parserTasks = new ArrayList<ParserTask>();
long start = 0;
if (LOG.isDebugEnabled())
LOG.debug("Annotation scanning commencing: webxml={}, metadatacomplete={}, configurationDiscovered={}, multiThreaded={}, maxScanWait={}",
context.getServletContext().getEffectiveMajorVersion(),
@ -446,7 +438,6 @@ public class AnnotationConfiguration extends AbstractConfiguration
isUseMultiThreading(context),
getMaxScanWait(context));
parseContainerPath(context, parser);
//email from Rajiv Mordani jsrs 315 7 April 2010
// If there is a <others/> then the ordering should be
@ -454,16 +445,16 @@ public class AnnotationConfiguration extends AbstractConfiguration
// In case there is no others then it is
// WEB-INF/classes + order of the elements.
parseWebInfClasses(context, parser);
parseWebInfLib (context, parser);
parseWebInfLib(context, parser);
start = System.nanoTime();
//execute scan, either effectively synchronously (1 thread only), or asynchronously (limited by number of processors available)
final Semaphore task_limit = (isUseMultiThreading(context)? new Semaphore(ProcessorUtils.availableProcessors()):new Semaphore( 1));
final Semaphore task_limit = (isUseMultiThreading(context) ? new Semaphore(ProcessorUtils.availableProcessors()) : new Semaphore(1));
final CountDownLatch latch = new CountDownLatch(_parserTasks.size());
final MultiException me = new MultiException();
for (final ParserTask p:_parserTasks)
for (final ParserTask p : _parserTasks)
{
task_limit.acquire();
context.getServer().getThreadPool().execute(new Runnable()
@ -489,19 +480,21 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
boolean timeout = !latch.await(getMaxScanWait(context), TimeUnit.SECONDS);
long elapsedMs = TimeUnit.MILLISECONDS.convert(System.nanoTime()-start, TimeUnit.NANOSECONDS);
long elapsedMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
LOG.info("Scanning elapsed time={}ms",elapsedMs);
LOG.info("Scanning elapsed time={}ms", elapsedMs);
if (LOG.isDebugEnabled())
{
for (ParserTask p:_parserTasks)
for (ParserTask p : _parserTasks)
{
LOG.debug("Scanned {} in {}ms", p.getResource(), TimeUnit.MILLISECONDS.convert(p.getStatistic().getElapsed(), TimeUnit.NANOSECONDS));
}
LOG.debug("Scanned {} container path jars, {} WEB-INF/lib jars, {} WEB-INF/classes dirs in {}ms for context {}",
(_containerPathStats==null?-1:_containerPathStats.getTotal()),
(_webInfLibStats==null?-1:_webInfLibStats.getTotal()),
(_webInfClassesStats==null?-1:_webInfClassesStats.getTotal()),
(_containerPathStats == null ? -1 : _containerPathStats.getTotal()),
(_webInfLibStats == null ? -1 : _webInfLibStats.getTotal()),
(_webInfClassesStats == null ? -1 : _webInfClassesStats.getTotal()),
elapsedMs,
context);
}
@ -511,8 +504,6 @@ public class AnnotationConfiguration extends AbstractConfiguration
me.ifExceptionThrow();
}
/**
* @param javaPlatform The java platform to scan for.
* @return a new AnnotationParser. This method can be overridden to use a different implementation of
@ -525,6 +516,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
/**
* Check if we should use multiple threads to scan for annotations or not
*
* @param context the context of the multi threaded setting
* @return true if multi threading is enabled on the context, server, or via a System property.
* @see #MULTI_THREADED
@ -547,8 +539,6 @@ public class AnnotationConfiguration extends AbstractConfiguration
return Boolean.parseBoolean(System.getProperty(MULTI_THREADED, Boolean.toString(DEFAULT_MULTI_THREADED)));
}
/**
* Work out how long we should wait for the async scanning to occur.
*
@ -556,7 +546,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
* @return the max scan wait setting on the context, or server, or via a System property.
* @see #MAX_SCAN_WAIT
*/
protected int getMaxScanWait (WebAppContext context)
protected int getMaxScanWait(WebAppContext context)
{
//try context attribute to get max time in sec to wait for scan completion
Object o = context.getAttribute(MAX_SCAN_WAIT);
@ -583,7 +573,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
context.getObjectFactory().addDecorator(new AnnotationDecorator(context));
}
public void createServletContainerInitializerAnnotationHandlers (WebAppContext context, List<ServletContainerInitializer> scis)
public void createServletContainerInitializerAnnotationHandlers(WebAppContext context, List<ServletContainerInitializer> scis)
throws Exception
{
if (scis == null || scis.isEmpty())
@ -603,7 +593,10 @@ public class AnnotationConfiguration extends AbstractConfiguration
if (classes != null)
{
if (LOG.isDebugEnabled()){LOG.debug("HandlesTypes {} on initializer {}",Arrays.asList(classes),service.getClass());}
if (LOG.isDebugEnabled())
{
LOG.debug("HandlesTypes {} on initializer {}", Arrays.asList(classes), service.getClass());
}
initializer = new ContainerInitializer(service, classes);
@ -617,13 +610,14 @@ public class AnnotationConfiguration extends AbstractConfiguration
_classInheritanceHandler = new ClassInheritanceHandler(map);
}
for (Class<?> c: classes)
for (Class<?> c : classes)
{
//The value of one of the HandlesTypes classes is actually an Annotation itself so
//register a handler for it
if (c.isAnnotation())
{
if (LOG.isDebugEnabled()) LOG.debug("Registering annotation handler for "+c.getName());
if (LOG.isDebugEnabled())
LOG.debug("Registering annotation handler for " + c.getName());
_containerInitializerAnnotationHandlers.add(new ContainerInitializerAnnotationHandler(initializer, c));
}
}
@ -631,19 +625,20 @@ public class AnnotationConfiguration extends AbstractConfiguration
else
{
initializer = new ContainerInitializer(service, null);
if (LOG.isDebugEnabled()) LOG.debug("No classes in HandlesTypes on initializer "+service.getClass());
if (LOG.isDebugEnabled())
LOG.debug("No classes in HandlesTypes on initializer " + service.getClass());
}
}
else
{
initializer = new ContainerInitializer(service, null);
if (LOG.isDebugEnabled()) LOG.debug("No HandlesTypes annotation on initializer "+service.getClass());
if (LOG.isDebugEnabled())
LOG.debug("No HandlesTypes annotation on initializer " + service.getClass());
}
initializers.add(initializer);
}
//add a bean to the context which will call the servletcontainerinitializers when appropriate
ServletContainerInitializersStarter starter = (ServletContainerInitializersStarter)context.getAttribute(CONTAINER_INITIALIZER_STARTER);
if (starter != null)
@ -653,7 +648,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
context.addBean(starter, true);
}
public Resource getJarFor (ServletContainerInitializer service)
public Resource getJarFor(ServletContainerInitializer service)
throws MalformedURLException, IOException
{
URI uri = TypeUtil.getLocationOfClass(service.getClass());
@ -672,7 +667,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
* @return true if excluded
* @throws Exception if unable to determine exclusion
*/
public boolean isFromExcludedJar (WebAppContext context, ServletContainerInitializer sci, Resource sciResource)
public boolean isFromExcludedJar(WebAppContext context, ServletContainerInitializer sci, Resource sciResource)
throws Exception
{
if (sci == null)
@ -734,7 +729,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
if (LOG.isDebugEnabled())
LOG.debug("{}Excluded {} found={}",found?"!":"",sci,found);
LOG.debug("{}Excluded {} found={}", found ? "!" : "", sci, found);
return !found;
}
@ -753,11 +748,10 @@ public class AnnotationConfiguration extends AbstractConfiguration
//test if name of class matches the regex
if (LOG.isDebugEnabled())
LOG.debug("Checking {} against containerInitializerExclusionPattern",sci.getClass().getName());
LOG.debug("Checking {} against containerInitializerExclusionPattern", sci.getClass().getName());
return _sciExcludePattern.matcher(sci.getClass().getName()).matches();
}
/**
* Test if the ServletContainerInitializer is from the container classpath
*
@ -765,7 +759,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
* @param sci the ServletContainerIntializer
* @return true if ServletContainerIntializer is from container classpath
*/
public boolean isFromContainerClassPath (WebAppContext context, ServletContainerInitializer sci)
public boolean isFromContainerClassPath(WebAppContext context, ServletContainerInitializer sci)
{
if (sci == null)
return false;
@ -773,7 +767,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
ClassLoader sciLoader = sci.getClass().getClassLoader();
//if loaded by bootstrap loader, then its the container classpath
if ( sciLoader == null)
if (sciLoader == null)
return true;
//if there is no context classloader, then its the container classpath
@ -799,7 +793,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
* @param sci a Resource representing the SCI
* @return true if the sci Resource is inside a WEB-INF/classes directory, false otherwise
*/
public boolean isFromWebInfClasses (WebAppContext context, Resource sci)
public boolean isFromWebInfClasses(WebAppContext context, Resource sci)
{
for (Resource dir : context.getMetaData().getWebInfClassesDirs())
{
@ -813,11 +807,12 @@ public class AnnotationConfiguration extends AbstractConfiguration
/**
* Get SCIs that are not excluded from consideration
*
* @param context the web app context
* @return the list of non-excluded servlet container initializers
* @throws Exception if unable to get list
*/
public List<ServletContainerInitializer> getNonExcludedInitializers (WebAppContext context)
public List<ServletContainerInitializer> getNonExcludedInitializers(WebAppContext context)
throws Exception
{
ArrayList<ServletContainerInitializer> nonExcludedInitializers = new ArrayList<ServletContainerInitializer>();
@ -828,25 +823,25 @@ public class AnnotationConfiguration extends AbstractConfiguration
start = System.nanoTime();
ServiceLoader<ServletContainerInitializer> loader = ServiceLoader.load(ServletContainerInitializer.class);
if (LOG.isDebugEnabled())
LOG.debug("Service loaders found in {}ms", (TimeUnit.MILLISECONDS.convert((System.nanoTime()-start), TimeUnit.NANOSECONDS)));
LOG.debug("Service loaders found in {}ms", (TimeUnit.MILLISECONDS.convert((System.nanoTime() - start), TimeUnit.NANOSECONDS)));
Map<ServletContainerInitializer,Resource> sciResourceMap = new HashMap<ServletContainerInitializer,Resource>();
Map<ServletContainerInitializer, Resource> sciResourceMap = new HashMap<ServletContainerInitializer, Resource>();
ServletContainerInitializerOrdering initializerOrdering = getInitializerOrdering(context);
//Get initial set of SCIs that aren't from excluded jars or excluded by the containerExclusionPattern, or excluded
//because containerInitializerOrdering omits it
Iterator<ServletContainerInitializer> iter = loader.iterator();
while(iter.hasNext())
while (iter.hasNext())
{
ServletContainerInitializer sci;
try
{
sci=iter.next();
sci = iter.next();
}
catch(Error e)
catch (Error e)
{
// Probably a SCI discovered on the system classpath that is hidden by the context classloader
LOG.info("Error: "+e.getMessage()+" for "+context);
LOG.info("Error: " + e.getMessage() + " for " + context);
LOG.debug(e);
continue;
}
@ -868,8 +863,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
//check containerInitializerOrdering doesn't exclude it
String name = sci.getClass().getName();
if (initializerOrdering != null
&& (!initializerOrdering.hasWildcard() && initializerOrdering.getIndexOf(name) < 0))
if (initializerOrdering != null && (!initializerOrdering.hasWildcard() && initializerOrdering.getIndexOf(name) < 0))
{
if (LOG.isDebugEnabled())
LOG.debug("{} is excluded by ordering", sci);
@ -883,7 +877,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
if (initializerOrdering != null && !initializerOrdering.isDefaultOrder())
{
if (LOG.isDebugEnabled())
LOG.debug("Ordering ServletContainerInitializers with "+initializerOrdering);
LOG.debug("Ordering ServletContainerInitializers with " + initializerOrdering);
//There is an ordering that is not just "*".
//Arrange ServletContainerInitializers according to the ordering of classnames given, irrespective of coming from container or webapp classpaths
@ -898,9 +892,9 @@ public class AnnotationConfiguration extends AbstractConfiguration
//First add in all SCIs that can't be excluded
int lastContainerSCI = -1;
for (Map.Entry<ServletContainerInitializer, Resource> entry:sciResourceMap.entrySet())
for (Map.Entry<ServletContainerInitializer, Resource> entry : sciResourceMap.entrySet())
{
if (entry.getKey().getClass().getClassLoader()==context.getClassLoader().getParent())
if (entry.getKey().getClass().getClassLoader() == context.getClassLoader().getParent())
{
nonExcludedInitializers.add(++lastContainerSCI, entry.getKey()); //add all container SCIs before any webapp SCIs
}
@ -921,8 +915,10 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
//throw out the ones we've already accounted for
for (ServletContainerInitializer s:nonExcludedInitializers)
for (ServletContainerInitializer s : nonExcludedInitializers)
{
sciResourceMap.remove(s);
}
if (context.getMetaData().getOrdering() == null)
{
@ -934,12 +930,12 @@ public class AnnotationConfiguration extends AbstractConfiguration
else
{
if (LOG.isDebugEnabled())
LOG.debug("Ordering ServletContainerInitializers with ordering {}",context.getMetaData().getOrdering());
LOG.debug("Ordering ServletContainerInitializers with ordering {}", context.getMetaData().getOrdering());
//add SCIs according to the ordering of its containing jar
for (Resource webInfJar:context.getMetaData().getOrderedWebInfJars())
for (Resource webInfJar : context.getMetaData().getOrderedWebInfJars())
{
for (Map.Entry<ServletContainerInitializer, Resource> entry:sciResourceMap.entrySet())
for (Map.Entry<ServletContainerInitializer, Resource> entry : sciResourceMap.entrySet())
{
if (webInfJar.equals(entry.getValue()))
nonExcludedInitializers.add(entry.getKey());
@ -969,22 +965,23 @@ public class AnnotationConfiguration extends AbstractConfiguration
if (LOG.isDebugEnabled())
{
int i=0;
for (ServletContainerInitializer sci:nonExcludedInitializers)
LOG.debug("ServletContainerInitializer: {} {} from {}",(++i), sci.getClass().getName(), sciResourceMap.get(sci));
int i = 0;
for (ServletContainerInitializer sci : nonExcludedInitializers)
{
LOG.debug("ServletContainerInitializer: {} {} from {}", (++i), sci.getClass().getName(), sciResourceMap.get(sci));
}
}
return nonExcludedInitializers;
}
/**
* Jetty-specific extension that allows an ordering to be applied across ALL ServletContainerInitializers.
*
* @param context the context for the initializer ordering configuration
* @return the ordering of the ServletContainerIntializer's
*/
public ServletContainerInitializerOrdering getInitializerOrdering (WebAppContext context)
public ServletContainerInitializerOrdering getInitializerOrdering(WebAppContext context)
{
if (context == null)
return null;
@ -996,7 +993,6 @@ public class AnnotationConfiguration extends AbstractConfiguration
return new ServletContainerInitializerOrdering(tmp);
}
/**
* Scan jars on container path.
*
@ -1004,7 +1000,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
* @param parser the parser to scan with
* @throws Exception if unable to scan
*/
public void parseContainerPath (final WebAppContext context, final AnnotationParser parser) throws Exception
public void parseContainerPath(final WebAppContext context, final AnnotationParser parser) throws Exception
{
//always parse for discoverable annotations as well as class hierarchy and servletcontainerinitializer related annotations
final Set<Handler> handlers = new HashSet<Handler>();
@ -1032,7 +1028,6 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
}
/**
* Scan jars in WEB-INF/lib
*
@ -1040,7 +1035,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
* @param parser the annotation parser to use
* @throws Exception if unable to scan and/or parse
*/
public void parseWebInfLib (final WebAppContext context, final AnnotationParser parser) throws Exception
public void parseWebInfLib(final WebAppContext context, final AnnotationParser parser) throws Exception
{
List<FragmentDescriptor> frags = context.getMetaData().getFragments();
@ -1089,8 +1084,8 @@ public class AnnotationConfiguration extends AbstractConfiguration
if (_parserTasks != null)
{
ParserTask task = new ParserTask(parser, handlers,r);
_parserTasks.add (task);
ParserTask task = new ParserTask(parser, handlers, r);
_parserTasks.add(task);
if (LOG.isDebugEnabled())
{
_webInfLibStats.increment();
@ -1101,7 +1096,6 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
}
/**
* Scan classes in WEB-INF/classes
*
@ -1109,7 +1103,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
* @param parser the annotation parser to use
* @throws Exception if unable to scan and/or parse
*/
public void parseWebInfClasses (final WebAppContext context, final AnnotationParser parser)
public void parseWebInfClasses(final WebAppContext context, final AnnotationParser parser)
throws Exception
{
Set<Handler> handlers = new HashSet<Handler>();
@ -1136,8 +1130,6 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
}
/**
* Get the web-fragment.xml from a jar
*
@ -1146,15 +1138,15 @@ public class AnnotationConfiguration extends AbstractConfiguration
* @return true if the fragment if found, or null of not found
* @throws Exception if unable to determine the the fragment contains
*/
public FragmentDescriptor getFragmentFromJar (Resource jar, List<FragmentDescriptor> frags)
public FragmentDescriptor getFragmentFromJar(Resource jar, List<FragmentDescriptor> frags)
throws Exception
{
//check if the jar has a web-fragment.xml
FragmentDescriptor d = null;
for (FragmentDescriptor frag: frags)
for (FragmentDescriptor frag : frags)
{
Resource fragResource = frag.getResource(); //eg jar:file:///a/b/c/foo.jar!/META-INF/web-fragment.xml
if (Resource.isContainedIn(fragResource,jar))
if (Resource.isContainedIn(fragResource, jar))
{
d = frag;
break;
@ -1163,9 +1155,9 @@ public class AnnotationConfiguration extends AbstractConfiguration
return d;
}
public boolean isMetaDataComplete (WebDescriptor d)
public boolean isMetaDataComplete(WebDescriptor d)
{
return (d!=null && d.getMetaDataComplete() == MetaDataComplete.True);
return (d != null && d.getMetaDataComplete() == MetaDataComplete.True);
}
public static class ClassInheritanceMap extends ConcurrentHashMap<String, Set<String>>
@ -1174,7 +1166,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
@Override
public String toString()
{
return String.format("ClassInheritanceMap@%x{size=%d}",hashCode(),size());
return String.format("ClassInheritanceMap@%x{size=%d}", hashCode(), size());
}
}
}

View File

@ -33,7 +33,7 @@ public class AnnotationDecorator implements Decorator
registerHandlers(context);
}
public void registerHandlers (WebAppContext context)
public void registerHandlers(WebAppContext context)
{
_introspector.registerHandler(new ResourceAnnotationHandler(context));
_introspector.registerHandler(new ResourcesAnnotationHandler(context));
@ -54,9 +54,10 @@ public class AnnotationDecorator implements Decorator
* <li> PreDestroy </li>
* <li> ServletSecurity? </li>
* </ul>
*
* @param o the object ot introspect
*/
protected void introspect (Object o)
protected void introspect(Object o)
{
_introspector.introspect(o.getClass());
}

View File

@ -23,14 +23,11 @@ import java.util.List;
/**
* AnnotationIntrospector
*
*
*/
public class AnnotationIntrospector
{
protected List<IntrospectableAnnotationHandler> _handlers = new ArrayList<IntrospectableAnnotationHandler>();
/**
* IntrospectableAnnotationHandler
*
@ -41,21 +38,18 @@ public class AnnotationIntrospector
public void handle(Class<?> clazz);
}
/**
* AbstractIntrospectableAnnotationHandler
*
* Base class for handlers that introspect a class to find a particular annotation.
* A handler can optionally introspect the parent hierarchy of a class.
*/
public static abstract class AbstractIntrospectableAnnotationHandler implements IntrospectableAnnotationHandler
public abstract static class AbstractIntrospectableAnnotationHandler implements IntrospectableAnnotationHandler
{
private boolean _introspectAncestors;
public abstract void doHandle(Class<?> clazz);
public AbstractIntrospectableAnnotationHandler(boolean introspectAncestors)
{
_introspectAncestors = introspectAncestors;
@ -67,7 +61,7 @@ public class AnnotationIntrospector
Class<?> c = clazz;
//process the whole inheritance hierarchy for the class
while (c!=null && (!c.equals(Object.class)))
while (c != null && (!c.equals(Object.class)))
{
doHandle(c);
if (!_introspectAncestors)
@ -78,19 +72,19 @@ public class AnnotationIntrospector
}
}
public void registerHandler (IntrospectableAnnotationHandler handler)
public void registerHandler(IntrospectableAnnotationHandler handler)
{
_handlers.add(handler);
}
public void introspect (Class<?> clazz)
public void introspect(Class<?> clazz)
{
if (_handlers == null)
return;
if (clazz == null)
return;
for (IntrospectableAnnotationHandler handler:_handlers)
for (IntrospectableAnnotationHandler handler : _handlers)
{
try
{
@ -105,6 +99,5 @@ public class AnnotationIntrospector
throw new RuntimeException(e);
}
}
}
}

View File

@ -82,9 +82,10 @@ public class AnnotationParser
/**
* Determine the runtime version of asm.
*
* @return the org.objectweb.asm.Opcode matching the runtime version of asm.
*/
public static int asmVersion ()
public static int asmVersion()
{
int asmVersion = ASM_OPCODE_VERSION;
String version = ManifestUtils.getVersion(Opcodes.class).orElse(null);
@ -141,18 +142,18 @@ public class AnnotationParser
* @param name the internal name
* @return the simple name
*/
public static String normalize (String name)
public static String normalize(String name)
{
if (name==null)
if (name == null)
return null;
if (name.startsWith("L") && name.endsWith(";"))
name = name.substring(1, name.length()-1);
name = name.substring(1, name.length() - 1);
if (name.endsWith(".class"))
name = name.substring(0, name.length()-".class".length());
name = name.substring(0, name.length() - ".class".length());
return StringUtil.replace(name,'/', '.');
return StringUtil.replace(name, '/', '.');
}
/**
@ -161,14 +162,16 @@ public class AnnotationParser
* @param list the list of internal names
* @return the list of simple names
*/
public static String[] normalize (String[] list)
public static String[] normalize(String[] list)
{
if (list == null)
return null;
String[] normalList = new String[list.length];
int i=0;
int i = 0;
for (String s : list)
{
normalList[i++] = normalize(s);
}
return normalList;
}
@ -347,17 +350,22 @@ public class AnnotationParser
public static interface Handler
{
public void handle(ClassInfo classInfo);
public void handle(MethodInfo methodInfo);
public void handle (FieldInfo fieldInfo);
public void handle (ClassInfo info, String annotationName);
public void handle (MethodInfo info, String annotationName);
public void handle (FieldInfo info, String annotationName);
public void handle(FieldInfo fieldInfo);
public void handle(ClassInfo info, String annotationName);
public void handle(MethodInfo info, String annotationName);
public void handle(FieldInfo info, String annotationName);
}
/**
* Convenience base class to provide no-ops for all Handler methods.
*/
public static abstract class AbstractHandler implements Handler
public abstract static class AbstractHandler implements Handler
{
@Override
public void handle(ClassInfo classInfo)
@ -409,7 +417,7 @@ public class AnnotationParser
{
super(asmVersion);
_handlers = handlers;
_mi = new MethodInfo(classInfo, name, access, methodDesc,signature, exceptions);
_mi = new MethodInfo(classInfo, name, access, methodDesc, signature, exceptions);
}
/**
@ -419,8 +427,10 @@ public class AnnotationParser
public AnnotationVisitor visitAnnotation(String desc, boolean visible)
{
String annotationName = normalize(desc);
for (Handler h:_handlers)
for (Handler h : _handlers)
{
h.handle(_mi, annotationName);
}
return null;
}
}
@ -456,7 +466,9 @@ public class AnnotationParser
{
String annotationName = normalize(desc);
for (Handler h : _handlers)
{
h.handle(_fieldInfo, annotationName);
}
return null;
}
@ -481,7 +493,7 @@ public class AnnotationParser
}
@Override
public void visit (final int version,
public void visit(final int version,
final int access,
final String name,
final String signature,
@ -489,19 +501,23 @@ public class AnnotationParser
final String[] interfaces)
{
_ci = new ClassInfo(_containingResource, normalize(name), version, access, signature, normalize(superName), normalize(interfaces));
for (Handler h:_handlers)
for (Handler h : _handlers)
{
h.handle(_ci);
}
}
/**
* Visit an annotation on a Class
*/
@Override
public AnnotationVisitor visitAnnotation (String desc, boolean visible)
public AnnotationVisitor visitAnnotation(String desc, boolean visible)
{
String annotationName = normalize(desc);
for (Handler h : _handlers)
{
h.handle(_ci, annotationName);
}
return null;
}
@ -509,7 +525,7 @@ public class AnnotationParser
* Visit a method to extract its annotations
*/
@Override
public MethodVisitor visitMethod (final int access,
public MethodVisitor visitMethod(final int access,
final String name,
final String methodDesc,
final String signature,
@ -522,7 +538,7 @@ public class AnnotationParser
* Visit a field to extract its annotations
*/
@Override
public FieldVisitor visitField (final int access,
public FieldVisitor visitField(final int access,
final String fieldName,
final String fieldType,
final String signature,
@ -543,18 +559,17 @@ public class AnnotationParser
public AnnotationParser(int javaPlatform)
{
_asmVersion = asmVersion();
if (javaPlatform==0)
if (javaPlatform == 0)
javaPlatform = JavaVersion.VERSION.getPlatform();
_javaPlatform = javaPlatform;
}
public AnnotationParser(int javaPlatform, int asmVersion)
{
if (javaPlatform==0)
if (javaPlatform == 0)
javaPlatform = JavaVersion.VERSION.getPlatform();
_javaPlatform = javaPlatform;
if (asmVersion==0)
if (asmVersion == 0)
asmVersion = ASM_OPCODE_VERSION;
_asmVersion = asmVersion;
}
@ -565,7 +580,7 @@ public class AnnotationParser
* @param classname the name of the class
* @param location the fully qualified location of the class
*/
public void addParsedClass (String classname, Resource location)
public void addParsedClass(String classname, Resource location)
{
Resource existing = _parsedClassNames.putIfAbsent(classname, location);
if (existing != null)
@ -579,14 +594,14 @@ public class AnnotationParser
* @param className the class name to parse
* @throws Exception if unable to parse
*/
public void parse (Set<? extends Handler> handlers, String className) throws Exception
public void parse(Set<? extends Handler> handlers, String className) throws Exception
{
if (className == null)
return;
String classRef = TypeUtil.toClassReference(className);
URL resource = Loader.getResource(classRef);
if (resource!= null)
if (resource != null)
{
Resource r = Resource.newResource(resource);
addParsedClass(className, r);
@ -605,14 +620,14 @@ public class AnnotationParser
* @param visitSuperClasses if true, also visit super classes for parse
* @throws Exception if unable to parse class
*/
public void parse (Set<? extends Handler> handlers, Class<?> clazz, boolean visitSuperClasses) throws Exception
public void parse(Set<? extends Handler> handlers, Class<?> clazz, boolean visitSuperClasses) throws Exception
{
Class<?> cz = clazz;
while (cz != Object.class)
{
String nameAsResource = TypeUtil.toClassReference(cz);
URL resource = Loader.getResource(nameAsResource);
if (resource!= null)
if (resource != null)
{
Resource r = Resource.newResource(resource);
addParsedClass(clazz.getName(), r);
@ -636,7 +651,7 @@ public class AnnotationParser
* @param classNames the class name
* @throws Exception if unable to parse
*/
public void parse (Set<? extends Handler> handlers, String[] classNames) throws Exception
public void parse(Set<? extends Handler> handlers, String[] classNames) throws Exception
{
if (classNames == null)
return;
@ -651,7 +666,7 @@ public class AnnotationParser
* @param classNames the class names
* @throws Exception if unable to parse
*/
public void parse (Set<? extends Handler> handlers, List<String> classNames) throws Exception
public void parse(Set<? extends Handler> handlers, List<String> classNames) throws Exception
{
MultiException me = new MultiException();
@ -661,7 +676,7 @@ public class AnnotationParser
{
String classRef = TypeUtil.toClassReference(className);
URL resource = Loader.getResource(classRef);
if (resource!= null)
if (resource != null)
{
Resource r = Resource.newResource(resource);
addParsedClass(className, r);
@ -673,7 +688,7 @@ public class AnnotationParser
}
catch (Exception e)
{
me.add(new RuntimeException("Error scanning class "+className, e));
me.add(new RuntimeException("Error scanning class " + className, e));
}
}
me.ifExceptionThrow();
@ -686,7 +701,7 @@ public class AnnotationParser
* @param root the resource directory to look for classes
* @throws Exception if unable to parse
*/
protected void parseDir (Set<? extends Handler> handlers, Resource root) throws Exception
protected void parseDir(Set<? extends Handler> handlers, Resource root) throws Exception
{
if (!root.isDirectory() || !root.exists() || root.getName().startsWith("."))
return;
@ -700,13 +715,13 @@ public class AnnotationParser
Collection<Resource> resources = root.getAllResources();
if (resources != null)
{
for (Resource r:resources)
for (Resource r : resources)
{
if (r.isDirectory())
continue;
File file = r.getFile();
if (isValidClassFileName((file==null?null:file.getName())))
if (isValidClassFileName((file == null ? null : file.getName())))
{
Path classpath = rootFile.toPath().relativize(file.toPath());
String str = classpath.toString();
@ -718,20 +733,22 @@ public class AnnotationParser
if (LOG.isDebugEnabled())
LOG.debug("Scanning class {}", r);
addParsedClass(str, r);
try (InputStream is=r.getInputStream())
try (InputStream is = r.getInputStream())
{
scanClass(handlers, Resource.newResource(file.getParentFile()), is);
}
}
catch (Exception ex)
{
if (LOG.isDebugEnabled()) LOG.debug("Error scanning file "+file, ex);
me.add(new RuntimeException("Error scanning file "+file,ex));
if (LOG.isDebugEnabled())
LOG.debug("Error scanning file " + file, ex);
me.add(new RuntimeException("Error scanning file " + file, ex));
}
}
else
{
if (LOG.isDebugEnabled()) LOG.debug("Skipping scan on invalid file {}", file);
if (LOG.isDebugEnabled())
LOG.debug("Skipping scan on invalid file {}", file);
}
}
}
@ -746,14 +763,14 @@ public class AnnotationParser
* @param uris the uris for the jars
* @throws Exception if unable to parse
*/
public void parse (final Set<? extends Handler> handlers, final URI[] uris) throws Exception
public void parse(final Set<? extends Handler> handlers, final URI[] uris) throws Exception
{
if (uris==null)
if (uris == null)
return;
MultiException me = new MultiException();
for (URI uri:uris)
for (URI uri : uris)
{
try
{
@ -761,7 +778,7 @@ public class AnnotationParser
}
catch (Exception e)
{
me.add(new RuntimeException("Problem parsing classes from "+ uri, e));
me.add(new RuntimeException("Problem parsing classes from " + uri, e));
}
}
me.ifExceptionThrow();
@ -774,12 +791,12 @@ public class AnnotationParser
* @param uri the uri for the jar
* @throws Exception if unable to parse
*/
public void parse (final Set<? extends Handler> handlers, URI uri) throws Exception
public void parse(final Set<? extends Handler> handlers, URI uri) throws Exception
{
if (uri == null)
return;
parse (handlers, Resource.newResource(uri));
parse(handlers, Resource.newResource(uri));
}
/**
@ -789,7 +806,7 @@ public class AnnotationParser
* @param r the resource to parse
* @throws Exception if unable to parse
*/
public void parse (final Set<? extends Handler> handlers, Resource r) throws Exception
public void parse(final Set<? extends Handler> handlers, Resource r) throws Exception
{
if (r == null)
return;
@ -809,14 +826,15 @@ public class AnnotationParser
if (fullname.endsWith(".class"))
{
try (InputStream is=r.getInputStream())
try (InputStream is = r.getInputStream())
{
scanClass(handlers, null, is);
return;
}
}
if (LOG.isDebugEnabled()) LOG.warn("Resource not scannable for classes: {}", r);
if (LOG.isDebugEnabled())
LOG.warn("Resource not scannable for classes: {}", r);
}
/**
@ -826,7 +844,7 @@ public class AnnotationParser
* @param jarResource the jar resource to parse
* @throws Exception if unable to parse
*/
protected void parseJar (Set<? extends Handler> handlers, Resource jarResource) throws Exception
protected void parseJar(Set<? extends Handler> handlers, Resource jarResource) throws Exception
{
if (jarResource == null)
return;
@ -837,9 +855,9 @@ public class AnnotationParser
LOG.debug("Scanning jar {}", jarResource);
MultiException me = new MultiException();
try (MultiReleaseJarFile jarFile = new MultiReleaseJarFile(jarResource.getFile(),_javaPlatform,false))
try (MultiReleaseJarFile jarFile = new MultiReleaseJarFile(jarResource.getFile(), _javaPlatform, false))
{
jarFile.stream().forEach(e->
jarFile.stream().forEach(e ->
{
try
{
@ -863,7 +881,7 @@ public class AnnotationParser
* @param jar the jar file
* @throws Exception if unable to parse
*/
protected void parseJarEntry (Set<? extends Handler> handlers, Resource jar, MultiReleaseJarFile.VersionedJarEntry entry)
protected void parseJarEntry(Set<? extends Handler> handlers, Resource jar, MultiReleaseJarFile.VersionedJarEntry entry)
throws Exception
{
if (jar == null || entry == null)
@ -879,7 +897,7 @@ public class AnnotationParser
if (isValidClassFileName(name) && isValidClassFilePath(name))
{
String shortName = StringUtil.replace(name, '/', '.').substring(0, name.length() - 6);
addParsedClass(shortName, Resource.newResource("jar:"+jar.getURI()+"!/"+entry.getNameInJar()));
addParsedClass(shortName, Resource.newResource("jar:" + jar.getURI() + "!/" + entry.getNameInJar()));
if (LOG.isDebugEnabled())
LOG.debug("Scanning class from jar {}!/{}", jar, entry);
try (InputStream is = entry.getInputStream())
@ -897,16 +915,16 @@ public class AnnotationParser
* @param is the input stream to parse
* @throws IOException if unable to parse
*/
protected void scanClass (Set<? extends Handler> handlers, Resource containingResource, InputStream is) throws IOException
protected void scanClass(Set<? extends Handler> handlers, Resource containingResource, InputStream is) throws IOException
{
ClassReader reader = new ClassReader(is);
reader.accept(new MyClassVisitor(handlers, containingResource, _asmVersion), ClassReader.SKIP_CODE|ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES);
reader.accept(new MyClassVisitor(handlers, containingResource, _asmVersion), ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
}
/**
* Remove any parsed class names.
*/
public void resetParsedClasses ()
public void resetParsedClasses()
{
_parsedClassNames.clear();
}
@ -919,36 +937,40 @@ public class AnnotationParser
* <li> it isn't a dot file or in a hidden directory </li>
* <li> the name of the class at least begins with a valid identifier for a class name </li>
* </ul>
*
* @param name the class file name
* @return whether the class file name is valid
*/
private boolean isValidClassFileName (String name)
private boolean isValidClassFileName(String name)
{
//no name cannot be valid
if (name == null || name.length()==0)
if (name == null || name.length() == 0)
return false;
//skip anything that is not a class file
String lc = name.toLowerCase(Locale.ENGLISH);
if (!lc.endsWith(".class"))
{
if (LOG.isDebugEnabled()) LOG.debug("Not a class: {}",name);
if (LOG.isDebugEnabled())
LOG.debug("Not a class: {}", name);
return false;
}
if (lc.equals("module-info.class"))
{
if (LOG.isDebugEnabled()) LOG.debug("Skipping module-info.class");
if (LOG.isDebugEnabled())
LOG.debug("Skipping module-info.class");
return false;
}
//skip any classfiles that are not a valid java identifier
int c0 = 0;
int ldir = name.lastIndexOf('/', name.length()-6);
c0 = (ldir > -1 ? ldir+1 : c0);
int ldir = name.lastIndexOf('/', name.length() - 6);
c0 = (ldir > -1 ? ldir + 1 : c0);
if (!Character.isJavaIdentifierStart(name.charAt(c0)))
{
if (LOG.isDebugEnabled()) LOG.debug("Not a java identifier: {}",name);
if (LOG.isDebugEnabled())
LOG.debug("Not a java identifier: {}", name);
return false;
}
@ -961,16 +983,17 @@ public class AnnotationParser
* @param path the class file path
* @return whether the class file path is valid
*/
private boolean isValidClassFilePath (String path)
private boolean isValidClassFilePath(String path)
{
//no path is not valid
if (path == null || path.length()==0)
if (path == null || path.length() == 0)
return false;
// skip any classfiles that are in a hidden directory
if (path.startsWith(".") || path.contains("/."))
{
if (LOG.isDebugEnabled()) LOG.debug("Contains hidden dirs: " + path);
if (LOG.isDebugEnabled())
LOG.debug("Contains hidden dirs: " + path);
return false;
}

View File

@ -38,7 +38,6 @@ public class ClassInheritanceHandler extends AbstractHandler
Map<String, Set<String>> _inheritanceMap;
public ClassInheritanceHandler(Map<String, Set<String>> map)
{
_inheritanceMap = map;
@ -53,7 +52,7 @@ public class ClassInheritanceHandler extends AbstractHandler
if ("java.lang.Object".equals(classInfo.getClassName()))
return;
for (int i=0; classInfo.getInterfaces() != null && i < classInfo.getInterfaces().length;i++)
for (int i = 0; classInfo.getInterfaces() != null && i < classInfo.getInterfaces().length; i++)
{
addToInheritanceMap(classInfo.getInterfaces()[i], classInfo.getClassName());
}
@ -69,7 +68,7 @@ public class ClassInheritanceHandler extends AbstractHandler
}
}
private void addToInheritanceMap (String interfaceOrSuperClassName, String implementingOrExtendingClassName)
private void addToInheritanceMap(String interfaceOrSuperClassName, String implementingOrExtendingClassName)
{
//As it is likely that the interfaceOrSuperClassName is already in the map, try getting it first

View File

@ -16,10 +16,8 @@
// ========================================================================
//
package org.eclipse.jetty.annotations;
import org.eclipse.jetty.annotations.AnnotationParser.AbstractHandler;
import org.eclipse.jetty.annotations.AnnotationParser.ClassInfo;
import org.eclipse.jetty.annotations.AnnotationParser.FieldInfo;
@ -38,7 +36,7 @@ public class ContainerInitializerAnnotationHandler extends AbstractHandler
final ContainerInitializer _initializer;
final Class _annotation;
public ContainerInitializerAnnotationHandler (ContainerInitializer initializer, Class annotation)
public ContainerInitializerAnnotationHandler(ContainerInitializer initializer, Class annotation)
{
_initializer = initializer;
_annotation = annotation;
@ -84,7 +82,6 @@ public class ContainerInitializerAnnotationHandler extends AbstractHandler
_initializer.addAnnotatedTypeName(info.getClassInfo().getClassName());
}
public ContainerInitializer getContainerInitializer()
{
return _initializer;

View File

@ -18,7 +18,6 @@
package org.eclipse.jetty.annotations;
import javax.annotation.security.DeclareRoles;
import javax.servlet.Servlet;
@ -44,7 +43,6 @@ public class DeclareRolesAnnotationHandler extends AbstractIntrospectableAnnotat
_context = context;
}
/**
* @see org.eclipse.jetty.annotations.AnnotationIntrospector.AbstractIntrospectableAnnotationHandler#doHandle(java.lang.Class)
*/
@ -60,7 +58,7 @@ public class DeclareRolesAnnotationHandler extends AbstractIntrospectableAnnotat
return;
}
DeclareRoles declareRoles = (DeclareRoles) clazz.getAnnotation(DeclareRoles.class);
DeclareRoles declareRoles = (DeclareRoles)clazz.getAnnotation(DeclareRoles.class);
if (declareRoles == null)
return;
@ -68,9 +66,10 @@ public class DeclareRolesAnnotationHandler extends AbstractIntrospectableAnnotat
if (roles != null && roles.length > 0)
{
for (String r:roles)
for (String r : roles)
{
((ConstraintSecurityHandler)_context.getSecurityHandler()).addRole(r);
}
}
}
}

View File

@ -30,8 +30,6 @@ import org.eclipse.jetty.webapp.WebAppContext;
/**
* MultiPartConfigAnnotationHandler
*
*
*/
public class MultiPartConfigAnnotationHandler extends AbstractIntrospectableAnnotationHandler
{
@ -43,6 +41,7 @@ public class MultiPartConfigAnnotationHandler extends AbstractIntrospectableAnno
super(false);
_context = context;
}
/**
* @see org.eclipse.jetty.annotations.AnnotationIntrospector.AbstractIntrospectableAnnotationHandler#doHandle(java.lang.Class)
*/
@ -52,7 +51,7 @@ public class MultiPartConfigAnnotationHandler extends AbstractIntrospectableAnno
if (!Servlet.class.isAssignableFrom(clazz))
return;
MultipartConfig multi = (MultipartConfig) clazz.getAnnotation(MultipartConfig.class);
MultipartConfig multi = (MultipartConfig)clazz.getAnnotation(MultipartConfig.class);
if (multi == null)
return;
@ -64,12 +63,12 @@ public class MultiPartConfigAnnotationHandler extends AbstractIntrospectableAnno
//Assuming TRUE for now.
for (ServletHolder holder : _context.getServletHandler().getServlets(clazz))
{
Descriptor d = metaData.getOriginDescriptor(holder.getName()+".servlet.multipart-config");
Descriptor d = metaData.getOriginDescriptor(holder.getName() + ".servlet.multipart-config");
//if a descriptor has already set the value for multipart config, do not
//let the annotation override it
if (d == null)
{
metaData.setOrigin(holder.getName()+".servlet.multipart-config",multi,clazz);
metaData.setOrigin(holder.getName() + ".servlet.multipart-config", multi, clazz);
holder.getRegistration().setMultipartConfig(new MultipartConfigElement(multi));
}
}

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.annotations;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import javax.annotation.PostConstruct;
import org.eclipse.jetty.annotations.AnnotationIntrospector.AbstractIntrospectableAnnotationHandler;
@ -34,13 +33,12 @@ public class PostConstructAnnotationHandler extends AbstractIntrospectableAnnota
{
protected WebAppContext _context;
public PostConstructAnnotationHandler (WebAppContext wac)
public PostConstructAnnotationHandler(WebAppContext wac)
{
super(true);
_context = wac;
}
@Override
public void doHandle(Class clazz)
{
@ -48,19 +46,19 @@ public class PostConstructAnnotationHandler extends AbstractIntrospectableAnnota
if (supportsPostConstruct(clazz))
{
Method[] methods = clazz.getDeclaredMethods();
for (int i=0; i<methods.length; i++)
for (int i = 0; i < methods.length; i++)
{
Method m = (Method)methods[i];
if (m.isAnnotationPresent(PostConstruct.class))
{
if (m.getParameterCount() != 0)
throw new IllegalStateException(m+" has parameters");
throw new IllegalStateException(m + " has parameters");
if (m.getReturnType() != Void.TYPE)
throw new IllegalStateException(m+" is not void");
throw new IllegalStateException(m + " is not void");
if (m.getExceptionTypes().length != 0)
throw new IllegalStateException(m+" throws checked exceptions");
throw new IllegalStateException(m + " throws checked exceptions");
if (Modifier.isStatic(m.getModifiers()))
throw new IllegalStateException(m+" is static");
throw new IllegalStateException(m + " is static");
//ServletSpec 3.0 p80 If web.xml declares even one post-construct then all post-constructs
//in fragments must be ignored. Otherwise, they are additive.
@ -78,7 +76,7 @@ public class PostConstructAnnotationHandler extends AbstractIntrospectableAnnota
if (lifecycles == null)
{
lifecycles = new LifeCycleCallbackCollection();
_context.setAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION,lifecycles);
_context.setAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION, lifecycles);
}
lifecycles.add(callback);
}
@ -88,10 +86,11 @@ public class PostConstructAnnotationHandler extends AbstractIntrospectableAnnota
/**
* Check if the given class is permitted to have PostConstruct annotation.
*
* @param c the class
* @return true if the spec permits the class to have PostConstruct, false otherwise
*/
public boolean supportsPostConstruct (Class c)
public boolean supportsPostConstruct(Class c)
{
if (javax.servlet.Servlet.class.isAssignableFrom(c) ||
javax.servlet.Filter.class.isAssignableFrom(c) ||

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.annotations;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import javax.annotation.PreDestroy;
import org.eclipse.jetty.annotations.AnnotationIntrospector.AbstractIntrospectableAnnotationHandler;
@ -34,7 +33,7 @@ public class PreDestroyAnnotationHandler extends AbstractIntrospectableAnnotatio
{
WebAppContext _context;
public PreDestroyAnnotationHandler (WebAppContext wac)
public PreDestroyAnnotationHandler(WebAppContext wac)
{
super(true);
_context = wac;
@ -47,19 +46,19 @@ public class PreDestroyAnnotationHandler extends AbstractIntrospectableAnnotatio
if (supportsPreDestroy(clazz))
{
Method[] methods = clazz.getDeclaredMethods();
for (int i=0; i<methods.length; i++)
for (int i = 0; i < methods.length; i++)
{
Method m = (Method)methods[i];
if (m.isAnnotationPresent(PreDestroy.class))
{
if (m.getParameterCount() != 0)
throw new IllegalStateException(m+" has parameters");
throw new IllegalStateException(m + " has parameters");
if (m.getReturnType() != Void.TYPE)
throw new IllegalStateException(m+" is not void");
throw new IllegalStateException(m + " is not void");
if (m.getExceptionTypes().length != 0)
throw new IllegalStateException(m+" throws checked exceptions");
throw new IllegalStateException(m + " throws checked exceptions");
if (Modifier.isStatic(m.getModifiers()))
throw new IllegalStateException(m+" is static");
throw new IllegalStateException(m + " is static");
//ServletSpec 3.0 p80 If web.xml declares even one predestroy then all predestroys
//in fragments must be ignored. Otherwise, they are additive.
@ -89,10 +88,11 @@ public class PreDestroyAnnotationHandler extends AbstractIntrospectableAnnotatio
/**
* Check if the spec permits the given class to use the PreDestroy annotation.
*
* @param c the class
* @return true if permitted, false otherwise
*/
public boolean supportsPreDestroy (Class c)
public boolean supportsPreDestroy(Class c)
{
if (javax.servlet.Servlet.class.isAssignableFrom(c) ||
javax.servlet.Filter.class.isAssignableFrom(c) ||

View File

@ -24,7 +24,6 @@ import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
@ -43,19 +42,19 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
private static final Logger LOG = Log.getLogger(ResourceAnnotationHandler.class);
protected static final List<Class<?>> ENV_ENTRY_TYPES =
Arrays.asList(new Class[] {String.class, Character.class, Integer.class, Boolean.class, Double.class, Byte.class, Short.class, Long.class, Float.class});
Arrays.asList(new Class[]{
String.class, Character.class, Integer.class, Boolean.class, Double.class, Byte.class, Short.class, Long.class,
Float.class
});
protected WebAppContext _context;
public ResourceAnnotationHandler (WebAppContext wac)
public ResourceAnnotationHandler(WebAppContext wac)
{
super(true);
_context = wac;
}
/**
* Class level Resource annotations declare a name in the
* environment that will be looked up at runtime. They do
@ -69,16 +68,20 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
handleClass(clazz);
Method[] methods = clazz.getDeclaredMethods();
for (int i=0; i<methods.length; i++)
for (int i = 0; i < methods.length; i++)
{
handleMethod(clazz, methods[i]);
}
Field[] fields = clazz.getDeclaredFields();
//For each field, get all of it's annotations
for (int i=0; i<fields.length; i++)
for (int i = 0; i < fields.length; i++)
{
handleField(clazz, fields[i]);
}
}
}
public void handleClass (Class<?> clazz)
public void handleClass(Class<?> clazz)
{
Resource resource = (Resource)clazz.getAnnotation(Resource.class);
if (resource != null)
@ -86,14 +89,14 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
String name = resource.name();
String mappedName = resource.mappedName();
if (name==null || name.trim().equals(""))
throw new IllegalStateException ("Class level Resource annotations must contain a name (Common Annotations Spec Section 2.3)");
if (name == null || name.trim().equals(""))
throw new IllegalStateException("Class level Resource annotations must contain a name (Common Annotations Spec Section 2.3)");
try
{
if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context, name,mappedName))
if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context.getServer(), name,mappedName))
throw new IllegalStateException("No resource at "+(mappedName==null?name:mappedName));
if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context, name, mappedName))
if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_context.getServer(), name, mappedName))
throw new IllegalStateException("No resource at " + (mappedName == null ? name : mappedName));
}
catch (NamingException e)
{
@ -110,23 +113,23 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
//JavaEE Spec 5.2.3: Field cannot be static
if (Modifier.isStatic(field.getModifiers()))
{
LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+field.getName()+": cannot be static");
LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + field.getName() + ": cannot be static");
return;
}
//JavaEE Spec 5.2.3: Field cannot be final
if (Modifier.isFinal(field.getModifiers()))
{
LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+field.getName()+": cannot be final");
LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + field.getName() + ": cannot be final");
return;
}
//work out default name
String name = clazz.getCanonicalName()+"/"+field.getName();
String name = clazz.getCanonicalName() + "/" + field.getName();
//allow @Resource name= to override the field name
name = (resource.name()!=null && !resource.name().trim().equals("")? resource.name(): name);
String mappedName = (resource.mappedName()!=null && !resource.mappedName().trim().equals("")?resource.mappedName():null);
name = (resource.name() != null && !resource.name().trim().equals("") ? resource.name() : name);
String mappedName = (resource.mappedName() != null && !resource.mappedName().trim().equals("") ? resource.mappedName() : null);
//get the type of the Field
Class<?> type = field.getType();
@ -134,7 +137,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
//If a descriptor has specified at least 1 injection target for this
//resource, then it overrides this annotation
MetaData metaData = _context.getMetaData();
if (metaData.getOriginDescriptor("resource-ref."+name+".injection") != null)
if (metaData.getOriginDescriptor("resource-ref." + name + ".injection") != null)
{
//at least 1 injection was specified for this resource by a descriptor, so
//it overrides this annotation
@ -166,8 +169,8 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
try
{
InitialContext ic = new InitialContext();
String nameInEnvironment = (mappedName!=null?mappedName:name);
ic.lookup("java:comp/env/"+nameInEnvironment);
String nameInEnvironment = (mappedName != null ? mappedName : name);
ic.lookup("java:comp/env/" + nameInEnvironment);
bound = true;
}
catch (NameNotFoundException e)
@ -178,7 +181,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
//Check there is a JNDI entry for this annotation
if (bound)
{
LOG.debug("Bound "+(mappedName==null?name:mappedName) + " as "+ name);
LOG.debug("Bound " + (mappedName == null ? name : mappedName) + " as " + name);
// Make the Injection for it if the binding succeeded
injection = new Injection();
injection.setTarget(clazz, field, type);
@ -187,7 +190,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
injections.add(injection);
//TODO - an @Resource is equivalent to a resource-ref, resource-env-ref, message-destination
metaData.setOrigin("resource-ref."+name+".injection",resource,clazz);
metaData.setOrigin("resource-ref." + name + ".injection", resource, clazz);
}
else if (!isEnvEntryType(type))
{
@ -195,7 +198,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
//an error, it just means that perhaps the code will use a default value instead
// JavaEE Spec. sec 5.4.1.3
throw new IllegalStateException("No resource at "+(mappedName==null?name:mappedName));
throw new IllegalStateException("No resource at " + (mappedName == null ? name : mappedName));
}
}
catch (NamingException e)
@ -210,7 +213,6 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
}
}
/**
* Process a Resource annotation on a Method.
* <p>
@ -246,7 +248,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
//JavaEE Spec 5.2.3: Method cannot be static
if (Modifier.isStatic(method.getModifiers()))
{
LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+method.getName()+": cannot be static");
LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": cannot be static");
return;
}
@ -254,30 +256,29 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
// only 1 parameter
if (!method.getName().startsWith("set"))
{
LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+method.getName()+": invalid java bean, does not start with 'set'");
LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": invalid java bean, does not start with 'set'");
return;
}
if (method.getParameterCount() != 1)
{
LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+method.getName()+": invalid java bean, not single argument to method");
LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": invalid java bean, not single argument to method");
return;
}
if (Void.TYPE != method.getReturnType())
{
LOG.warn("Skipping Resource annotation on "+clazz.getName()+"."+method.getName()+": invalid java bean, not void");
LOG.warn("Skipping Resource annotation on " + clazz.getName() + "." + method.getName() + ": invalid java bean, not void");
return;
}
//default name is the javabean property name
String name = method.getName().substring(3);
name = name.substring(0,1).toLowerCase(Locale.ENGLISH)+name.substring(1);
name = clazz.getCanonicalName()+"/"+name;
name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
name = clazz.getCanonicalName() + "/" + name;
name = (resource.name()!=null && !resource.name().trim().equals("")? resource.name(): name);
String mappedName = (resource.mappedName()!=null && !resource.mappedName().trim().equals("")?resource.mappedName():null);
name = (resource.name() != null && !resource.name().trim().equals("") ? resource.name() : name);
String mappedName = (resource.mappedName() != null && !resource.mappedName().trim().equals("") ? resource.mappedName() : null);
Class<?> paramType = method.getParameterTypes()[0];
Class<?> resourceType = resource.type();
@ -286,7 +287,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
//If a descriptor has specified at least 1 injection target for this
//resource, then it overrides this annotation
MetaData metaData = _context.getMetaData();
if (metaData.getOriginDescriptor("resource-ref."+name+".injection") != null)
if (metaData.getOriginDescriptor("resource-ref." + name + ".injection") != null)
{
//at least 1 injection was specified for this resource by a descriptor, so
//it overrides this annotation
@ -324,8 +325,8 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
try
{
InitialContext ic = new InitialContext();
String nameInEnvironment = (mappedName!=null?mappedName:name);
ic.lookup("java:comp/env/"+nameInEnvironment);
String nameInEnvironment = (mappedName != null ? mappedName : name);
ic.lookup("java:comp/env/" + nameInEnvironment);
bound = true;
}
catch (NameNotFoundException e)
@ -336,15 +337,15 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
if (bound)
{
LOG.debug("Bound "+(mappedName==null?name:mappedName) + " as "+ name);
LOG.debug("Bound " + (mappedName == null ? name : mappedName) + " as " + name);
// Make the Injection for it
injection = new Injection();
injection.setTarget(clazz, method,paramType,resourceType);
injection.setTarget(clazz, method, paramType, resourceType);
injection.setJndiName(name);
injection.setMappingName(mappedName);
injections.add(injection);
//TODO - an @Resource is equivalent to a resource-ref, resource-env-ref, message-destination
metaData.setOrigin("resource-ref."+name+".injection",resource,clazz);
metaData.setOrigin("resource-ref." + name + ".injection", resource, clazz);
}
else if (!isEnvEntryType(paramType))
{
@ -352,7 +353,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
//if this is an env-entry type resource and there is no value bound for it, it isn't
//an error, it just means that perhaps the code will use a default value instead
// JavaEE Spec. sec 5.4.1.3
throw new IllegalStateException("No resource at "+(mappedName==null?name:mappedName));
throw new IllegalStateException("No resource at " + (mappedName == null ? name : mappedName));
}
}
catch (NamingException e)
@ -364,7 +365,6 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
throw new IllegalStateException(e);
}
}
}
}
@ -374,7 +374,7 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
* @param c the class
* @return true if Resource annotation permitted, false otherwise
*/
public boolean supportsResourceInjection (Class<?> c)
public boolean supportsResourceInjection(Class<?> c)
{
if (javax.servlet.Servlet.class.isAssignableFrom(c) ||
javax.servlet.Filter.class.isAssignableFrom(c) ||
@ -392,14 +392,14 @@ public class ResourceAnnotationHandler extends AbstractIntrospectableAnnotationH
return false;
}
/**
* Check if the class is one of the basic java types permitted as
* env-entries.
*
* @param clazz the class to check
* @return true if class is permitted by the spec to be an env-entry value
*/
public boolean isEnvEntryType (Class<?> clazz)
public boolean isEnvEntryType(Class<?> clazz)
{
return ENV_ENTRY_TYPES.contains(clazz);
}

View File

@ -31,35 +31,34 @@ public class ResourcesAnnotationHandler extends AbstractIntrospectableAnnotation
{
private static final Logger LOG = Log.getLogger(ResourcesAnnotationHandler.class);
protected WebAppContext _wac;
public ResourcesAnnotationHandler (WebAppContext wac)
public ResourcesAnnotationHandler(WebAppContext wac)
{
super(true);
_wac = wac;
}
@Override
public void doHandle (Class<?> clazz)
public void doHandle(Class<?> clazz)
{
Resources resources = (Resources)clazz.getAnnotation(Resources.class);
if (resources != null)
{
Resource[] resArray = resources.value();
if (resArray==null||resArray.length==0)
if (resArray == null || resArray.length == 0)
{
LOG.warn ("Skipping empty or incorrect Resources annotation on "+clazz.getName());
LOG.warn("Skipping empty or incorrect Resources annotation on " + clazz.getName());
return;
}
for (int j=0;j<resArray.length;j++)
for (int j = 0; j < resArray.length; j++)
{
String name = resArray[j].name();
String mappedName = resArray[j].mappedName();
if (name==null || name.trim().equals(""))
throw new IllegalStateException ("Class level Resource annotations must contain a name (Common Annotations Spec Section 2.3)");
if (name == null || name.trim().equals(""))
throw new IllegalStateException("Class level Resource annotations must contain a name (Common Annotations Spec Section 2.3)");
try
{
@ -67,7 +66,7 @@ public class ResourcesAnnotationHandler extends AbstractIntrospectableAnnotation
if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_wac, name, mappedName))
if (!org.eclipse.jetty.plus.jndi.NamingEntryUtil.bindToENC(_wac.getServer(), name, mappedName))
LOG.warn("Skipping Resources(Resource) annotation on "+clazz.getName()+" for name "+name+": No resource bound at "+(mappedName==null?name:mappedName));
LOG.warn("Skipping Resources(Resource) annotation on " + clazz.getName() + " for name " + name + ": No resource bound at " + (mappedName == null ? name : mappedName));
}
catch (NamingException e)
{
@ -76,5 +75,4 @@ public class ResourcesAnnotationHandler extends AbstractIntrospectableAnnotation
}
}
}
}

View File

@ -29,14 +29,13 @@ import org.eclipse.jetty.webapp.Descriptor;
import org.eclipse.jetty.webapp.MetaData;
import org.eclipse.jetty.webapp.WebAppContext;
public class RunAsAnnotationHandler extends AbstractIntrospectableAnnotationHandler
{
private static final Logger LOG = Log.getLogger(RunAsAnnotationHandler.class);
protected WebAppContext _context;
public RunAsAnnotationHandler (WebAppContext wac)
public RunAsAnnotationHandler(WebAppContext wac)
{
//Introspect only the given class for a RunAs annotation, as it is a class level annotation,
//and according to Common Annotation Spec p2-6 a class-level annotation is not inheritable.
@ -45,7 +44,7 @@ public class RunAsAnnotationHandler extends AbstractIntrospectableAnnotationHand
}
@Override
public void doHandle (Class clazz)
public void doHandle(Class clazz)
{
if (!Servlet.class.isAssignableFrom(clazz))
return;
@ -59,12 +58,12 @@ public class RunAsAnnotationHandler extends AbstractIntrospectableAnnotationHand
for (ServletHolder holder : _context.getServletHandler().getServlets(clazz))
{
MetaData metaData = _context.getMetaData();
Descriptor d = metaData.getOriginDescriptor(holder.getName()+".servlet.run-as");
Descriptor d = metaData.getOriginDescriptor(holder.getName() + ".servlet.run-as");
//if a descriptor has already set the value for run-as, do not
//let the annotation override it
if (d == null)
{
metaData.setOrigin(holder.getName()+".servlet.run-as",runAs,clazz);
metaData.setOrigin(holder.getName() + ".servlet.run-as", runAs, clazz);
org.eclipse.jetty.plus.annotation.RunAs ra = new org.eclipse.jetty.plus.annotation.RunAs();
ra.setTargetClassName(clazz.getCanonicalName());
ra.setRoleName(role);
@ -79,17 +78,17 @@ public class RunAsAnnotationHandler extends AbstractIntrospectableAnnotationHand
}
}
else
LOG.warn("Bad value for @RunAs annotation on class "+clazz.getName());
LOG.warn("Bad value for @RunAs annotation on class " + clazz.getName());
}
}
public void handleField(String className, String fieldName, int access, String fieldType, String signature, Object value, String annotation)
{
LOG.warn ("@RunAs annotation not applicable for fields: "+className+"."+fieldName);
LOG.warn("@RunAs annotation not applicable for fields: " + className + "." + fieldName);
}
public void handleMethod(String className, String methodName, int access, String params, String signature, String[] exceptions, String annotation)
{
LOG.warn("@RunAs annotation ignored on method: "+className+"."+methodName+" "+signature);
LOG.warn("@RunAs annotation ignored on method: " + className + "." + methodName + " " + signature);
}
}

View File

@ -27,7 +27,6 @@ import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.webapp.WebAppContext;
/**
* ServletContainerInitializersStarter
*
@ -46,6 +45,7 @@ public class ServletContainerInitializersStarter extends AbstractLifeCycle imple
/**
* Call the doStart method of the ServletContainerInitializers
*
* @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart()
*/
@Override
@ -60,7 +60,7 @@ public class ServletContainerInitializersStarter extends AbstractLifeCycle imple
try
{
if (LOG.isDebugEnabled())
LOG.debug("Calling ServletContainerInitializer "+i.getTarget().getClass().getName());
LOG.debug("Calling ServletContainerInitializer " + i.getTarget().getClass().getName());
i.callStartup(_context);
}
catch (Exception e)

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.annotations;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletSecurityElement;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.ServletSecurity.EmptyRoleSemantic;
@ -90,7 +89,7 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno
if (constraintsExist(servletMappings, constraintMappings))
{
LOG.warn("Constraints already defined for "+clazz.getName()+", skipping ServletSecurity annotation");
LOG.warn("Constraints already defined for " + clazz.getName() + ", skipping ServletSecurity annotation");
return;
}
@ -102,7 +101,7 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno
{
for (String url : sm.getPathSpecs())
{
_context.getMetaData().setOrigin("constraint.url."+url,servletSecurity,clazz);
_context.getMetaData().setOrigin("constraint.url." + url, servletSecurity, clazz);
constraintMappings.addAll(ConstraintSecurityHandler.createConstraintsWithMappingsForPath(clazz.getName(), url, securityElement));
}
}
@ -110,15 +109,15 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno
//set up the security constraints produced by the annotation
ConstraintAware securityHandler = (ConstraintAware)_context.getSecurityHandler();
for (ConstraintMapping m:constraintMappings)
for (ConstraintMapping m : constraintMappings)
{
securityHandler.addConstraintMapping(m);
}
//Servlet Spec 3.1 requires paths with uncovered http methods to be reported
securityHandler.checkPathsWithUncoveredHttpMethods();
}
/**
* Make a jetty Constraint object, which represents the <code>&lt;auth-constraint&gt;</code> and
* <code>&lt;user-data-constraint&gt;</code> elements, based on the security annotation.
@ -129,15 +128,14 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno
* @param transport the transport guarantee
* @return the constraint
*/
protected Constraint makeConstraint (Class servlet, String[] rolesAllowed, EmptyRoleSemantic permitOrDeny, TransportGuarantee transport)
protected Constraint makeConstraint(Class servlet, String[] rolesAllowed, EmptyRoleSemantic permitOrDeny, TransportGuarantee transport)
{
return ConstraintSecurityHandler.createConstraint(servlet.getName(), rolesAllowed, permitOrDeny, transport);
}
/**
* Get the ServletMappings for the servlet's class.
*
* @param className the class name
* @return the servlet mappings for the class
*/
@ -155,8 +153,6 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno
return results;
}
/**
* Check if there are already <code>&lt;security-constraint&gt;</code> elements defined that match the url-patterns for
* the servlet.
@ -165,7 +161,7 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno
* @param constraintMappings the constraint mappings
* @return true if constraint exists
*/
protected boolean constraintsExist (List<ServletMapping> servletMappings, List<ConstraintMapping> constraintMappings)
protected boolean constraintsExist(List<ServletMapping> servletMappings, List<ConstraintMapping> constraintMappings)
{
boolean exists = false;
@ -181,9 +177,9 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno
//Check through the constraints to see if there are any whose pathSpecs (url mappings)
//match the servlet. If so, then we already have constraints defined for this servlet,
//and we will not be processing the annotation (ie web.xml or programmatic override).
for (int i=0; constraintMappings != null && i < constraintMappings.size() && !exists; i++)
for (int i = 0; constraintMappings != null && i < constraintMappings.size() && !exists; i++)
{
for (int j=0; j < pathSpecs.length; j++)
for (int j = 0; j < pathSpecs.length; j++)
{
//TODO decide if we need to check the origin
if (pathSpecs[j].equals(constraintMappings.get(i).getPathSpec()))
@ -196,5 +192,4 @@ public class ServletSecurityAnnotationHandler extends AbstractIntrospectableAnno
}
return exists;
}
}

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.annotations;
import java.util.ArrayList;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
@ -66,15 +65,14 @@ public class WebFilterAnnotation extends DiscoveredAnnotation
Class clazz = getTargetClass();
if (clazz == null)
{
LOG.warn(_className+" cannot be loaded");
LOG.warn(_className + " cannot be loaded");
return;
}
//Servlet Spec 8.1.2
if (!Filter.class.isAssignableFrom(clazz))
{
LOG.warn(clazz.getName()+" is not assignable from javax.servlet.Filter");
LOG.warn(clazz.getName() + " is not assignable from javax.servlet.Filter");
return;
}
MetaData metaData = _context.getMetaData();
@ -83,11 +81,11 @@ public class WebFilterAnnotation extends DiscoveredAnnotation
if (filterAnnotation.value().length > 0 && filterAnnotation.urlPatterns().length > 0)
{
LOG.warn(clazz.getName()+" defines both @WebFilter.value and @WebFilter.urlPatterns");
LOG.warn(clazz.getName() + " defines both @WebFilter.value and @WebFilter.urlPatterns");
return;
}
String name = (filterAnnotation.filterName().equals("")?clazz.getName():filterAnnotation.filterName());
String name = (filterAnnotation.filterName().equals("") ? clazz.getName() : filterAnnotation.filterName());
String[] urlPatterns = filterAnnotation.value();
if (urlPatterns.length == 0)
urlPatterns = filterAnnotation.urlPatterns();
@ -96,19 +94,19 @@ public class WebFilterAnnotation extends DiscoveredAnnotation
if (holder == null)
{
//Filter with this name does not already exist, so add it
holder = _context.getServletHandler().newFilterHolder(new Source (Source.Origin.ANNOTATION, clazz.getName()));
holder = _context.getServletHandler().newFilterHolder(new Source(Source.Origin.ANNOTATION, clazz.getName()));
holder.setName(name);
holder.setHeldClass(clazz);
metaData.setOrigin(name+".filter.filter-class",filterAnnotation,clazz);
metaData.setOrigin(name + ".filter.filter-class", filterAnnotation, clazz);
holder.setDisplayName(filterAnnotation.displayName());
metaData.setOrigin(name+".filter.display-name",filterAnnotation,clazz);
metaData.setOrigin(name + ".filter.display-name", filterAnnotation, clazz);
for (WebInitParam ip: filterAnnotation.initParams())
for (WebInitParam ip : filterAnnotation.initParams())
{
holder.setInitParameter(ip.name(), ip.value());
metaData.setOrigin(name+".filter.init-param."+ip.name(),ip,clazz);
metaData.setOrigin(name + ".filter.init-param." + ip.name(), ip, clazz);
}
FilterMapping mapping = new FilterMapping();
@ -117,7 +115,7 @@ public class WebFilterAnnotation extends DiscoveredAnnotation
if (urlPatterns.length > 0)
{
ArrayList<String> paths = new ArrayList<String>();
for (String s:urlPatterns)
for (String s : urlPatterns)
{
paths.add(ServletPathSpec.normalize(s));
}
@ -140,10 +138,10 @@ public class WebFilterAnnotation extends DiscoveredAnnotation
dispatcherSet.add(d);
}
mapping.setDispatcherTypes(dispatcherSet);
metaData.setOrigin(name+".filter.mappings",filterAnnotation,clazz);
metaData.setOrigin(name + ".filter.mappings", filterAnnotation, clazz);
holder.setAsyncSupported(filterAnnotation.asyncSupported());
metaData.setOrigin(name+".filter.async-supported",filterAnnotation,clazz);
metaData.setOrigin(name + ".filter.async-supported", filterAnnotation, clazz);
_context.getServletHandler().addFilter(holder);
_context.getServletHandler().addFilterMapping(mapping);
@ -155,13 +153,13 @@ public class WebFilterAnnotation extends DiscoveredAnnotation
//they override the annotation. If it already has DispatcherType set, that
//also overrides the annotation. Init-params are additive, but web.xml overrides
//init-params of the same name.
for (WebInitParam ip: filterAnnotation.initParams())
for (WebInitParam ip : filterAnnotation.initParams())
{
//if (holder.getInitParameter(ip.name()) == null)
if (metaData.getOrigin(name+".filter.init-param."+ip.name())==Origin.NotSet)
if (metaData.getOrigin(name + ".filter.init-param." + ip.name()) == Origin.NotSet)
{
holder.setInitParameter(ip.name(), ip.value());
metaData.setOrigin(name+".filter.init-param."+ip.name(),ip,clazz);
metaData.setOrigin(name + ".filter.init-param." + ip.name(), ip, clazz);
}
}
@ -169,7 +167,7 @@ public class WebFilterAnnotation extends DiscoveredAnnotation
boolean mappingExists = false;
if (mappings != null)
{
for (FilterMapping m:mappings)
for (FilterMapping m : mappings)
{
if (m.getFilterName().equals(name))
{
@ -188,7 +186,7 @@ public class WebFilterAnnotation extends DiscoveredAnnotation
if (urlPatterns.length > 0)
{
ArrayList<String> paths = new ArrayList<String>();
for (String s:urlPatterns)
for (String s : urlPatterns)
{
paths.add(ServletPathSpec.normalize(s));
}
@ -211,9 +209,8 @@ public class WebFilterAnnotation extends DiscoveredAnnotation
}
mapping.setDispatcherTypes(dispatcherSet);
_context.getServletHandler().addFilterMapping(mapping);
metaData.setOrigin(name+".filter.mappings",filterAnnotation,clazz);
metaData.setOrigin(name + ".filter.mappings", filterAnnotation, clazz);
}
}
}
}

View File

@ -27,19 +27,16 @@ import org.eclipse.jetty.webapp.WebAppContext;
/**
* WebFilterAnnotationHandler
*
*
*/
public class WebFilterAnnotationHandler extends AbstractDiscoverableAnnotationHandler
{
private static final Logger LOG = Log.getLogger(WebFilterAnnotationHandler.class);
public WebFilterAnnotationHandler (WebAppContext context)
public WebFilterAnnotationHandler(WebAppContext context)
{
super(context);
}
@Override
public void handle(ClassInfo info, String annotationName)
{
@ -55,7 +52,7 @@ public class WebFilterAnnotationHandler extends AbstractDiscoverableAnnotationHa
{
if (annotationName == null || !"javax.servlet.annotation.WebFilter".equals(annotationName))
return;
LOG.warn ("@WebFilter not applicable for fields: "+info.getClassInfo().getClassName()+"."+info.getFieldName());
LOG.warn("@WebFilter not applicable for fields: " + info.getClassInfo().getClassName() + "." + info.getFieldName());
}
@Override
@ -63,6 +60,6 @@ public class WebFilterAnnotationHandler extends AbstractDiscoverableAnnotationHa
{
if (annotationName == null || !"javax.servlet.annotation.WebFilter".equals(annotationName))
return;
LOG.warn ("@WebFilter not applicable for methods: "+info.getClassInfo().getClassName()+"."+info.getMethodName()+" "+info.getSignature());
LOG.warn("@WebFilter not applicable for methods: " + info.getClassInfo().getClassName() + "." + info.getMethodName() + " " + info.getSignature());
}
}

View File

@ -19,7 +19,6 @@
package org.eclipse.jetty.annotations;
import java.util.EventListener;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestAttributeListener;
@ -65,7 +64,7 @@ public class WebListenerAnnotation extends DiscoveredAnnotation
if (clazz == null)
{
LOG.warn(_className+" cannot be loaded");
LOG.warn(_className + " cannot be loaded");
return;
}
@ -80,7 +79,7 @@ public class WebListenerAnnotation extends DiscoveredAnnotation
HttpSessionIdListener.class.isAssignableFrom(clazz))
{
MetaData metaData = _context.getMetaData();
if (metaData.getOrigin(clazz.getName()+".listener") == Origin.NotSet)
if (metaData.getOrigin(clazz.getName() + ".listener") == Origin.NotSet)
{
ListenerHolder h = _context.getServletHandler().newListenerHolder(new Source(Source.Origin.ANNOTATION, clazz.getName()));
h.setHeldClass(clazz);
@ -88,7 +87,7 @@ public class WebListenerAnnotation extends DiscoveredAnnotation
}
}
else
LOG.warn(clazz.getName()+" does not implement one of the servlet listener interfaces");
LOG.warn(clazz.getName() + " does not implement one of the servlet listener interfaces");
}
catch (Exception e)
{

View File

@ -29,7 +29,7 @@ public class WebListenerAnnotationHandler extends AbstractDiscoverableAnnotation
{
private static final Logger LOG = Log.getLogger(WebListenerAnnotationHandler.class);
public WebListenerAnnotationHandler (WebAppContext context)
public WebListenerAnnotationHandler(WebAppContext context)
{
super(context);
}
@ -49,7 +49,7 @@ public class WebListenerAnnotationHandler extends AbstractDiscoverableAnnotation
{
if (annotationName == null || !"javax.servlet.annotation.WebListener".equals(annotationName))
return;
LOG.warn ("@WebListener is not applicable to fields: "+info.getClassInfo().getClassName()+"."+info.getFieldName());
LOG.warn("@WebListener is not applicable to fields: " + info.getClassInfo().getClassName() + "." + info.getFieldName());
}
@Override
@ -57,6 +57,6 @@ public class WebListenerAnnotationHandler extends AbstractDiscoverableAnnotation
{
if (annotationName == null || !"javax.servlet.annotation.WebListener".equals(annotationName))
return;
LOG.warn ("@WebListener is not applicable to methods: "+info.getClassInfo().getClassName()+"."+info.getMethodName()+" "+info.getSignature());
LOG.warn("@WebListener is not applicable to methods: " + info.getClassInfo().getClassName() + "." + info.getMethodName() + " " + info.getSignature());
}
}

View File

@ -21,14 +21,12 @@ package org.eclipse.jetty.annotations;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.Servlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import org.eclipse.jetty.http.pathmap.ServletPathSpec;
import org.eclipse.jetty.servlet.Holder;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.ServletMapping;
import org.eclipse.jetty.servlet.Source;
@ -44,20 +42,17 @@ import org.eclipse.jetty.webapp.WebAppContext;
/**
* WebServletAnnotation
*
*
*/
public class WebServletAnnotation extends DiscoveredAnnotation
{
private static final Logger LOG = Log.getLogger(WebServletAnnotation.class);
public WebServletAnnotation (WebAppContext context, String className)
public WebServletAnnotation(WebAppContext context, String className)
{
super(context, className);
}
public WebServletAnnotation (WebAppContext context, String className, Resource resource)
public WebServletAnnotation(WebAppContext context, String className, Resource resource)
{
super(context, className, resource);
}
@ -73,14 +68,14 @@ public class WebServletAnnotation extends DiscoveredAnnotation
if (clazz == null)
{
LOG.warn(_className+" cannot be loaded");
LOG.warn(_className + " cannot be loaded");
return;
}
//Servlet Spec 8.1.1
if (!HttpServlet.class.isAssignableFrom(clazz))
{
LOG.warn(clazz.getName()+" is not assignable from javax.servlet.http.HttpServlet");
LOG.warn(clazz.getName() + " is not assignable from javax.servlet.http.HttpServlet");
return;
}
@ -88,7 +83,7 @@ public class WebServletAnnotation extends DiscoveredAnnotation
if (annotation.urlPatterns().length > 0 && annotation.value().length > 0)
{
LOG.warn(clazz.getName()+ " defines both @WebServlet.value and @WebServlet.urlPatterns");
LOG.warn(clazz.getName() + " defines both @WebServlet.value and @WebServlet.urlPatterns");
return;
}
@ -98,16 +93,18 @@ public class WebServletAnnotation extends DiscoveredAnnotation
if (urlPatterns.length == 0)
{
LOG.warn(clazz.getName()+ " defines neither @WebServlet.value nor @WebServlet.urlPatterns");
LOG.warn(clazz.getName() + " defines neither @WebServlet.value nor @WebServlet.urlPatterns");
return;
}
//canonicalize the patterns
ArrayList<String> urlPatternList = new ArrayList<String>();
for (String p : urlPatterns)
{
urlPatternList.add(ServletPathSpec.normalize(p));
}
String servletName = (annotation.name().equals("")?clazz.getName():annotation.name());
String servletName = (annotation.name().equals("") ? clazz.getName() : annotation.name());
MetaData metaData = _context.getMetaData();
ServletMapping mapping = null; //the new mapping
@ -137,30 +134,29 @@ public class WebServletAnnotation extends DiscoveredAnnotation
holder = _context.getServletHandler().newServletHolder(source);
holder.setHeldClass(clazz);
metaData.setOrigin(servletName+".servlet.servlet-class",annotation,clazz);
metaData.setOrigin(servletName + ".servlet.servlet-class", annotation, clazz);
holder.setName(servletName);
holder.setDisplayName(annotation.displayName());
metaData.setOrigin(servletName+".servlet.display-name",annotation,clazz);
metaData.setOrigin(servletName + ".servlet.display-name", annotation, clazz);
holder.setInitOrder(annotation.loadOnStartup());
metaData.setOrigin(servletName+".servlet.load-on-startup",annotation,clazz);
metaData.setOrigin(servletName + ".servlet.load-on-startup", annotation, clazz);
holder.setAsyncSupported(annotation.asyncSupported());
metaData.setOrigin(servletName+".servlet.async-supported",annotation,clazz);
metaData.setOrigin(servletName + ".servlet.async-supported", annotation, clazz);
for (WebInitParam ip:annotation.initParams())
for (WebInitParam ip : annotation.initParams())
{
holder.setInitParameter(ip.name(), ip.value());
metaData.setOrigin(servletName+".servlet.init-param."+ip.name(),ip,clazz);
metaData.setOrigin(servletName + ".servlet.init-param." + ip.name(), ip, clazz);
}
_context.getServletHandler().addServlet(holder);
mapping = new ServletMapping(source);
mapping.setServletName(holder.getName());
mapping.setPathSpecs( LazyList.toStringArray(urlPatternList));
mapping.setPathSpecs(LazyList.toStringArray(urlPatternList));
}
else
{
@ -175,16 +171,15 @@ public class WebServletAnnotation extends DiscoveredAnnotation
//check if the existing servlet has each init-param from the annotation
//if not, add it
for (WebInitParam ip:annotation.initParams())
for (WebInitParam ip : annotation.initParams())
{
if (metaData.getOrigin(servletName+".servlet.init-param."+ip.name())==Origin.NotSet)
if (metaData.getOrigin(servletName + ".servlet.init-param." + ip.name()) == Origin.NotSet)
{
holder.setInitParameter(ip.name(), ip.value());
metaData.setOrigin(servletName+".servlet.init-param."+ip.name(),ip,clazz);
metaData.setOrigin(servletName + ".servlet.init-param." + ip.name(), ip, clazz);
}
}
//check the url-patterns
//ServletSpec 3.0 p81 If a servlet already has url mappings from a
//webxml or fragment descriptor the annotation is ignored.
@ -201,7 +196,6 @@ public class WebServletAnnotation extends DiscoveredAnnotation
}
}
//We also want to be able to replace mappings that were defined in webdefault.xml
//that were for a different servlet eg a mapping in webdefault.xml for / to the jetty
//default servlet should be able to be replaced by an annotation for / to a different
@ -217,7 +211,7 @@ public class WebServletAnnotation extends DiscoveredAnnotation
//for each of the urls in the annotation, check if a mapping to same/different servlet exists
// if mapping exists and is from a default descriptor, it can be replaced. NOTE: we do not
// guard against duplicate path mapping here: that is the job of the ServletHandler
for (String p:urlPatternList)
for (String p : urlPatternList)
{
ServletMapping existingMapping = _context.getServletHandler().getServletMapping(p);
if (existingMapping != null && existingMapping.isDefault())
@ -227,36 +221,34 @@ public class WebServletAnnotation extends DiscoveredAnnotation
if (updatedPaths == null || updatedPaths.length == 0)
{
boolean success = allMappings.remove(existingMapping);
if (LOG.isDebugEnabled()) LOG.debug("Removed empty mapping {} from defaults descriptor success:{}",existingMapping, success);
if (LOG.isDebugEnabled())
LOG.debug("Removed empty mapping {} from defaults descriptor success:{}", existingMapping, success);
}
else
{
existingMapping.setPathSpecs(updatedPaths);
if (LOG.isDebugEnabled()) LOG.debug("Removed path {} from mapping {} from defaults descriptor ", p,existingMapping);
if (LOG.isDebugEnabled())
LOG.debug("Removed path {} from mapping {} from defaults descriptor ", p, existingMapping);
}
}
_context.getMetaData().setOrigin(servletName+".servlet.mapping."+p, annotation, clazz);
_context.getMetaData().setOrigin(servletName + ".servlet.mapping." + p, annotation, clazz);
}
allMappings.add(mapping);
_context.getServletHandler().setServletMappings(allMappings.toArray(new ServletMapping[allMappings.size()]));
}
}
/**
* @param name
* @return
*
*/
private List<ServletMapping> getServletMappingsForServlet (String name)
private List<ServletMapping> getServletMappingsForServlet(String name)
{
ServletMapping[] allMappings = _context.getServletHandler().getServletMappings();
if (allMappings == null)
return Collections.emptyList();
List<ServletMapping> mappings = new ArrayList<ServletMapping>();
for (ServletMapping m:allMappings)
for (ServletMapping m : allMappings)
{
if (m.getServletName() != null && name.equals(m.getServletName()))
{
@ -266,16 +258,14 @@ public class WebServletAnnotation extends DiscoveredAnnotation
return mappings;
}
/**
* @param mappings
* @return
*
*/
private boolean containsNonDefaultMappings (List<ServletMapping> mappings)
private boolean containsNonDefaultMappings(List<ServletMapping> mappings)
{
if (mappings == null)
return false;
for (ServletMapping m:mappings)
for (ServletMapping m : mappings)
{
if (!m.isDefault())
return true;

View File

@ -34,12 +34,11 @@ public class WebServletAnnotationHandler extends AbstractDiscoverableAnnotationH
{
private static final Logger LOG = Log.getLogger(WebServletAnnotationHandler.class);
public WebServletAnnotationHandler (WebAppContext context)
public WebServletAnnotationHandler(WebAppContext context)
{
super(context);
}
/**
* Handle discovering a WebServlet annotation.
*/
@ -49,7 +48,7 @@ public class WebServletAnnotationHandler extends AbstractDiscoverableAnnotationH
if (annotationName == null || !"javax.servlet.annotation.WebServlet".equals(annotationName))
return;
WebServletAnnotation annotation = new WebServletAnnotation (_context, info.getClassName(), info.getContainingResource());
WebServletAnnotation annotation = new WebServletAnnotation(_context, info.getClassName(), info.getContainingResource());
addAnnotation(annotation);
}
@ -59,7 +58,7 @@ public class WebServletAnnotationHandler extends AbstractDiscoverableAnnotationH
if (annotationName == null || !"javax.servlet.annotation.WebServlet".equals(annotationName))
return;
LOG.warn ("@WebServlet annotation not supported for fields");
LOG.warn("@WebServlet annotation not supported for fields");
}
@Override
@ -68,6 +67,6 @@ public class WebServletAnnotationHandler extends AbstractDiscoverableAnnotationH
if (annotationName == null || !"javax.servlet.annotation.WebServlet".equals(annotationName))
return;
LOG.warn ("@WebServlet annotation not supported for methods");
LOG.warn("@WebServlet annotation not supported for methods");
}
}

View File

@ -17,13 +17,8 @@ package org.acme;
// ========================================================================
//
/**
* ClassOne
*
*
*/
public class ClassOne
{
@ -31,5 +26,4 @@ public class ClassOne
public void one()
{
}
}

View File

@ -18,11 +18,8 @@
package org.eclipse.jetty.annotations;
/**
* ClassA
*
*
*/
@Sample(1)
public class ClassA
@ -34,7 +31,6 @@ public class ClassA
private Integer j;
private Integer k;
public static class Foo
{
@ -44,7 +40,7 @@ public class ClassA
private Integer m;
@Sample(2)
public void a (Integer[] x)
public void a(Integer[] x)
{
System.err.println("ClassA.public");
}

Some files were not shown because too many files have changed in this diff Show More