List of usage examples for javax.servlet.http HttpServlet HttpServlet
public HttpServlet()
From source file:com.thoughtworks.go.agent.testhelper.FakeBootstrapperServer.java
public void start() throws Exception { server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(9090);/*from w ww .j a va2 s .com*/ server.addConnector(connector); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setCertAlias("cruise"); sslContextFactory.setKeyStoreResource(Resource.newClassPathResource("testdata/fake-server-keystore")); sslContextFactory.setKeyStorePassword("serverKeystorepa55w0rd"); ServerConnector secureConnnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(new HttpConfiguration())); secureConnnector.setPort(9091); server.addConnector(secureConnnector); WebAppContext wac = new WebAppContext(".", "/go"); ServletHolder holder = new ServletHolder(); holder.setServlet(new HttpServlet() { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getOutputStream().println("Hello"); } }); wac.addServlet(holder, "/hello"); addFakeAgentBinaryServlet(wac, "/admin/agent", TEST_AGENT); addFakeAgentBinaryServlet(wac, "/admin/agent-launcher.jar", TEST_AGENT_LAUNCHER); addFakeAgentBinaryServlet(wac, "/admin/agent-plugins.zip", TEST_AGENT_PLUGINS); addFakeAgentBinaryServlet(wac, "/admin/tfs-impl.jar", TEST_TFS_IMPL); addlatestAgentStatusCall(wac); addDefaultServlet(wac); server.setHandler(wac); server.setStopAtShutdown(true); server.start(); }
From source file:com.thoughtworks.go.agent.testhelper.FakeGoServer.java
private void start() throws Exception { server = new Server(); ServerConnector connector = new ServerConnector(server); server.addConnector(connector);/* w ww.j a va 2 s. com*/ SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setCertAlias("cruise"); sslContextFactory.setKeyStoreResource(Resource.newClassPathResource("testdata/fake-server-keystore")); sslContextFactory.setKeyStorePassword("serverKeystorepa55w0rd"); ServerConnector secureConnnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(new HttpConfiguration())); server.addConnector(secureConnnector); WebAppContext wac = new WebAppContext(".", "/go"); ServletHolder holder = new ServletHolder(); holder.setServlet(new HttpServlet() { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.getOutputStream().println("Hello"); } }); wac.addServlet(holder, "/hello"); addFakeAgentBinaryServlet(wac, "/admin/agent", TEST_AGENT, this); addFakeAgentBinaryServlet(wac, "/admin/agent-launcher.jar", TEST_AGENT_LAUNCHER, this); addFakeAgentBinaryServlet(wac, "/admin/agent-plugins.zip", TEST_AGENT_PLUGINS, this); addFakeAgentBinaryServlet(wac, "/admin/tfs-impl.jar", TEST_TFS_IMPL, this); addlatestAgentStatusCall(wac); addDefaultServlet(wac); server.setHandler(wac); server.setStopAtShutdown(true); server.start(); port = connector.getLocalPort(); securePort = secureConnnector.getLocalPort(); }
From source file:io.cettia.ProtocolTest.java
@Test public void protocol() throws Exception { final DefaultServer server = new DefaultServer(); server.onsocket(new Action<ServerSocket>() { @Override//from w ww.ja va2s. com public void on(final ServerSocket socket) { log.debug("socket.uri() is {}", socket.uri()); 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); jetty.addConnector(connector); connector.setPort(8000); ServletContextHandler handler = new ServletContextHandler(); jetty.setHandler(handler); handler.addEventListener(new ServletContextListener() { @Override @SuppressWarnings("serial") public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); 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"); // For HTTP transport Servlet servlet = new AsityServlet().onhttp(httpTransportServer); ServletRegistration.Dynamic reg = context.addServlet(AsityServlet.class.getName(), servlet); reg.setAsyncSupported(true); reg.addMapping("/cettia"); } @Override public void contextDestroyed(ServletContextEvent sce) { } }); // For WebSocket transport ServerContainer container = WebSocketServerContainerInitializer.configureContext(handler); ServerEndpointConfig config = ServerEndpointConfig.Builder.create(AsityServerEndpoint.class, "/cettia") .configurator(new Configurator() { @Override public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { return endpointClass.cast(new AsityServerEndpoint().onwebsocket(wsTransportServer)); } }).build(); container.addEndpoint(config); jetty.start(); CommandLine cmdLine = CommandLine.parse("./src/test/resources/node/node") .addArgument("./src/test/resources/runner").addArgument("--cettia.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:com.digitalpebble.storm.crawler.metrics.DebugMetricsConsumer.java
private Server startServlet(int serverPort) throws Exception { // Setup HTTP server Server server = new Server(serverPort); Context root = new Context(server, "/"); server.start();/* w ww. j a v a2 s .c o m*/ HttpServlet servlet = new HttpServlet() { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { SortedMap<String, Number> metrics = ImmutableSortedMap.copyOf(DebugMetricsConsumer.this.metrics); SortedMap<String, Map<String, Object>> metrics_metadata = ImmutableSortedMap .copyOf(DebugMetricsConsumer.this.metrics_metadata); Map<String, Object> toplevel = ImmutableMap.of("retrieved", new Date(), // TODO this call fails with mysterious // exception // "java.lang.IllegalArgumentException: Could not find component common for __metrics" // Mailing list suggests it's a library version // issue but couldn't find anything suspicious // Need to eventually investigate // "sources", // context.getThisSources().toString(), "metrics", metrics, "metric_metadata", metrics_metadata); ObjectWriter prettyPrinter = OM.writerWithDefaultPrettyPrinter(); prettyPrinter.writeValue(resp.getWriter(), toplevel); } }; root.addServlet(new ServletHolder(servlet), "/metrics"); log.info("Started metric server..."); return server; }
From source file:com.github.jrialland.ajpclient.AbstractTomcatTest.java
@SuppressWarnings("serial") protected void addStaticResource(final String mapping, final Path file) { if (!Files.isRegularFile(file)) { final FileNotFoundException fnf = new FileNotFoundException(file.toString()); fnf.fillInStackTrace();/* ww w .jav a 2s. c o m*/ throw new IllegalArgumentException(fnf); } String md5; try { final InputStream is = file.toUri().toURL().openStream(); md5 = computeMd5(is); is.close(); } catch (final Exception e) { throw new RuntimeException(e); } final String fMd5 = md5; addServlet(mapping, new HttpServlet() { @Override protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { resp.setContentLength((int) Files.size(file)); resp.setHeader("Content-MD5", fMd5); final String mime = Files.probeContentType(file); if (mime != null) { resp.setContentType(mime); } final OutputStream out = resp.getOutputStream(); Files.copy(file, out); out.flush(); } }); }
From source file:org.apache.sling.discovery.etcd.EtcdServiceTest.java
@Test public void testSendLocalProperties() throws Exception { HttpServlet servlet = new HttpServlet() { @Override/*from ww w .j a va2 s .c om*/ protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (!"PUT".equals(req.getMethod())) { throw new IllegalArgumentException("send props requires PUT"); } String value = req.getParameter("value"); if (value == null) { throw new IllegalArgumentException("value not specified"); } res.setStatus(201); res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/send-properties.json"))); } }; server = startServer(servlet, "/v2/keys/discovery/properties/sling-id"); EtcdService etcdService = buildEtcdService(serverPort(server)); long lastModified = etcdService.sendInstanceProperties(Collections.singletonMap("n1", "v1"), "sling-id"); Assert.assertEquals(253L, lastModified); }
From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java
@Test public void testGetRedirect() throws Exception { server2 = startServer(new StaticHandler(200, "/action-2.json"), "/v2/keys/redi"); HttpServlet servlet = new HttpServlet() { @Override// w w w .j ava 2 s . com protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setHeader("Location", "http://localhost:" + (serverPort(server2)) + "/v2/keys/redi"); res.setStatus(307); } }; server1 = startServer(servlet, "/v2/keys/test"); buildEtcdClient(serverPort(server1)); KeyResponse response = etcdClient.getKey("/test", EtcdParams.noParams()); Assert.assertTrue(response.isAction()); KeyAction action = response.action(); Assert.assertEquals("get", action.action()); Assert.assertEquals("/test", action.node().key()); }
From source file:fr.xebia.servlet.filter.ExpiresFilterTest.java
/** * Test that a resource with empty content is also processed *//* w ww . j ava 2 s .c o m*/ @Test public void testEmptyContent() throws Exception { HttpServlet servlet = new HttpServlet() { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); // no content is written in the response } }; int expectedMaxAgeInSeconds = 7 * 60; validate(servlet, expectedMaxAgeInSeconds); }
From source file:org.apache.sling.discovery.etcd.EtcdServiceTest.java
@Test public void testGetAnnounces() throws Exception { HttpServlet servlet = new HttpServlet() { @Override//from w w w .j av a 2 s . c om protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (!"GET".equals(req.getMethod())) { throw new IllegalArgumentException("get announces requires GET"); } String recursive = req.getParameter("recursive"); if (recursive == null || "false".equals(recursive)) { throw new IllegalArgumentException("recursive must be true"); } String sorted = req.getParameter("sorted"); if (sorted == null || "false".equals(sorted)) { throw new IllegalArgumentException("sorted must be true"); } res.setStatus(200); res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/get-announces.json"))); } }; server = startServer(servlet, "/v2/keys/discovery/announces"); EtcdService etcdService = buildEtcdService(serverPort(server)); List<EtcdNode> announces = etcdService.getAnnounces(); Assert.assertNotNull(announces); Assert.assertEquals(2, announces.size()); }
From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java
@Test public void testPutKeyWithParameter() throws Exception { HttpServlet servlet = new HttpServlet() { @Override//from ww w. ja v a 2 s .c o m protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String ttl = req.getParameter("ttl"); if ("10".equals(ttl)) { res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/action-1.json"))); } } }; server1 = startServer(servlet, "/v2/keys/test"); buildEtcdClient(serverPort(server1)); KeyResponse response = etcdClient.putKey("/test", "test-data", EtcdParams.builder().ttl(10).build()); Assert.assertTrue(response.isAction()); KeyAction action = response.action(); Assert.assertNotNull(action); }