Example usage for javax.servlet.http HttpServlet HttpServlet

List of usage examples for javax.servlet.http HttpServlet HttpServlet

Introduction

In this page you can find the example usage for javax.servlet.http HttpServlet HttpServlet.

Prototype


public HttpServlet() 

Source Link

Document

Does nothing, because this is an abstract class.

Usage

From source file:fr.xebia.servlet.filter.XForwardedFilterTest.java

private void test302RedirectWithJetty(final String sendRedirectLocation, String expectedLocation,
        int httpsServerPortParameter) throws Exception {
    // SETUP//from   w ww .ja v a  2  s.c o m
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    // mostly default configuration : enable "x-forwarded-proto"
    XForwardedFilter xforwardedFilter = new XForwardedFilter();
    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter(XForwardedFilter.PROTOCOL_HEADER_PARAMETER, "x-forwarded-proto");
    filterConfig.addInitParameter(XForwardedFilter.HTTPS_SERVER_PORT_PARAMETER,
            String.valueOf(httpsServerPortParameter));
    // Following is needed on ipv6 stacks..
    filterConfig.addInitParameter(XForwardedFilter.INTERNAL_PROXIES_PARAMETER,
            InetAddress.getByName("localhost").getHostAddress());
    xforwardedFilter.init(filterConfig);
    context.addFilter(new FilterHolder(xforwardedFilter), "/*", Handler.REQUEST);

    HttpServlet mockServlet = new HttpServlet() {

        private static final long serialVersionUID = 1L;

        @Override
        public void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.sendRedirect(sendRedirectLocation);
        }

    };
    context.addServlet(new ServletHolder(mockServlet), "/test");

    server.start();
    try {
        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();
        httpURLConnection.setInstanceFollowRedirects(false);
        String expectedRemoteAddr = "my-remote-addr";
        httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
        httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

        // VALIDATE
        Assert.assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, httpURLConnection.getResponseCode());
        String actualLocation = httpURLConnection.getHeaderField("Location");
        assertEquals(expectedLocation, actualLocation);

    } finally {
        server.stop();
    }
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

private String setUpFactoryForCompression(int contentSize, String[] mimeTypes, String[] excludedUserAgents)
        throws Exception {
    char[] chars = new char[contentSize];
    Arrays.fill(chars, 'F');
    String testContent = new String(chars);
    AbstractServletWebServerFactory factory = getFactory();
    Compression compression = new Compression();
    compression.setEnabled(true);//  w ww  .  ja v  a  2s  .c o m
    if (mimeTypes != null) {
        compression.setMimeTypes(mimeTypes);
    }
    if (excludedUserAgents != null) {
        compression.setExcludedUserAgents(excludedUserAgents);
    }
    factory.setCompression(compression);
    factory.addInitializers(new ServletRegistrationBean<HttpServlet>(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            resp.setContentType("text/plain");
            resp.setContentLength(testContent.length());
            resp.getWriter().write(testContent);
            resp.getWriter().flush();
        }

    }, "/test.txt"));
    this.webServer = factory.getWebServer();
    this.webServer.start();
    return testContent;
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

/**
 * Initialize the filter./*from  w ww.java  2  s . c om*/
 *
 * @param filterConfig filter configuration.
 * @throws ServletException thrown if the filter could not be initialized.
 */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    LOG.info("AtlasAuthenticationFilter initialization started");
    final FilterConfig globalConf = filterConfig;

    final Map<String, String> params = new HashMap<>();

    FilterConfig filterConfig1 = new FilterConfig() {
        @Override
        public ServletContext getServletContext() {
            if (globalConf != null) {
                return globalConf.getServletContext();
            } else {
                return nullContext;
            }
        }

        @SuppressWarnings("unchecked")
        @Override
        public Enumeration<String> getInitParameterNames() {
            return new IteratorEnumeration(params.keySet().iterator());
        }

        @Override
        public String getInitParameter(String param) {
            return params.get(param);
        }

        @Override
        public String getFilterName() {
            return "AtlasAuthenticationFilter";
        }
    };

    super.init(filterConfig1);

    optionsServlet = new HttpServlet() {
    };
    optionsServlet.init();

}

From source file:org.apache.falcon.security.BasicAuthFilter.java

