List of usage examples for javax.servlet.http HttpServlet init
public void init(ServletConfig config) throws ServletException
From source file:com.qwazr.webapps.transaction.ControllerManager.java
private void handleJavaClass(WebappTransaction transaction, String className) throws IOException, InterruptedException, ScriptException, ReflectiveOperationException, ServletException { final Class<? extends HttpServlet> servletClass = ClassLoaderUtils.findClass(ClassLoaderManager.classLoader, className);// ww w. j av a 2 s . c o m Objects.requireNonNull(servletClass, "Class not found: " + className); final ServletInfo servletInfo = new ServletInfo(className, servletClass); servletInfo.getInstanceFactory().createInstance(); HttpServlet servlet = servletMap.getOrCreate(servletClass, new Supplier() { @Override public HttpServlet get() { try { HttpServlet servlet = servletClass.newInstance(); WebServlet webServlet = AnnotationsUtils.getFirstAnnotation(servletClass, WebServlet.class); servlet.init(new ServletConfigImpl(servletInfo, transaction.getRequest().getServletContext())); LibraryManager.inject(servlet); return servlet; } catch (InstantiationException | IllegalAccessException | ServletException e) { throw new RuntimeException(e); } } }); servlet.service(transaction.getRequest(), transaction.getResponse()); }
From source file:de.micromata.genome.tpsb.httpmockup.MockServletContext.java
public MockServletContext addServlet(final String name, final Class<? extends HttpServlet> servletClass, final Map<String, String> initParams) { try {/*from ww w .ja v a2s . co m*/ final HttpServlet servlet = servletClass.newInstance(); final MockServletConfig sc = new MockServletConfig(); sc.setServletName(name); sc.setServletContext(this); if (initParams != null) { sc.setInitParameters(initParams); } servlet.init(sc); this.servletsConfig.addServlet(name, servlet); return this; } catch (final Exception ex) { throw new RuntimeException("Exception in initializing filter: " + name + "; " + servletClass.getName() + "; " + ex.getMessage(), ex); } }
From source file:com.google.gwt.dev.shell.GWTShellServlet.java
private HttpServlet tryGetOrLoadServlet(TreeLogger logger, ModuleDef moduleDef, String className) { // Maps className to live servlet for this module. Map<String, HttpServlet> moduleServlets; synchronized (loadedServletsByModuleAndClassName) { moduleServlets = loadedServletsByModuleAndClassName.get(moduleDef); if (moduleServlets == null) { moduleServlets = new HashMap<String, HttpServlet>(); loadedServletsByModuleAndClassName.put(moduleDef, moduleServlets); }//from w ww . j a v a 2 s . co m } synchronized (moduleServlets) { HttpServlet servlet = moduleServlets.get(className); if (servlet != null) { // Found it. // return servlet; } // Try to load and instantiate it. // Throwable caught = null; try { Class<?> servletClass = Class.forName(className); Object newInstance = servletClass.newInstance(); if (!(newInstance instanceof HttpServlet)) { logger.log(TreeLogger.ERROR, "Not compatible with HttpServlet: " + className + " (does your service extend RemoteServiceServlet?)", null); return null; } // Success. Hang onto the instance so we can reuse it. // servlet = (HttpServlet) newInstance; // We create proxies for ServletContext and ServletConfig to enable // RemoteServiceServlets to load public and generated resources via // ServletContext.getResourceAsStream() // ServletContext context = new HostedModeServletContextProxy(getServletContext(), moduleDef, getShellWorkDirs()); ServletConfig config = new HostedModeServletConfigProxy(getServletConfig(), context); servlet.init(config); moduleServlets.put(className, servlet); return servlet; } catch (ClassNotFoundException e) { caught = e; } catch (InstantiationException e) { caught = e; } catch (IllegalAccessException e) { caught = e; } catch (ServletException e) { caught = e; } String msg = "Unable to instantiate '" + className + "'"; logger.log(TreeLogger.ERROR, msg, caught); return null; } }
From source file:org.j2free.invoker.InvokerFilter.java
/** * * @param req/* ww w . j a va 2 s. co m*/ * @param chain The filter chain we are processing * * @param resp * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; // Get the path after the context-path (final so we can't accidentally fuck with it) final String path = httpReq.getRequestURI().substring(httpReq.getContextPath().length()) // chop the context-path .toLowerCase(); // all comparisons in lower-case // Benchmark vars final long start = System.currentTimeMillis(); // start time long resolve = 0, // time after figuring out what to do process = 0, // time after processing finish = 0; // finish time // Set cache-control based on content if (Constants.RUN_MODE.compareTo(RunMode.PRODUCTION) == -1) // dev mode { httpResp.setHeader(HEADER_PRAGMA, "no-cache"); httpResp.setHeader(HEADER_CACHE_CONTROL, "no-store"); } else if (path.matches(SHORT_CACHE_REGEX) && !path.contains(CAPTCHA_PATH)) { httpResp.setHeader(HEADER_PRAGMA, PRAGMA_VAL); httpResp.setHeader(HEADER_CACHE_CONTROL, SHORT_CACHE_VAL); } else if (path.matches(LONG_CACHE_REGEX)) { httpResp.setHeader(HEADER_PRAGMA, PRAGMA_VAL); httpResp.setHeader(HEADER_CACHE_CONTROL, LONG_CACHE_VAL); } try { // This will block requests during configuration read.lock(); if (log.isTraceEnabled()) log.trace("InvokerFilter for path: " + path); // Try to get an explicit mapping from the whole URL to a class Class<? extends HttpServlet> klass = urlMap.get(path); // Try to a fast lookup using the whole URL for a previously resolved partial URL. if (klass == null) klass = partialsMap.get(path); /** * If we don't already have an exact match for this path, * try to break it down. * * Certain extensions are known to be mapped in web.xml, * known to never be dynamic resources (e.g. .swf), or * were discovered earlier to be static content, so don't * process those. */ if (klass == null && !path.matches(bypassPath)) { // (1) Look for *.ext wildcard matches String partial; int index = path.lastIndexOf("."); // If the path contains a "." then check for the *.ext patterns if (index != -1) { partial = "*" + path.substring(index); // gives us the *.<THE_EXTENSION> klass = urlMap.get(partial); } // (2) Check any regex mapping against the path if (klass == null) { // @TODO this iteration could be coslty... perhaps it would be more efficient to have // constructed one long regex of all the possible regex mapping with String regex; Iterator<String> itr = regexMap.keySet().iterator(); while (itr.hasNext()) { regex = itr.next(); if (path.matches(regex)) { // Sweet, we have a match, but make sure we actually get the klass // since it could have been altered since we got the iterator (though, unlikely) klass = regexMap.get(regex); if (klass != null) { // Even better, we got the klass, so move on break; } } } } // (3) Check for possible /something/* patterns if (klass == null) { // start with the full path partial = path; // Start with most specific and move down to just /* while ((index = partial.lastIndexOf("/")) > 0) { // Chop off everything past the last "/" and add the "*" partial = partial.substring(0, index + 1) + "*"; // if we had /first/second, we'd get /first/* if (log.isTraceEnabled()) log.trace("Trying wildcard partial resource: " + partial); klass = urlMap.get(partial); // if we found a match, or if we made it to the simplest form and didn't find anything, get out if (klass != null || partial.equals("/*")) break; // Otherwise, let's try the next chunk, so chop the ending "/*" off partial = partial.substring(0, index); // If we had /first/second to start, we'd get /first if (log.isTraceEnabled()) log.trace("Next partial: " + partial); } } // (4) If we found a class in any way, register it with the currentPath for faster future lookups // UNLESS the config for that klass prohibits it (e.g. a servlet mapped to /user/* in an app // with millions of users could increase the size of urlMap well beyond what is optimal, so // if a servlet knows that is a possibility, it can specify to not save direct mapping when // the servlet was found via a partial mapping) if (klass != null) { if (log.isTraceEnabled()) log.trace("Matched path " + path + " to " + klass.getName()); // Make sure the ServletConfig supports direct lookups before storing the resolved path if (servletMap.get(klass).config.preferDirectLookups()) { partialsMap.putIfAbsent(path, klass); } } } // If we didn't find it, then just pass it on if (klass == null) { if (log.isTraceEnabled()) log.trace("Dynamic resource not found for path: " + path); // Save this path in the staticSet so we don't have to look it up next time urlMap.putIfAbsent(path, StaticResource.class); resolve = System.currentTimeMillis(); chain.doFilter(req, resp); process = System.currentTimeMillis(); } else if (klass == StaticResource.class) { // If it's known to be static, then pass it on if (log.isTraceEnabled()) log.trace("Processing known static path: " + path); resolve = System.currentTimeMillis(); chain.doFilter(req, resp); process = System.currentTimeMillis(); } else { ServletMapping mapping = servletMap.get(klass); // If the klass requires SSL, make sure we're on an SSL connection boolean isSsl = requestExaminer.isSSL(httpReq); SSLOption sslOpt = mapping.config.ssl(); if (sslOpt == SSLOption.UNSPECIFIED) sslOpt = defaultSSLOption; if (sslOpt == SSLOption.REQUIRE && !isSsl) { if (log.isDebugEnabled()) log.debug("Redirecting over SSL: " + path + " [url=" + httpReq.getRequestURL() + "]"); redirectOverSSL(httpReq, httpResp, sslRedirectPort); return; } else if (sslOpt == SSLOption.DENY && isSsl) { if (log.isDebugEnabled()) log.debug("Redirecting off SSL: " + path + " [url=" + httpReq.getRequestURL() + "]"); redirectOverNonSSL(httpReq, httpResp, nonSslRedirectPort); return; } try { if (log.isTraceEnabled()) log.trace("Dynamic resource found, servicing with " + klass.getName()); // Get the time after finding the resource resolve = System.currentTimeMillis(); // Service the end-point on the chain if (log.isTraceEnabled()) log.trace("ServiceChain [path=" + path + ", endPoint=" + mapping.getName() + "]"); new ServiceChain(filters.iterator(), path, mapping).service(httpReq, httpResp); // Get the time after running process = System.currentTimeMillis(); if (httpReq.getParameter("benchmark") != null) log.info(klass.getName() + " execution time: " + (process - start)); } catch (Exception e) { process = System.currentTimeMillis(); if (uncaughtExceptionHandler != null) uncaughtExceptionHandler.handleException(req, resp, e); else throw new ServletException(e); } finally { // maxUses values less than 0 indicate the value is not set and the default should be used // maxUses == 0 indicates the servlet should NOT be reloaded int maxUses = mapping.config.maxUses() < 0 ? maxServletUses : mapping.config.maxUses(); if (maxUses > 0) { long instanceUses = mapping.incrementUses(); // only increment if servlet reloading is enabled if (instanceUses >= maxUses) { try { HttpServlet newInstance = klass.newInstance(); // Create a new instance newInstance.init(mapping.servlet.getServletConfig()); // Copy over the javax.servlet.ServletConfig ServletMapping newMapping = new ServletMapping(newInstance, mapping.config); // new instance but old config if (log.isTraceEnabled()) { if (servletMap.replace(klass, mapping, newMapping)) log.trace("Successfully replaced old " + klass.getSimpleName() + " with a new instance"); else log.trace("Failed to replace old " + klass.getSimpleName() + " with a new instance"); } else { // if we're not tracing, don't bother checking the result, because // either (a) it succeeded and the new servlet is in place, or // (b) it failed meaning another thread beat us to it. servletMap.replace(klass, mapping, newMapping); } // In either case, the old serlvet is no longer in use, but DON'T // destroy it yet, since it may be in the process of serving other // requests. By removing the mapping to it, it should be garbage // collected. } catch (Exception e) { log.error("Error replacing " + klass.getSimpleName() + " instance after " + instanceUses + " uses!", e); } } } } } finish = System.currentTimeMillis(); if (benchmark) { log.info(String.format("[path=%s, find=%d, run=%d, finish=%d]", path, (resolve - start), (process - resolve), (finish - process))); } } finally { read.unlock(); // Make sure to release the read lock } }
From source file:org.j2free.invoker.InvokerFilter.java
/** * Locks to prevent request processing while mapping is added. * * Finds all classes annotated with ServletConfig and maps the class to * the url specified in the annotation. Wildcard mapping are allowed in * the form of *.extension or /some/path/* * * @param context an active ServletContext *///from www . j a v a 2 s. co m public void load(final ServletContext context) { try { write.lock(); LinkedList<URL> urlList = new LinkedList<URL>(); urlList.addAll(Arrays.asList(ClasspathUrlFinder.findResourceBases(EMPTY))); urlList.addAll(Arrays.asList(WarUrlFinder.findWebInfLibClasspaths(context))); URL[] urls = new URL[urlList.size()]; urls = urlList.toArray(urls); AnnotationDB annoDB = new AnnotationDB(); annoDB.setScanClassAnnotations(true); annoDB.setScanFieldAnnotations(false); annoDB.setScanMethodAnnotations(false); annoDB.setScanParameterAnnotations(false); annoDB.scanArchives(urls); HashMap<String, Set<String>> annotationIndex = (HashMap<String, Set<String>>) annoDB .getAnnotationIndex(); if (annotationIndex != null && !annotationIndex.isEmpty()) { //----------------------------------------------------------- // Look for any classes annotated with @ServletConfig Set<String> classNames = annotationIndex.get(ServletConfig.class.getName()); if (classNames != null) { for (String c : classNames) { try { final Class<? extends HttpServlet> klass = (Class<? extends HttpServlet>) Class .forName(c); if (klass.isAnnotationPresent(ServletConfig.class)) { final ServletConfig config = (ServletConfig) klass .getAnnotation(ServletConfig.class); // If the config specifies String mapppings... if (config.mappings() != null) { for (String url : config.mappings()) { // Leave the asterisk, we'll add it when matching... //if (url.matches("(^\\*[^*]*?)|([^*]*?/\\*$)")) // url = url.replace("*", EMPTY); url = url.toLowerCase(); // all comparisons are lower-case if (urlMap.putIfAbsent(url, klass) == null) { if (log.isDebugEnabled()) log.debug("Mapping servlet " + klass.getName() + " to path " + url); } else log.error("Unable to map servlet " + klass.getName() + " to path " + url + ", path already mapped to " + urlMap.get(url).getName()); } } // If the config specifies a regex mapping... if (!empty(config.regex())) { regexMap.putIfAbsent(config.regex(), klass); if (log.isDebugEnabled()) log.debug("Mapping servlet " + klass.getName() + " to regex path " + config.regex()); } // Create an instance of the servlet and init it HttpServlet servlet = klass.newInstance(); servlet.init(new ServletConfigImpl(klass.getName(), context)); // Store a reference servletMap.put(klass, new ServletMapping(servlet, config)); } } catch (Exception e) { log.error("Error registering servlet [name=" + c + "]", e); } } } //----------------------------------------------------------- // Look for any classes annotated with @FiltersConfig classNames = annotationIndex.get(FilterConfig.class.getName()); if (classNames != null) { for (String c : classNames) { try { final Class<? extends Filter> klass = (Class<? extends Filter>) Class.forName(c); if (klass.isAnnotationPresent(FilterConfig.class)) { final FilterConfig config = (FilterConfig) klass.getAnnotation(FilterConfig.class); // Create an instance of the servlet and init it Filter filter = klass.newInstance(); filter.init(new FilterConfigImpl(klass.getName(), context)); if (log.isDebugEnabled()) log.debug("Mapping filter " + klass.getName() + " to path " + config.match()); // Store a reference filters.add(new FilterMapping(filter, config)); } } catch (Exception e) { log.error("Error registering servlet [name=" + c + "]", e); } } } } } catch (IOException e) { log.error("Error loading urlMappings", e); } finally { write.unlock(); // ALWAYS Release the configure lock } }
From source file:org.openmrs.module.web.WebModuleUtil.java
/** * This method will find and cache this module's servlets (so that it doesn't have to look them * up every time)//from w w w.ja va 2 s .c o m * * @param mod * @param servletContext the servlet context */ public static void loadServlets(Module mod, ServletContext servletContext) { Element rootNode = mod.getConfig().getDocumentElement(); NodeList servletTags = rootNode.getElementsByTagName("servlet"); for (int i = 0; i < servletTags.getLength(); i++) { Node node = servletTags.item(i); NodeList childNodes = node.getChildNodes(); String name = "", className = ""; for (int j = 0; j < childNodes.getLength(); j++) { Node childNode = childNodes.item(j); if ("servlet-name".equals(childNode.getNodeName())) { if (childNode.getTextContent() != null) { name = childNode.getTextContent().trim(); } } else if ("servlet-class".equals(childNode.getNodeName()) && childNode.getTextContent() != null) { className = childNode.getTextContent().trim(); } } if (name.length() == 0 || className.length() == 0) { log.warn("both 'servlet-name' and 'servlet-class' are required for the 'servlet' tag. Given '" + name + "' and '" + className + "' for module " + mod.getName()); continue; } HttpServlet httpServlet = null; try { httpServlet = (HttpServlet) ModuleFactory.getModuleClassLoader(mod).loadClass(className) .newInstance(); } catch (ClassNotFoundException e) { log.warn("Class not found for servlet " + name + " for module " + mod.getName(), e); continue; } catch (IllegalAccessException e) { log.warn("Class cannot be accessed for servlet " + name + " for module " + mod.getName(), e); continue; } catch (InstantiationException e) { log.warn("Class cannot be instantiated for servlet " + name + " for module " + mod.getName(), e); continue; } try { log.debug("Initializing " + name + " servlet. - " + httpServlet + "."); ServletConfig servletConfig = new ModuleServlet.SimpleServletConfig(name, servletContext); httpServlet.init(servletConfig); } catch (Exception e) { log.warn("Unable to initialize servlet: ", e); throw new ModuleException("Unable to initialize servlet: " + httpServlet, mod.getModuleId(), e); } // don't allow modules to overwrite servlets of other modules. HttpServlet otherServletUsingSameName = moduleServlets.get(name); if (otherServletUsingSameName != null) { //log.debug("A servlet mapping with name " + name + " already exists. " + mod.getModuleId() + "'s servlet is overwriting it"); String otherServletName = otherServletUsingSameName.getClass().getPackage() + "." + otherServletUsingSameName.getClass().getName(); throw new ModuleException("A servlet mapping with name " + name + " is already in use and pointing at: " + otherServletName + " from another installed module and this module is trying" + " to use that same name. Either the module attempting to be installed (" + mod.getModuleId() + ") will not work or the other one will not. Please consult the developers of these two" + " modules to sort this out."); } log.debug("Caching the " + name + " servlet."); moduleServlets.put(name, httpServlet); } }