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:org.apache.sling.discovery.etcd.EtcdServiceTest.java

@Test
public void testGetAllInstancesProperties() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        @Override//w  w  w  . j  a v a 2  s  .  co m
        protected void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            if (!"GET".equals(req.getMethod())) {
                throw new IllegalArgumentException("get all properties requires GET");
            }
            String recursive = req.getParameter("recursive");
            if (recursive == null || "false".equals(recursive)) {
                throw new IllegalArgumentException("recursive must be true");
            }
            res.setStatus(200);
            res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/get-all-properties.json")));
        }
    };
    server = startServer(servlet, "/v2/keys/discovery/properties");
    EtcdService etcdService = buildEtcdService(serverPort(server));
    Map<String, Map<String, String>> properties = etcdService.getInstancesProperties();
    Assert.assertNotNull(properties);
    Assert.assertEquals(2, properties.size());
    Map<String, String> props = properties.get("sling-id");
    Assert.assertNotNull(props);
    Assert.assertEquals(1, props.size());
}

From source file:io.druid.server.AsyncManagementForwardingServletTest.java

private static Server makeTestServer(int port, ExpectedRequest expectedRequest) {
    Server server = new Server(port);
    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(new ServletHolder(new HttpServlet() {
        @Override/*www  . ja va2s .  c om*/
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            handle(req, resp);
        }

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            handle(req, resp);
        }

        @Override
        protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            handle(req, resp);
        }

        @Override
        protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            handle(req, resp);
        }

        private void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            boolean passed = expectedRequest.path.equals(req.getRequestURI());
            passed &= expectedRequest.query == null || expectedRequest.query.equals(req.getQueryString());
            passed &= expectedRequest.method.equals(req.getMethod());

            if (expectedRequest.headers != null) {
                for (Map.Entry<String, String> header : expectedRequest.headers.entrySet()) {
                    passed &= header.getValue().equals(req.getHeader(header.getKey()));
                }
            }

            passed &= expectedRequest.body == null
                    || expectedRequest.body.equals(IOUtils.toString(req.getReader()));

            expectedRequest.called = true;
            resp.setStatus(passed ? 200 : 400);
        }
    }), "/*");

    server.setHandler(handler);
    return server;
}

From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java

@Test
public void testPostRequestFormat() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        @Override/* w w w  . ja  va2  s  . c  om*/
        protected void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            ContentType contentType = ContentType.parse(req.getContentType());
            if (!contentType.getMimeType().equals(EtcdClientImpl.FORM_URLENCODED.getMimeType())) {
                throw new IllegalArgumentException("wrong mime type");
            }
            if (!contentType.getCharset().equals(EtcdClientImpl.FORM_URLENCODED.getCharset())) {
                throw new IllegalArgumentException("wrong content charset");
            }
            String value = req.getParameter("value");
            if (value == null) {
                throw new IllegalArgumentException("missing value parameter");
            }
            String ttl = req.getParameter("ttl");
            if (!"10".equals(ttl)) {
                throw new IllegalArgumentException("missing ttl parameter");
            }
            res.setStatus(201);
            res.getWriter().write(IOUtils.toString(getClass().getResourceAsStream("/action-3.json")));
        }
    };
    server1 = startServer(servlet, "/v2/keys/post/test");
    buildEtcdClient(serverPort(server1));
    KeyResponse response = etcdClient.postKey("/post/test", "test-data", Collections.singletonMap("ttl", "10"));
    Assert.assertNotNull(response);
    Assert.assertTrue(response.isAction());
}

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

@Test
public void testUseDefaultConfiguration2() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override//  w  ww  .ja  v  a2  s.  c  o  m
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("image/jpeg");
            response.addHeader("Cache-Control", "private");

            response.getWriter().print("Hello world");
        }
    };

    int expectedMaxAgeInSeconds = 1 * 60;

    validate(servlet, expectedMaxAgeInSeconds);
}

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

@Test
public void testUseMajorTypeExpiresConfiguration() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override// w  ww.  j  a  va 2 s  . c o  m
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/json; charset=iso-8859-1");
            response.getWriter().print("Hello world");
        }
    };

    int expectedMaxAgeInSeconds = 7 * 60;

    validate(servlet, expectedMaxAgeInSeconds);
}

From source file:org.apache.sling.discovery.etcd.EtcdServiceTest.java

@Test
public void testRefreshAnnounce() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        @Override//  www.ja  v a 2  s  .  co m
        protected void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            if (!"PUT".equals(req.getMethod())) {
                throw new IllegalArgumentException("refresh announce requires PUT");
            }
            String recursive = req.getParameter("prevExist");
            if (recursive == null || "false".equals(recursive)) {
                throw new IllegalArgumentException("prevExist must be true");
            }
            String value = req.getParameter("value");
            if (value == null) {
                throw new IllegalArgumentException("value not specified");
            }
            res.setStatus(200);
            res.getWriter()
                    .write(IOUtils.toString(getClass().getResourceAsStream("/refresh-existing-announce.json")));
        }
    };
    server = startServer(servlet, "/v2/keys/discovery/announces/265");
    EtcdService etcdService = buildEtcdService(serverPort(server));
    AnnounceData annData = new AnnounceData("sling-id-2", "server-info-2", "default-cluster", 1928);
    etcdService.refreshAnnounce("/discovery/announces/265", annData.toString(), 20000);
}