/**
 * Initialize the filter.//from www.j a va 2s .co  m
 *
 * @param filterConfig filter configuration.
 * @throws ServletException thrown if the filter could not be initialized.
 */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    LOG.info("BasicAuthFilter initialization started");
    super.init(filterConfig);

    optionsServlet = new HttpServlet() {
    };
    optionsServlet.init();

    initializeBlackListedUsers();
}

From source file:org.apache.falcon.security.FalconAuthenticationFilter.java

/**
 * Initialize the filter.//from w w  w .  ja  v a2  s .c  om
 *
 * @param filterConfig filter configuration.
 * @throws ServletException thrown if the filter could not be initialized.
 */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    LOG.info("FalconAuthenticationFilter initialization started");
    super.init(filterConfig);

    optionsServlet = new HttpServlet() {
    };
    optionsServlet.init();

    initializeBlackListedUsers();
}

From source file:org.apache.stratos.redirector.servlet.ui.util.Util.java

public static void domainRegisterServlet(BundleContext bundleContext) throws Exception {
    if (!CarbonUtils.isRemoteRegistry()) {
        HttpServlet reirectorServlet = new HttpServlet() {
            // the redirector filter will forward the request before this servlet is hit
            protected void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
            }/*from  ww w .  j ava 2s.  com*/
        };

        Filter redirectorFilter = new AllPagesFilter();

        Dictionary redirectorServletAttributes = new Hashtable(2);
        Dictionary redirectorParams = new Hashtable(2);
        redirectorParams.put("url-pattern", "/" + MultitenantConstants.TENANT_AWARE_URL_PREFIX);
        redirectorParams.put("associated-filter", redirectorFilter);
        redirectorParams.put("servlet-attributes", redirectorServletAttributes);

        redirectorServiceRegistration = bundleContext.registerService(Servlet.class.getName(), reirectorServlet,
                redirectorParams);

    }
}

From source file:org.apache.stratos.sso.redirector.ui.internal.SSORedirectorServiceComponent.java

protected void activate(ComponentContext ctxt) {

    // register a servlet filter for SSO redirector page
    HttpServlet redirectJSPRedirectorServlet = new HttpServlet() {
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        }//w ww .ja  v a  2 s  .  c om
    };

    Filter redirectPageFilter = new RedirectorJSPFilter();
    Dictionary redirectorPageFilterAttrs = new Hashtable(2);
    Dictionary redirectorPageFilterParams = new Hashtable(2);
    redirectorPageFilterParams.put("url-pattern", "/carbon/sso-acs/redirect_ajaxprocessor.jsp");
    redirectorPageFilterParams.put("associated-filter", redirectPageFilter);
    redirectorPageFilterParams.put("servlet-attributes", redirectorPageFilterAttrs);
    ctxt.getBundleContext().registerService(Servlet.class.getName(), redirectJSPRedirectorServlet,
            redirectorPageFilterParams);
    log.debug("Stratos SSO Redirector bundle is activated..");
}

From source file:org.atmosphere.vibe.ProtocolTest.java

