use of javax.servlet.Servlet in project tomcat by apache.
the class TestContextConfigAnnotation method testCheckHandleTypes.
@Test
public void testCheckHandleTypes() throws Exception {
Map<String, JavaClassCacheEntry> javaClassCache = new HashMap<>();
ContextConfig config = new ContextConfig();
config.handlesTypesAnnotations = true;
config.handlesTypesNonAnnotations = true;
// Need a Context, Loader and ClassLoader for checkHandleTypes
StandardContext context = new StandardContext();
context.setLoader(new TesterLoader());
config.context = context;
// Add an SCI that has no interest in any type
SCI sciNone = new SCI();
config.initializerClassMap.put(sciNone, new HashSet<Class<?>>());
// Add an SCI with an interest in Servlets
SCI sciServlet = new SCI();
config.initializerClassMap.put(sciServlet, new HashSet<Class<?>>());
config.typeInitializerMap.put(Servlet.class, new HashSet<ServletContainerInitializer>());
config.typeInitializerMap.get(Servlet.class).add(sciServlet);
// Add an SCI with an interest in Objects - i.e. everything
SCI sciObject = new SCI();
config.initializerClassMap.put(sciObject, new HashSet<Class<?>>());
config.typeInitializerMap.put(Object.class, new HashSet<ServletContainerInitializer>());
config.typeInitializerMap.get(Object.class).add(sciObject);
// Scan Servlet, Filter, Servlet, Listener
WebXml ignore = new WebXml();
File file = paramClassResource("org/apache/catalina/startup/ParamServlet");
config.processAnnotationsFile(file, ignore, false, javaClassCache);
file = paramClassResource("org/apache/catalina/startup/ParamFilter");
config.processAnnotationsFile(file, ignore, false, javaClassCache);
file = paramClassResource("org/apache/catalina/startup/TesterServlet");
config.processAnnotationsFile(file, ignore, false, javaClassCache);
file = paramClassResource("org/apache/catalina/startup/TestListener");
config.processAnnotationsFile(file, ignore, false, javaClassCache);
// Check right number of classes were noted to be handled
assertEquals(0, config.initializerClassMap.get(sciNone).size());
assertEquals(2, config.initializerClassMap.get(sciServlet).size());
assertEquals(4, config.initializerClassMap.get(sciObject).size());
}
use of javax.servlet.Servlet in project tomcat by apache.
the class ApplicationDispatcher method invoke.
// -------------------------------------------------------- Private Methods
/**
* Ask the resource represented by this RequestDispatcher to process
* the associated request, and create (or append to) the associated
* response.
* <p>
* <strong>IMPLEMENTATION NOTE</strong>: This implementation assumes
* that no filters are applied to a forwarded or included resource,
* because they were already done for the original request.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
private void invoke(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException {
// Checking to see if the context classloader is the current context
// classloader. If it's not, we're saving it, and setting the context
// classloader to the Context classloader
ClassLoader oldCCL = context.bind(false, null);
// Initialize local variables we may need
HttpServletResponse hresponse = state.hresponse;
Servlet servlet = null;
IOException ioException = null;
ServletException servletException = null;
RuntimeException runtimeException = null;
boolean unavailable = false;
// Check for the servlet being marked unavailable
if (wrapper.isUnavailable()) {
wrapper.getLogger().warn(sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
long available = wrapper.getAvailable();
if ((available > 0L) && (available < Long.MAX_VALUE))
hresponse.setDateHeader("Retry-After", available);
hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
unavailable = true;
}
// Allocate a servlet instance to process this request
try {
if (!unavailable) {
servlet = wrapper.allocate();
}
} catch (ServletException e) {
wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e));
servletException = e;
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
servletException = new ServletException(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
servlet = null;
}
// Get the FilterChain Here
ApplicationFilterChain filterChain = ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);
// Call the service() method for the allocated servlet instance
try {
// for includes/forwards
if ((servlet != null) && (filterChain != null)) {
filterChain.doFilter(request, response);
}
// Servlet Service Method is called by the FilterChain
} catch (ClientAbortException e) {
ioException = e;
} catch (IOException e) {
wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
ioException = e;
} catch (UnavailableException e) {
wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
servletException = e;
wrapper.unavailable(e);
} catch (ServletException e) {
Throwable rootCause = StandardWrapper.getRootCause(e);
if (!(rootCause instanceof ClientAbortException)) {
wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause);
}
servletException = e;
} catch (RuntimeException e) {
wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
runtimeException = e;
}
// Release the filter chain (if any) for this request
try {
if (filterChain != null)
filterChain.release();
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e);
// FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue
}
// Deallocate the allocated servlet instance
try {
if (servlet != null) {
wrapper.deallocate(servlet);
}
} catch (ServletException e) {
wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
servletException = e;
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
servletException = new ServletException(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
}
// Reset the old context class loader
context.unbind(false, oldCCL);
// Unwrap request/response if needed
// See Bugzilla 30949
unwrapRequest(state);
unwrapResponse(state);
// Recycle request if necessary (also BZ 30949)
recycleRequestWrapper(state);
// Rethrow an exception if one was thrown by the invoked servlet
if (ioException != null)
throw ioException;
if (servletException != null)
throw servletException;
if (runtimeException != null)
throw runtimeException;
}
use of javax.servlet.Servlet in project tomcat by apache.
the class JspServletWrapper method service.
public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException {
Servlet servlet;
try {
if (ctxt.isRemoved()) {
throw new FileNotFoundException(jspUri);
}
if ((available > 0L) && (available < Long.MAX_VALUE)) {
if (available > System.currentTimeMillis()) {
response.setDateHeader("Retry-After", available);
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable"));
return;
}
// Wait period has expired. Reset.
available = 0;
}
/*
* (1) Compile
*/
if (options.getDevelopment() || firstTime) {
synchronized (this) {
firstTime = false;
// The following sets reload to true, if necessary
ctxt.compile();
}
} else {
if (compileException != null) {
// Throw cached compilation exception
throw compileException;
}
}
/*
* (2) (Re)load servlet class file
*/
servlet = getServlet();
// If a page is to be precompiled only, return.
if (precompile) {
return;
}
} catch (ServletException ex) {
if (options.getDevelopment()) {
throw handleJspException(ex);
}
throw ex;
} catch (FileNotFoundException fnfe) {
// File has been removed. Let caller handle this.
throw fnfe;
} catch (IOException ex) {
if (options.getDevelopment()) {
throw handleJspException(ex);
}
throw ex;
} catch (IllegalStateException ex) {
if (options.getDevelopment()) {
throw handleJspException(ex);
}
throw ex;
} catch (Exception ex) {
if (options.getDevelopment()) {
throw handleJspException(ex);
}
throw new JasperException(ex);
}
try {
/*
* (3) Handle limitation of number of loaded Jsps
*/
if (unloadAllowed) {
synchronized (this) {
if (unloadByCount) {
if (unloadHandle == null) {
unloadHandle = ctxt.getRuntimeContext().push(this);
} else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) {
ctxt.getRuntimeContext().makeYoungest(unloadHandle);
lastUsageTime = System.currentTimeMillis();
}
} else {
if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) {
lastUsageTime = System.currentTimeMillis();
}
}
}
}
/*
* (4) Service request
*/
if (servlet instanceof SingleThreadModel) {
// of the page is determined right before servicing
synchronized (this) {
servlet.service(request, response);
}
} else {
servlet.service(request, response);
}
} catch (UnavailableException ex) {
String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
if (includeRequestUri != null) {
// servlet engine.
throw ex;
}
int unavailableSeconds = ex.getUnavailableSeconds();
if (unavailableSeconds <= 0) {
// Arbitrary default
unavailableSeconds = 60;
}
available = System.currentTimeMillis() + (unavailableSeconds * 1000L);
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage());
} catch (ServletException ex) {
if (options.getDevelopment()) {
throw handleJspException(ex);
}
throw ex;
} catch (IOException ex) {
if (options.getDevelopment()) {
throw new IOException(handleJspException(ex).getMessage(), ex);
}
throw ex;
} catch (IllegalStateException ex) {
if (options.getDevelopment()) {
throw handleJspException(ex);
}
throw ex;
} catch (Exception ex) {
if (options.getDevelopment()) {
throw handleJspException(ex);
}
throw new JasperException(ex);
}
}
use of javax.servlet.Servlet in project tomcat by apache.
the class TestStandardWrapper method doTestSecurityAnnotationsAddServlet.
private void doTestSecurityAnnotationsAddServlet(boolean useCreateServlet) throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Servlet s = new DenyAllServlet();
ServletContainerInitializer sci = new SCI(s, useCreateServlet);
ctx.addServletContainerInitializer(sci, null);
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
rc = getUrl("http://localhost:" + getPort() + "/", bc, null, null);
if (useCreateServlet) {
assertTrue(bc.getLength() > 0);
assertEquals(403, rc);
} else {
assertEquals("OK", bc.toString());
assertEquals(200, rc);
}
}
use of javax.servlet.Servlet in project jetty.project by eclipse.
the class WebServletAnnotation method apply.
/**
* @see DiscoveredAnnotation#apply()
*/
public void apply() {
//TODO check this algorithm with new rules for applying descriptors and annotations in order
Class<? extends Servlet> clazz = (Class<? extends Servlet>) getTargetClass();
if (clazz == null) {
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");
return;
}
WebServlet annotation = (WebServlet) clazz.getAnnotation(WebServlet.class);
if (annotation.urlPatterns().length > 0 && annotation.value().length > 0) {
LOG.warn(clazz.getName() + " defines both @WebServlet.value and @WebServlet.urlPatterns");
return;
}
String[] urlPatterns = annotation.value();
if (urlPatterns.length == 0)
urlPatterns = annotation.urlPatterns();
if (urlPatterns.length == 0) {
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());
MetaData metaData = _context.getMetaData();
//the new mapping
ServletMapping mapping = null;
//Find out if a <servlet> already exists with this name
ServletHolder[] holders = _context.getServletHandler().getServlets();
ServletHolder holder = null;
if (holders != null) {
for (ServletHolder h : holders) {
if (h.getName() != null && servletName.equals(h.getName())) {
holder = h;
break;
}
}
}
//handle creation/completion of a servlet
if (holder == null) {
//No servlet of this name has already been defined, either by a descriptor
//or another annotation (which would be impossible).
Source source = new Source(Source.Origin.ANNOTATION, clazz.getName());
holder = _context.getServletHandler().newServletHolder(source);
holder.setHeldClass(clazz);
metaData.setOrigin(servletName + ".servlet.servlet-class", annotation, clazz);
holder.setName(servletName);
holder.setDisplayName(annotation.displayName());
metaData.setOrigin(servletName + ".servlet.display-name", annotation, clazz);
holder.setInitOrder(annotation.loadOnStartup());
metaData.setOrigin(servletName + ".servlet.load-on-startup", annotation, clazz);
holder.setAsyncSupported(annotation.asyncSupported());
metaData.setOrigin(servletName + ".servlet.async-supported", annotation, clazz);
for (WebInitParam ip : annotation.initParams()) {
holder.setInitParameter(ip.name(), ip.value());
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));
} else {
//can complete it, see http://java.net/jira/browse/SERVLET_SPEC-42
if (holder.getClassName() == null)
holder.setClassName(clazz.getName());
if (holder.getHeldClass() == null)
holder.setHeldClass(clazz);
//if not, add it
for (WebInitParam ip : annotation.initParams()) {
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);
}
}
//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.
//However, we want to be able to replace mappings that were given in webdefault.xml
List<ServletMapping> existingMappings = getServletMappingsForServlet(servletName);
//about processing these url mappings
if (existingMappings.isEmpty() || !containsNonDefaultMappings(existingMappings)) {
mapping = new ServletMapping(new Source(Source.Origin.ANNOTATION, clazz.getName()));
mapping.setServletName(servletName);
mapping.setPathSpecs(LazyList.toStringArray(urlPatternList));
}
}
//servlet
if (mapping != null) {
//url mapping was permitted by annotation processing rules
//take a copy of the existing servlet mappings that we can iterate over and remove from. This is
//because the ServletHandler interface does not support removal of individual mappings.
List<ServletMapping> allMappings = ArrayUtil.asMutableList(_context.getServletHandler().getServletMappings());
// guard against duplicate path mapping here: that is the job of the ServletHandler
for (String p : urlPatternList) {
ServletMapping existingMapping = _context.getServletHandler().getServletMapping(p);
if (existingMapping != null && existingMapping.isDefault()) {
String[] updatedPaths = ArrayUtil.removeFromArray(existingMapping.getPathSpecs(), p);
//if we removed the last path from a servletmapping, delete the servletmapping
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);
} else {
existingMapping.setPathSpecs(updatedPaths);
if (LOG.isDebugEnabled())
LOG.debug("Removed path {} from mapping {} from defaults descriptor ", p, existingMapping);
}
}
_context.getMetaData().setOrigin(servletName + ".servlet.mapping." + p, annotation, clazz);
}
allMappings.add(mapping);
_context.getServletHandler().setServletMappings(allMappings.toArray(new ServletMapping[allMappings.size()]));
}
}
Aggregations