Search in sources :

Example 21 with Servlet

use of javax.servlet.Servlet in project spring-framework by spring-projects.

the class HttpRequestHandlerTests method testHttpRequestHandlerServletPassThrough.

@Test
public void testHttpRequestHandlerServletPassThrough() throws Exception {
    MockServletContext servletContext = new MockServletContext();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.getBeanFactory().registerSingleton("myHandler", new HttpRequestHandler() {

        @Override
        public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
            assertSame(request, req);
            assertSame(response, res);
            String exception = request.getParameter("exception");
            if ("ServletException".equals(exception)) {
                throw new ServletException("test");
            }
            if ("IOException".equals(exception)) {
                throw new IOException("test");
            }
            res.getWriter().write("myResponse");
        }
    });
    wac.setServletContext(servletContext);
    wac.refresh();
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    Servlet servlet = new HttpRequestHandlerServlet();
    servlet.init(new MockServletConfig(servletContext, "myHandler"));
    servlet.service(request, response);
    assertEquals("myResponse", response.getContentAsString());
    try {
        request.setParameter("exception", "ServletException");
        servlet.service(request, response);
        fail("Should have thrown ServletException");
    } catch (ServletException ex) {
        assertEquals("test", ex.getMessage());
    }
    try {
        request.setParameter("exception", "IOException");
        servlet.service(request, response);
        fail("Should have thrown IOException");
    } catch (IOException ex) {
        assertEquals("test", ex.getMessage());
    }
}
Also used : HttpRequestHandler(org.springframework.web.HttpRequestHandler) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) MockServletConfig(org.springframework.mock.web.test.MockServletConfig) IOException(java.io.IOException) MockServletContext(org.springframework.mock.web.test.MockServletContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) ServletException(javax.servlet.ServletException) Servlet(javax.servlet.Servlet) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) Test(org.junit.Test)

Example 22 with Servlet

use of javax.servlet.Servlet in project atmosphere by Atmosphere.

the class MeteorServiceInterceptor method mapAnnotatedService.

protected void mapAnnotatedService(boolean reMap, String path, AtmosphereRequest request, AtmosphereFramework.AtmosphereHandlerWrapper w) {
    synchronized (config.handlers()) {
        if (config.handlers().get(path) == null) {
            // MeteorService
            if (ReflectorServletProcessor.class.isAssignableFrom(w.atmosphereHandler.getClass())) {
                ReflectorServletProcessor r = ReflectorServletProcessor.class.cast(w.atmosphereHandler);
                Servlet s = r.getServlet();
                MeteorService m = s.getClass().getAnnotation(MeteorService.class);
                if (m != null) {
                    String targetPath = m.path();
                    if (targetPath.indexOf("{") != -1 && targetPath.indexOf("}") != -1) {
                        try {
                            boolean singleton = s.getClass().getAnnotation(Singleton.class) != null;
                            if (!singleton) {
                                r = config.framework().newClassInstance(ReflectorServletProcessor.class, ReflectorServletProcessor.class);
                                r.setServlet(config.framework().newClassInstance(Servlet.class, s.getClass()));
                                r.init(config);
                            }
                            request.localAttributes().put(Named.class.getName(), path.substring(targetPath.indexOf("{")));
                            AtmosphereResourceImpl.class.cast(request.resource()).atmosphereHandler(r);
                            config.framework().addAtmosphereHandler(path, r, config.getBroadcasterFactory().lookup(w.broadcaster.getClass(), path, true), w.interceptors);
                            request.setAttribute(FrameworkConfig.NEW_MAPPING, "true");
                        } catch (Throwable e) {
                            logger.warn("Unable to create AtmosphereHandler", e);
                        }
                    }
                }
            }
        } else if (reMap) {
            request.setAttribute(FrameworkConfig.NEW_MAPPING, "true");
        }
    }
}
Also used : MeteorService(org.atmosphere.config.service.MeteorService) Named(javax.inject.Named) Singleton(org.atmosphere.config.service.Singleton) Servlet(javax.servlet.Servlet) ReflectorServletProcessor(org.atmosphere.handler.ReflectorServletProcessor) AtmosphereResourceImpl(org.atmosphere.runtime.AtmosphereResourceImpl)

Example 23 with Servlet

use of javax.servlet.Servlet in project atmosphere by Atmosphere.

the class AtmosphereResourceTest method verifyTestCompletionAwareForSync.

