List of usage examples for javax.servlet Servlet service
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
From source file:info.magnolia.cms.filters.ServletDispatchingFilterTest.java
private void doTestBypassAndPathInfo(final boolean shouldBypass, final String expectedPathInfo, final String expectedServletPath, final String requestPath, String mapping, boolean shouldCheckPathInfoAndServletPath) throws Exception { ComponentsTestUtil.setInstance(Voting.class, new DefaultVoting()); WebContext ctx = createStrictMock(WebContext.class); MgnlContext.setInstance(ctx);/* ww w . j av a 2 s.co m*/ final AggregationState state = new MockAggregationState(); expect(ctx.getContextPath()).andReturn("/magnoliaAuthor").anyTimes(); final FilterChain chain = createNiceMock(FilterChain.class); final HttpServletResponse res = createNiceMock(HttpServletResponse.class); final HttpServletRequest req = createMock(HttpServletRequest.class); expect(req.getAttribute(EasyMock.<String>anyObject())).andReturn(null).anyTimes(); expect(ctx.getAggregationState()).andReturn(state).anyTimes(); expect(req.getRequestURI()).andReturn("/magnoliaAuthor" + requestPath).anyTimes(); expect(req.getContextPath()).andReturn("/magnoliaAuthor").anyTimes(); expect(req.getServletPath()).andReturn("/magnoliaAuthor" + requestPath).anyTimes(); expect(req.getPathInfo()).andReturn(null).anyTimes(); expect(req.getQueryString()).andReturn(null).anyTimes(); final Servlet servlet = createStrictMock(Servlet.class); if (!shouldBypass) { servlet.service(isA(HttpServletRequestWrapper.class), same(res)); expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { final HttpServletRequestWrapper requestWrapper = (HttpServletRequestWrapper) getCurrentArguments()[0]; final String pathInfo = requestWrapper.getPathInfo(); final String servletPath = requestWrapper.getServletPath(); assertEquals("pathInfo does not match", expectedPathInfo, pathInfo); assertEquals("servletPath does not match", expectedServletPath, servletPath); return null; } }); } replay(chain, res, req, servlet, ctx); state.setCurrentURI(requestPath); final AbstractMgnlFilter filter = new ServletDispatchingFilter(); final Field servletField = ServletDispatchingFilter.class.getDeclaredField("servlet"); servletField.setAccessible(true); servletField.set(filter, servlet); filter.addMapping(mapping); assertEquals("Should " + (shouldBypass ? "" : "not ") + "have bypassed", shouldBypass, !filter.matches(req)); if (!shouldBypass) { filter.doFilter(req, res, chain); } verify(chain, res, req, servlet, ctx); }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHolder.java
/** Service a request with this servlet. *///from w ww . j a v a 2s . co m public void handle(ServletRequest request, ServletResponse response) throws ServletException, UnavailableException, IOException { if (_class == null) throw new UnavailableException("Servlet Not Initialized"); Servlet servlet = (!_initOnStartup || _servlets != null) ? getServlet() : _servlet; if (servlet == null) throw new UnavailableException("Could not instantiate " + _class); // Service the request boolean servlet_error = true; Principal user = null; HttpRequest http_request = null; try { // Handle aliased path if (_forcedPath != null) // TODO complain about poor naming to the Jasper folks request.setAttribute("org.apache.catalina.jsp_file", _forcedPath); // Handle run as if (_runAs != null && _realm != null) { http_request = getHttpContext().getHttpConnection().getRequest(); user = _realm.pushRole(http_request.getUserPrincipal(), _runAs); http_request.setUserPrincipal(user); } servlet.service(request, response); servlet_error = false; } catch (UnavailableException e) { if (_servlets != null && servlet != null) stop(); makeUnavailable(e); } finally { // pop run-as role if (_runAs != null && _realm != null && user != null) { user = _realm.popRole(user); http_request.setUserPrincipal(user); } // Handle error params. if (servlet_error) request.setAttribute("javax.servlet.error.servlet_name", getName()); // Return to singleThreaded pool synchronized (this) { if (_servlets != null && servlet != null) _servlets.push(servlet); } } }
From source file:ch.entwine.weblounge.workbench.WorkbenchService.java
/** * Asks the site servlet to render the given url using the page, composer and * pagelet as the rendering environment. If the no servlet is available for * the given site, the contents are loaded from the url directly. * //from www . ja v a2 s . c o m * @param rendererURL * the renderer url * @param site * the site * @param page * the page * @param composer * the composer * @param pagelet * the pagelet * @param environment * the environment * @param language * the language * @return the servlet response, serialized to a string * @throws IOException * if the servlet fails to create the response * @throws ServletException * if an exception occurs while processing */ private String loadContents(URL rendererURL, Site site, Page page, Composer composer, Pagelet pagelet, Environment environment, String language) throws IOException, ServletException { Servlet servlet = siteServlets.get(site.getIdentifier()); String httpContextURI = UrlUtils.concat("/weblounge-sites", site.getIdentifier()); int httpContextURILength = httpContextURI.length(); String url = rendererURL.toExternalForm(); int uriInPath = url.indexOf(httpContextURI); if (uriInPath > 0) { String pathInfo = url.substring(uriInPath + httpContextURILength); // Prepare the mock request MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); request.setServerName(site.getHostname(environment).getURL().getHost()); request.setServerPort(site.getHostname(environment).getURL().getPort()); request.setMethod(site.getHostname(environment).getURL().getProtocol()); if (language != null) request.addPreferredLocale(new Locale(language)); request.setAttribute(WebloungeRequest.PAGE, page); request.setAttribute(WebloungeRequest.COMPOSER, composer); request.setAttribute(WebloungeRequest.PAGELET, pagelet); request.setPathInfo(pathInfo); request.setRequestURI(UrlUtils.concat(httpContextURI, pathInfo)); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); return response.getContentAsString(); } else { InputStream is = null; try { is = rendererURL.openStream(); return IOUtils.toString(is, "utf-8"); } finally { IOUtils.closeQuietly(is); } } }
From source file:ch.entwine.weblounge.preview.xhtmlrenderer.XhtmlRendererPagePreviewGenerator.java
/** * Renders the page located at <code>rendererURL</code> in the given language. * //w ww .j a v a 2 s . c o m * @param rendererURL * the page url * @param site * the site * @param environment * the environment * @param language * the language * @param version * the version * @return the rendered <code>HTML</code> * @throws ServletException * if rendering fails * @throws IOException * if reading from the servlet fails */ private String render(URL rendererURL, Site site, Environment environment, Language language, long version) throws ServletException, IOException { Servlet servlet = siteServlets.get(site.getIdentifier()); String httpContextURI = UrlUtils.concat("/weblounge-sites", site.getIdentifier()); int httpContextURILength = httpContextURI.length(); String url = rendererURL.toExternalForm(); int uriInPath = url.indexOf(httpContextURI); // Are we trying to render a site resource (e. g. a jsp during // precompilation)? if (uriInPath > 0) { String pathInfo = url.substring(uriInPath + httpContextURILength); // Prepare the mock request MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); request.setServerName(site.getHostname(environment).getURL().getHost()); request.setServerPort(site.getHostname(environment).getURL().getPort()); request.setMethod(site.getHostname(environment).getURL().getProtocol()); request.setAttribute(WebloungeRequest.LANGUAGE, language); request.setPathInfo(pathInfo); request.setRequestURI(UrlUtils.concat(httpContextURI, pathInfo)); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); return response.getContentAsString(); } else { HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); try { if (version == Resource.WORK) { rendererURL = new URL(UrlUtils.concat(rendererURL.toExternalForm(), "work_" + language.getIdentifier() + ".html")); } else { rendererURL = new URL(UrlUtils.concat(rendererURL.toExternalForm(), "index_" + language.getIdentifier() + ".html")); } HttpGet getRequest = new HttpGet(rendererURL.toExternalForm()); getRequest.addHeader(new BasicHeader("X-Weblounge-Special", "Page-Preview")); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) return null; String responseText = EntityUtils.toString(response.getEntity(), "utf-8"); return responseText; } finally { httpClient.getConnectionManager().shutdown(); } } }
From source file:ch.entwine.weblounge.dispatcher.impl.handler.FeedRequestHandlerImpl.java
/** * Asks the site servlet to render the given url using the page, composer and * pagelet as the rendering environment. If the no servlet is available for * the given site, the contents are loaded from the url directly. * /*from ww w.j a va 2 s . c o m*/ * @param rendererURL * the renderer url * @param site * the site * @param page * the page * @param composer * the composer * @param pagelet * the pagelet * @param environment * the environment * @return the servlet response, serialized to a string * @throws IOException * if the servlet fails to create the response * @throws ServletException * if an exception occurs while processing */ private String loadContents(URL rendererURL, Site site, Page page, Composer composer, Pagelet pagelet, Environment environment) throws IOException, ServletException { Servlet servlet = siteServlets.get(site.getIdentifier()); String httpContextURI = UrlUtils.concat("/weblounge-sites", site.getIdentifier()); int httpContextURILength = httpContextURI.length(); String url = rendererURL.toExternalForm(); int uriInPath = url.indexOf(httpContextURI); if (uriInPath > 0) { String pathInfo = url.substring(uriInPath + httpContextURILength); // Prepare the mock request MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); request.setServerName(site.getHostname(environment).getURL().getHost()); request.setServerPort(site.getHostname(environment).getURL().getPort()); request.setMethod(site.getHostname(environment).getURL().getProtocol()); request.setAttribute(WebloungeRequest.PAGE, page); request.setAttribute(WebloungeRequest.COMPOSER, composer); request.setAttribute(WebloungeRequest.PAGELET, pagelet); request.setPathInfo(pathInfo); request.setRequestURI(UrlUtils.concat(httpContextURI, pathInfo)); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); return response.getContentAsString(); } else { InputStream is = null; try { is = rendererURL.openStream(); return IOUtils.toString(is, "utf-8"); } finally { IOUtils.closeQuietly(is); } } }
From source file:org.apache.catalina.core.StandardWrapper.java
/** * Load and initialize an instance of this servlet, if there is not already * at least one initialized instance. This can be used, for example, to * load servlets that are marked in the deployment descriptor to be loaded * at server startup time./* www .ja va2s .c o m*/ */ public synchronized Servlet loadServlet() throws ServletException { // Nothing to do if we already have an instance or an instance pool if (!singleThreadModel && (instance != null)) return instance; PrintStream out = System.out; if (swallowOutput) { SystemLogHandler.startCapture(); } Servlet servlet; try { long t1 = System.currentTimeMillis(); // If this "servlet" is really a JSP file, get the right class. // HOLD YOUR NOSE - this is a kludge that avoids having to do special // case Catalina-specific code in Jasper - it also requires that the // servlet path be replaced by the <jsp-file> element content in // order to be completely effective String actualClass = servletClass; if ((actualClass == null) && (jspFile != null)) { Wrapper jspWrapper = (Wrapper) ((Context) getParent()).findChild(Constants.JSP_SERVLET_NAME); if (jspWrapper != null) actualClass = jspWrapper.getServletClass(); } // Complain if no servlet class has been specified if (actualClass == null) { unavailable(null); throw new ServletException(sm.getString("standardWrapper.notClass", getName())); } // Acquire an instance of the class loader to be used Loader loader = getLoader(); if (loader == null) { unavailable(null); throw new ServletException(sm.getString("standardWrapper.missingLoader", getName())); } ClassLoader classLoader = loader.getClassLoader(); // Special case class loader for a container provided servlet // if (isContainerProvidedServlet(actualClass) && !((Context) getParent()).getPrivileged()) { // If it is a priviledged context - using its own // class loader will work, since it's a child of the container // loader classLoader = this.getClass().getClassLoader(); } // Load the specified servlet class from the appropriate class loader Class classClass = null; try { if (System.getSecurityManager() != null) { final ClassLoader fclassLoader = classLoader; final String factualClass = actualClass; try { classClass = (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { if (fclassLoader != null) { return fclassLoader.loadClass(factualClass); } else { return Class.forName(factualClass); } } }); } catch (PrivilegedActionException pax) { Exception ex = pax.getException(); if (ex instanceof ClassNotFoundException) { throw (ClassNotFoundException) ex; } else { getServletContext().log("Error loading " + fclassLoader + " " + factualClass, ex); } } } else { if (classLoader != null) { classClass = classLoader.loadClass(actualClass); } else { classClass = Class.forName(actualClass); } } } catch (ClassNotFoundException e) { unavailable(null); getServletContext().log("Error loading " + classLoader + " " + actualClass, e); throw new ServletException(sm.getString("standardWrapper.missingClass", actualClass), e); } if (classClass == null) { unavailable(null); throw new ServletException(sm.getString("standardWrapper.missingClass", actualClass)); } // Instantiate and initialize an instance of the servlet class itself try { servlet = (Servlet) classClass.newInstance(); } catch (ClassCastException e) { unavailable(null); // Restore the context ClassLoader throw new ServletException(sm.getString("standardWrapper.notServlet", actualClass), e); } catch (Throwable e) { unavailable(null); // Restore the context ClassLoader throw new ServletException(sm.getString("standardWrapper.instantiate", actualClass), e); } // Check if loading the servlet in this web application should be // allowed if (!isServletAllowed(servlet)) { throw new SecurityException(sm.getString("standardWrapper.privilegedServlet", actualClass)); } // Special handling for ContainerServlet instances if ((servlet instanceof ContainerServlet) && (isContainerProvidedServlet(actualClass) || ((Context) getParent()).getPrivileged())) { ((ContainerServlet) servlet).setWrapper(this); } classLoadTime = (int) (System.currentTimeMillis() - t1); // Call the initialization method of this servlet try { instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT, servlet); if (System.getSecurityManager() != null) { Class[] classType = new Class[] { ServletConfig.class }; Object[] args = new Object[] { ((ServletConfig) facade) }; SecurityUtil.doAsPrivilege("init", servlet, classType, args); } else { servlet.init(facade); } // Invoke jspInit on JSP pages if ((loadOnStartup >= 0) && (jspFile != null)) { // Invoking jspInit DummyRequest req = new DummyRequest(); req.setServletPath(jspFile); req.setQueryString("jsp_precompile=true"); DummyResponse res = new DummyResponse(); if (System.getSecurityManager() != null) { Class[] classType = new Class[] { ServletRequest.class, ServletResponse.class }; Object[] args = new Object[] { req, res }; SecurityUtil.doAsPrivilege("service", servlet, classType, args); } else { servlet.service(req, res); } } instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet); } catch (UnavailableException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); unavailable(f); throw f; } catch (ServletException f) { instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw f; } catch (Throwable f) { getServletContext().log("StandardWrapper.Throwable", f); instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT, servlet, f); // If the servlet wanted to be unavailable it would have // said so, so do not call unavailable(null). throw new ServletException(sm.getString("standardWrapper.initException", getName()), f); } // Register our newly initialized instance singleThreadModel = servlet instanceof SingleThreadModel; if (singleThreadModel) { if (instancePool == null) instancePool = new Stack(); } fireContainerEvent("load", this); loadTime = System.currentTimeMillis() - t1; } finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); if (log != null && log.length() > 0) { if (getServletContext() != null) { getServletContext().log(log); } else { out.println(log); } } } } return servlet; }
From source file:org.apache.cocoon.servletservice.DispatcherServlet.java
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { final Map mountableServlets = getBlockServletMap(); String path = req.getPathInfo(); if (path == null) { path = ""; }//from ww w .jav a 2 s .c o m // find the servlet which mount path is the longest prefix of the path info int index = path.length(); Servlet servlet = null; while (servlet == null && index != -1) { path = path.substring(0, index); servlet = (Servlet) mountableServlets.get(path); index = path.lastIndexOf('/'); } //case when servlet is mounted at "/" must be handled separately servlet = servlet == null ? (Servlet) mountableServlets.get("/") : servlet; if (servlet == null) { String message = "No block for " + req.getPathInfo(); res.sendError(HttpServletResponse.SC_NOT_FOUND, message); this.logger.info(message); return; } // Create a dynamic proxy class that overwrites the getServletPath and // getPathInfo methods to provide reasonable values in the called servlet // the dynamic proxy implements all interfaces of the original request HttpServletRequest request = (HttpServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), getInterfaces(req.getClass()), new DynamicProxyRequestHandler(req, path)); if (this.logger.isDebugEnabled()) { this.logger.debug("DispatcherServlet: service servlet=" + servlet + " mountPath=" + path + " servletPath=" + request.getServletPath() + " pathInfo=" + request.getPathInfo()); } servlet.service(request, res); }
From source file:org.apache.sling.auth.form.impl.FormAuthenticationHandler.java
/** * Unless the <code>sling:authRequestLogin</code> to anything other than * <code>Form</code> this method either sends back a 403/FORBIDDEN response * if the <code>j_verify</code> parameter is set to <code>true</code> or * redirects to the login form to ask for credentials. * <p>//from w ww . ja v a 2 s . co m * This method assumes the <code>j_verify</code> request parameter to only * be set in the initial username/password submission through the login * form. No further checks are applied, though, before sending back the * 403/FORBIDDEN response. */ @Override public boolean requestCredentials(HttpServletRequest request, HttpServletResponse response) throws IOException { // 0. ignore this handler if an authentication handler is requested if (ignoreRequestCredentials(request)) { // consider this handler is not used return false; } //check the referrer to see if the request is for this handler if (!AuthUtil.checkReferer(request, loginForm)) { //not for this handler, so return return false; } final String resource = AuthUtil.setLoginResourceAttribute(request, request.getRequestURI()); if (includeLoginForm && (resourceResolverFactory != null)) { ResourceResolver resourceResolver = null; try { resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null); Resource loginFormResource = resourceResolver.resolve(loginForm); Servlet loginFormServlet = loginFormResource.adaptTo(Servlet.class); if (loginFormServlet != null) { try { loginFormServlet.service(request, response); return true; } catch (ServletException e) { log.error("Failed to include the form: " + loginForm, e); } } } catch (LoginException e) { log.error( "Unable to get a resource resolver to include for the login resource. Will redirect instead."); } finally { if (resourceResolver != null) { resourceResolver.close(); } } } HashMap<String, String> params = new HashMap<String, String>(); params.put(Authenticator.LOGIN_RESOURCE, resource); // append indication of previous login failure if (request.getAttribute(FAILURE_REASON) != null) { final Object jReason = request.getAttribute(FAILURE_REASON); @SuppressWarnings("rawtypes") final String reason = (jReason instanceof Enum) ? ((Enum) jReason).name() : jReason.toString(); params.put(FAILURE_REASON, reason); } try { AuthUtil.sendRedirect(request, response, request.getContextPath() + loginForm, params); } catch (IOException e) { log.error("Failed to redirect to the login form " + loginForm, e); } return true; }
From source file:org.apache.sling.scripting.sightly.impl.engine.extension.IncludeRuntimeExtension.java
private void includeScript(final Bindings bindings, String script, PrintWriter out) { if (StringUtils.isEmpty(script)) { throw new SightlyException("Path for data-sly-include is empty"); } else {//from www . j a va2s . co m LOG.debug("Attempting to include script {}.", script); SlingScriptHelper slingScriptHelper = BindingsUtils.getHelper(bindings); ServletResolver servletResolver = slingScriptHelper.getService(ServletResolver.class); if (servletResolver != null) { SlingHttpServletRequest request = BindingsUtils.getRequest(bindings); Servlet servlet = servletResolver.resolveServlet(request.getResource(), script); if (servlet != null) { try { SlingHttpServletResponse response = BindingsUtils.getResponse(bindings); PrintWriterResponseWrapper resWrapper = new PrintWriterResponseWrapper(out, response); servlet.service(request, resWrapper); } catch (Exception e) { throw new SightlyException("Failed to include script " + script, e); } } else { throw new SightlyException("Failed to locate script " + script); } } else { throw new SightlyException( "Sling ServletResolver service is unavailable, failed to include " + script); } } }
From source file:org.apache.sling.servlets.resolver.internal.SlingServletResolver.java
private void handleError(final Servlet errorHandler, final HttpServletRequest request, final HttpServletResponse response) throws IOException { request.setAttribute(SlingConstants.ERROR_REQUEST_URI, request.getRequestURI()); // if there is no explicitly known error causing servlet, use // the name of the error handler servlet if (request.getAttribute(SlingConstants.ERROR_SERVLET_NAME) == null) { request.setAttribute(SlingConstants.ERROR_SERVLET_NAME, errorHandler.getServletConfig().getServletName()); }/* ww w .j a va 2 s. c om*/ // Let the error handler servlet process the request and // forward all exceptions if it fails. // Before SLING-4143 we only forwarded IOExceptions. try { errorHandler.service(request, response); // commit the response response.flushBuffer(); // close the response (SLING-2724) response.getWriter().close(); } catch (final Throwable t) { LOGGER.error("Calling the error handler resulted in an error", t); LOGGER.error("Original error " + request.getAttribute(SlingConstants.ERROR_EXCEPTION_TYPE), (Throwable) request.getAttribute(SlingConstants.ERROR_EXCEPTION)); final IOException x = new IOException("Error handler failed: " + t.getClass().getName()); x.initCause(t); throw x; } }