@Test
public void protocol() throws Exception {
    final DefaultServer server = new DefaultServer();
    server.onsocket(new Action<ServerSocket>() {
        @Override//  ww  w  .ja v a 2s.  com
        public void on(final ServerSocket socket) {
            socket.on("abort", new VoidAction() {
                @Override
                public void on() {
                    socket.close();
                }
            }).on("echo", new Action<Object>() {
                @Override
                public void on(Object data) {
                    socket.send("echo", data);
                }
            }).on("/reply/inbound", new Action<Reply<Map<String, Object>>>() {
                @Override
                public void on(Reply<Map<String, Object>> reply) {
                    Map<String, Object> data = reply.data();
                    switch ((String) data.get("type")) {
                    case "resolved":
                        reply.resolve(data.get("data"));
                        break;
                    case "rejected":
                        reply.reject(data.get("data"));
                        break;
                    }
                }
            }).on("/reply/outbound", new Action<Map<String, Object>>() {
                @Override
                public void on(Map<String, Object> data) {
                    switch ((String) data.get("type")) {
                    case "resolved":
                        socket.send("test", data.get("data"), new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    case "rejected":
                        socket.send("test", data.get("data"), null, new Action<Object>() {
                            @Override
                            public void on(Object data) {
                                socket.send("done", data);
                            }
                        });
                        break;
                    }
                }
            });
        }
    });
    final HttpTransportServer httpTransportServer = new HttpTransportServer().ontransport(server);
    final WebSocketTransportServer wsTransportServer = new WebSocketTransportServer().ontransport(server);

    org.eclipse.jetty.server.Server jetty = new org.eclipse.jetty.server.Server();
    ServerConnector connector = new ServerConnector(jetty);
    connector.setPort(8000);
    jetty.addConnector(connector);
    ServletContextHandler handler = new ServletContextHandler();
    handler.addEventListener(new ServletContextListener() {
        @Override
        @SuppressWarnings("serial")
        public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();
            // /setup
            ServletRegistration regSetup = context.addServlet("/setup", new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse res)
                        throws ServletException, IOException {
                    Map<String, String[]> params = req.getParameterMap();
                    if (params.containsKey("heartbeat")) {
                        server.setHeartbeat(Integer.parseInt(params.get("heartbeat")[0]));
                    }
                    if (params.containsKey("_heartbeat")) {
                        server.set_heartbeat(Integer.parseInt(params.get("_heartbeat")[0]));
                    }
                }
            });
            regSetup.addMapping("/setup");
            // /vibe
            Servlet servlet = new VibeAtmosphereServlet().onhttp(httpTransportServer)
                    .onwebsocket(wsTransportServer);
            ServletRegistration.Dynamic reg = context.addServlet(VibeAtmosphereServlet.class.getName(),
                    servlet);
            reg.setAsyncSupported(true);
            reg.setInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR, Boolean.TRUE.toString());
            reg.addMapping("/vibe");
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
        }
    });
    jetty.setHandler(handler);
    jetty.start();

    CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node")
            .addArgument("./src/test/resources/runner").addArgument("--vibe.transports")
            .addArgument("websocket,httpstream,httplongpoll");
    DefaultExecutor executor = new DefaultExecutor();
    // The exit value of mocha is the number of failed tests.
    executor.execute(cmdLine);

    jetty.stop();
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

/**
 * This test should also not hit the error servlet as we've only set the
 * status. As per the Servlet spec this should not trigger error handling.
 *///from  w  w  w  .  j a  v a 2 s.c  o m
public void test_ErrorPage6() throws Exception {
    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            response.getWriter().write("Hello!");
            response.setStatus(444);
        }

    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "E6");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/TestErrorPage6/*");
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));
    props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "E6.error");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_ERROR_PAGE, "444");
    registrations.add(getBundleContext().registerService(Servlet.class, new ErrorServlet("444"), props));

    Map<String, List<String>> response = requestAdvisor.request("TestErrorPage6/a", null);

    String responseCode = response.get("responseCode").get(0);
    String responseBody = response.get("responseBody").get(0);

    Assert.assertEquals("444", responseCode);
    Assert.assertNotEquals("444 : 444 : ERROR : /TestErrorPage6/a", responseBody);
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

/**
 * This test should also not hit the error servlet as we've only set the
 * status. As per the Servlet spec this should not trigger error handling.
 *//*ww w . j  a v  a  2s .co  m*/
public void test_ErrorPage7() throws Exception {
    final int status = 422;

    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {

            resp.setStatus(status);

            PrintWriter printWriter = new PrintWriter(resp.getOutputStream());

            printWriter.println("{");
            printWriter.println("error: 'An error message',");
            printWriter.println("code: 'An error code'");
            printWriter.println("}");

            printWriter.flush();
        }
    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "E7");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/TestErrorPage7/*");
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));
    props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "E7.error");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_ERROR_PAGE, String.valueOf(status));
    registrations.add(
            getBundleContext().registerService(Servlet.class, new ErrorServlet(String.valueOf(status)), props));

    Map<String, List<String>> response = requestAdvisor.request("TestErrorPage7/a", null);

    String responseCode = response.get("responseCode").get(0);
    String responseBody = response.get("responseBody").get(0);

    Assert.assertEquals(String.valueOf(status), responseCode);
    Assert.assertNotEquals(status + " : " + status + " : ERROR : /TestErrorPage7/a", responseBody);
}