private void verifyTestCompletionAwareForSync(boolean aware) throws IOException, ServletException {
    Servlet s = mock(Servlet.class);
    if (aware) {
        framework.addInitParameter(ApplicationConfig.RESPONSE_COMPLETION_AWARE, "true");
    }
    ReflectorServletProcessor handler = new ReflectorServletProcessor(s);
    handler.init(framework.getAtmosphereConfig());
    AtmosphereRequest request = new AtmosphereRequestImpl.Builder().pathInfo("/a").build();
    AtmosphereResponseImpl response = mock(AtmosphereResponseImpl.class);
    AtmosphereResourceImpl res = new AtmosphereResourceImpl();
    res.initialize(framework.getAtmosphereConfig(), framework.getBroadcasterFactory().get(), request, response, null, null);
    res.transport(AtmosphereResource.TRANSPORT.WEBSOCKET);
    request.setAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE, res);
    request.setAttribute(FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE, res);
    handler.onRequest(res);
    verify(response, times(aware ? 1 : 0)).onComplete();
}
Also used : Servlet(javax.servlet.Servlet) ReflectorServletProcessor(org.atmosphere.handler.ReflectorServletProcessor)

Example 24 with Servlet

use of javax.servlet.Servlet in project karaf by apache.

the class ServletServiceImpl method getServlets.

@Override
public List<ServletInfo> getServlets() {
    List<ServletInfo> servletInfos = new ArrayList<>();
    Collection<ServletEvent> events = servletEventHandler.getServletEvents();
    for (ServletEvent event : events) {
        Servlet servlet = event.getServlet();
        String servletClassName = " ";
        if (servlet != null) {
            servletClassName = servlet.getClass().getName();
            servletClassName = servletClassName.substring(servletClassName.lastIndexOf(".") + 1, servletClassName.length());
        }
        String servletName = event.getServletName() != null ? event.getServletName() : " ";
        if (servletName.contains(".")) {
            servletName = servletName.substring(servletName.lastIndexOf(".") + 1, servletName.length());
        }
        String alias = event.getAlias() != null ? event.getAlias() : " ";
        String[] urls = event.getUrlParameter() != null ? event.getUrlParameter() : new String[] { "" };
        ServletInfo info = new ServletInfo();
        info.setBundleId(event.getBundle().getBundleId());
        info.setName(servletName);
        info.setClassName(servletClassName);
        info.setState(event.getType());
        info.setAlias(alias);
        info.setUrls(urls);
        servletInfos.add(info);
    }
    return servletInfos;
}
Also used : ServletInfo(org.apache.karaf.http.core.ServletInfo) ArrayList(java.util.ArrayList) ServletEvent(org.ops4j.pax.web.service.spi.ServletEvent) Servlet(javax.servlet.Servlet)

Example 25 with Servlet

use of javax.servlet.Servlet in project sling by apache.

the class FormAuthenticationHandler method requestCredentials.

/**
     * 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>
     * 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;
}
Also used : ServletException(javax.servlet.ServletException) HashMap(java.util.HashMap) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) Servlet(javax.servlet.Servlet) LoginException(org.apache.sling.api.resource.LoginException) IOException(java.io.IOException)

Aggregations

Servlet (javax.servlet.Servlet)86 Test (org.junit.Test)18 HttpServlet (javax.servlet.http.HttpServlet)16 ServletException (javax.servlet.ServletException)15 IOException (java.io.IOException)11 OptingServlet (org.apache.sling.api.servlets.OptingServlet)11 GenericServlet (javax.servlet.GenericServlet)10 DefaultErrorHandlerServlet (org.apache.sling.servlets.resolver.internal.defaults.DefaultErrorHandlerServlet)9 DefaultServlet (org.apache.sling.servlets.resolver.internal.defaults.DefaultServlet)9 ServletContext (javax.servlet.ServletContext)8 UnavailableException (javax.servlet.UnavailableException)8 Resource (org.apache.sling.api.resource.Resource)8 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)8 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)7 MockServletWebServerFactory (org.springframework.boot.web.servlet.server.MockServletWebServerFactory)7 ServletInfo (io.undertow.servlet.api.ServletInfo)6 ArrayList (java.util.ArrayList)5 Filter (javax.servlet.Filter)5 Context (org.apache.catalina.Context)5 SlingHttpServletResponse (org.apache.sling.api.SlingHttpServletResponse)5