From source file:de.zazaz.iot.bosch.indego.ifttt.IftttIndegoAdapter.java

/**
 * This creates a HTTP server instance for receiving IFTTT commands.
 * //from  ww w  .j a v a 2s.c o m
 * @return the HTTP server instance
 */
private Server buildHttpServer() {
    if (configuration.getIftttReceiverPort() == 0) {
        return null;
    }

    HttpServlet servlet = new HttpServlet() {

        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(HttpServletRequest req_, HttpServletResponse resp_)
                throws ServletException, IOException {
            if (req_.getPathInfo()
                    .startsWith(String.format("/%s/command/", configuration.getIftttReceiverSecret()))) {
                handleIftttCommand(req_, resp_);
                resp_.setContentType("text/html");
                resp_.setStatus(HttpStatus.SC_OK);
            } else {
                super.doGet(req_, resp_);
            }
        }

    };

    Server result = new Server(configuration.getIftttReceiverPort());
    ServletHandler handler = new ServletHandler();
    result.setHandler(handler);
    handler.addServletWithMapping(new ServletHolder(servlet), "/*");
    try {
        result.start();
    } catch (Exception ex) {
        LOG.fatal("Was not able to start the command server", ex);
        return null;
    }

    return result;
}

From source file:org.apache.sling.etcd.client.impl.EtcdClientImplTest.java

@Test
public void testSslServerAndClientAuthenticationWithCustomCA() throws Exception {

    /*/*from w  ww  .j  a va2  s. c  om*/
     * The client JKS keystore containing the client private key and certificate signed by the custom CA.
     */
    String clientKeyStorePath = "/client-keystore.jks";

    /*
     * The client JKS trust store containing the custom CA root certificate.
     */
    String clientTrustStorePath = "/client-truststore.jks";

    /**
     * The server key store containing the CA root certificate as well as the server private key and certificate.
     */
    String serverKeyStorePath = "/server-keystore.jks";

    String pwd = "testit";

    // start the server requiring client certificate

    HttpServlet servlet = new HttpServlet() {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            res.setStatus(200);
            res.getWriter().write("etcd 2.0.6");
        }
    };

    server1 = startSecureServer(servlet, "/version", serverKeyStorePath, pwd);
    int port = serverPort(server1);

    buildSecureEtcdClient(port, clientKeyStorePath, pwd, clientTrustStorePath, pwd);

    VersionResponse version = etcdClient.getVersion(new URI("https://127.0.0.1:" + port));
    Assert.assertEquals("etcd 2.0.6", version.version());
}

From source file:com.serotonin.m2m2.Lifecycle.java

private void webServerInitialize(ClassLoader classLoader) {
    this.SERVER = new Server();

    ServerConnector conn = new ServerConnector(this.SERVER);
    //    SelectChannelConnector conn = new SelectChannelConnector();
    conn.setPort(Common.envProps.getInt("web.port", 8080));
    this.SERVER.addConnector(conn);

    WebAppContext context = new OverridingWebAppContext(classLoader);
    this.SERVER.setHandler(context);

    registerServlets(context);/*from   w w  w .j  av  a  2s .  c  o  m*/
    try {
        this.SERVER.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    configureDwr(context);
    configureUrls(context);

    ServletHolder sh = new ServletHolder(new HttpServlet() {
        private static final long serialVersionUID = 1L;

        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.sendError(403);
        }
    });
    for (Module module : ModuleRegistry.getModules())
        context.addServlet(sh, module.getWebPath() + "/classes/*");
}

From source file:org.apache.sling.discovery.etcd.EtcdServiceTest.java

@Test
public void testGetGzipped() throws Exception {
    HttpServlet servlet = new HttpServlet() {
        @Override//w  ww.j a  v a 2s . co m
        protected void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            String acceptEncoding = req.getHeader("Accept-Encoding");
            if (acceptEncoding != null && acceptEncoding.equalsIgnoreCase("gzip")) {
                res.setHeader("Content-Encoding", "gzip");
                res.setStatus(200);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                GZIPOutputStream gzip = new GZIPOutputStream(out);
                String data = IOUtils.toString(getClass().getResourceAsStream("/get-properties.json"), "UTF-8");
                gzip.write(data.getBytes("UTF-8"));
                gzip.close();
                res.getOutputStream().write(out.toByteArray());
            } else {
                throw new IllegalArgumentException("accept-encoding not found or not gzip");
            }
        }
    };
    server = startServer(servlet, "/v2/keys/discovery/properties/sling-id");
    EtcdService etcdService = buildEtcdService(serverPort(server));
    Map<String, String> properties = etcdService.getProperties("sling-id");
    Assert.assertNotNull(properties);
    Assert.assertEquals(1, properties.size());
}