Java Code Examples for javax.servlet.http.HttpServlet

The following examples show how to use javax.servlet.http.HttpServlet. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: dropwizard-guicey   Source File: WebServletInstaller.java    License: MIT License 6 votes vote down vote up
private void configure(final ServletEnvironment environment, final HttpServlet servlet,
                       final Class<? extends HttpServlet> type, final String name, final WebServlet annotation) {
    final ServletRegistration.Dynamic mapping = environment.addServlet(name, servlet);
    final Set<String> clash = mapping
            .addMapping(annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value());
    if (clash != null && !clash.isEmpty()) {
        final String msg = String.format(
                "Servlet registration %s clash with already installed servlets on paths: %s",
                type.getSimpleName(), Joiner.on(',').join(clash));
        if (option(DenyServletRegistrationWithClash)) {
            throw new IllegalStateException(msg);
        } else {
            logger.warn(msg);
        }
    }
    if (annotation.initParams().length > 0) {
        for (WebInitParam param : annotation.initParams()) {
            mapping.setInitParameter(param.name(), param.value());
        }
    }
    mapping.setAsyncSupported(annotation.asyncSupported());
}
 
Example 2
Source Project: Tomcat8-Source-Read   Source File: TestExpiresFilter.java    License: MIT License 6 votes vote down vote up
@Test
public void testUseContentTypeWithoutCharsetExpiresConfiguration()
        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/xml; charset=iso-8859-1");
            response.getWriter().print("Hello world");
        }
    };

    validate(servlet, Integer.valueOf(5 * 60));
}
 
Example 3
Source Project: Tomcat8-Source-Read   Source File: TestExpiresFilter.java    License: MIT License 6 votes vote down vote up
@Test
public void testUseDefaultConfiguration2() 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("image/jpeg");
            response.addHeader("Cache-Control", "private");

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

    validate(servlet, Integer.valueOf(1 * 60));
}
 
Example 4
Source Project: ignite   Source File: WebSessionSelfTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Starts server with Login Service and create a realm file.
 *
 * @param port Port number.
 * @param cfg Configuration.
 * @param igniteInstanceName Ignite instance name.
 * @param servlet Servlet.
 * @return Server.
 * @throws Exception In case of error.
 */
private Server startServerWithLoginService(
    int port, @Nullable String cfg, @Nullable String igniteInstanceName, HttpServlet servlet
) throws Exception {
    Server srv = new Server(port);

    WebAppContext ctx = getWebContext(cfg, igniteInstanceName, keepBinary(), servlet);

    HashLoginService hashLoginService = new HashLoginService();
    hashLoginService.setName("Test Realm");
    createRealm();
    hashLoginService.setConfig("/tmp/realm.properties");
    ctx.getSecurityHandler().setLoginService(hashLoginService);

    srv.setHandler(ctx);

    srv.start();

    return srv;
}
 
Example 5
Source Project: spring-analysis-note   Source File: ForwardedHeaderFilterTests.java    License: MIT License 6 votes vote down vote up
private String sendRedirect(final String location) throws ServletException, IOException {
	Filter filter = new OncePerRequestFilter() {
		@Override
		protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
				FilterChain chain) throws IOException {

			res.sendRedirect(location);
		}
	};

	MockHttpServletResponse response = new MockHttpServletResponse();
	FilterChain filterChain = new MockFilterChain(mock(HttpServlet.class), this.filter, filter);
	filterChain.doFilter(request, response);

	return response.getRedirectedUrl();
}
 
Example 6
Source Project: incubator-tajo   Source File: HttpServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add an internal servlet in the server, specifying whether or not to
 * protect with Kerberos authentication. 
 * Note: This method is to be used for adding servlets that facilitate
 * internal communication and not for user facing functionality. For
 * servlets added using this method, filters (except internal Kerberized
 * filters) are not enabled. 
 * 
 * @param name The name of the servlet (can be passed as null)
 * @param pathSpec The path spec for the servlet
 * @param clazz The servlet class
 */
public void addInternalServlet(String name, String pathSpec, 
    Class<? extends HttpServlet> clazz, boolean requireAuth) {
  ServletHolder holder = new ServletHolder(clazz);
  if (name != null) {
    holder.setName(name);
  }
  webAppContext.addServlet(holder, pathSpec);
  
  if(requireAuth && UserGroupInformation.isSecurityEnabled()) {
     LOG.info("Adding Kerberos filter to " + name);
     ServletHandler handler = webAppContext.getServletHandler();
     FilterMapping fmap = new FilterMapping();
     fmap.setPathSpec(pathSpec);
     fmap.setFilterName("krb5Filter");
     fmap.setDispatches(Handler.ALL);
     handler.addFilterMapping(fmap);
  }
}
 
Example 7
Source Project: apm-agent-java   Source File: ApmFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testExceptionCapturingShouldContainUserInformationRecordedOnTheTransaction() throws IOException, ServletException {
    filterChain = new MockFilterChain(new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
            tracer.currentTransaction().setUser("id", "email", "username");
            tracer.getActive().captureException(new RuntimeException("Test exception capturing"));
        }
    });

    filterChain.doFilter(new MockHttpServletRequest("GET", "/foo"), new MockHttpServletResponse());
    assertThat(reporter.getTransactions()).hasSize(1);
    assertThat(reporter.getErrors()).hasSize(1);
    assertThat(reporter.getFirstError().getContext().getUser().getId()).isEqualTo("id");
    assertThat(reporter.getFirstError().getContext().getUser().getEmail()).isEqualTo("email");
    assertThat(reporter.getFirstError().getContext().getUser().getUsername()).isEqualTo("username");
}
 
Example 8
Source Project: apm-agent-java   Source File: TestRequestBodyCapturing.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {
    webConfiguration = tracer.getConfig(WebConfiguration.class);
    coreConfiguration = tracer.getConfig(CoreConfiguration.class);
    doReturn(CoreConfiguration.EventType.ALL).when(coreConfiguration).getCaptureBody();
    filterChain = new MockFilterChain(new HttpServlet() {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            final ServletInputStream is = req.getInputStream();
            int read;
            do {
                read = streamConsumer.read(is);
            } while (read != -1);
            streamCloser.close(is);
        }
    });
    streamConsumer = is -> is.readLine(BUFFER, 0, BUFFER.length);
    streamCloser = InputStream::close;

}
 
Example 9
@Override
protected AbstractConfiguration getConfiguration()
{
    final MockServletConfig config = new MockServletConfig();
    config.setInitParameter("key1", "value1");
    config.setInitParameter("key2", "value2");
    config.setInitParameter("list", "value1, value2");
    config.setInitParameter("listesc", "value1\\,value2");

    final Servlet servlet = new HttpServlet() {
        /**
         * Serial version UID.
         */
        private static final long serialVersionUID = 1L;

        @Override
        public ServletConfig getServletConfig()
        {
            return config;
        }
    };

    final ServletConfiguration servletConfiguration = new ServletConfiguration(servlet);
    servletConfiguration.setListDelimiterHandler(new DefaultListDelimiterHandler(','));
    return servletConfiguration;
}
 
Example 10
Source Project: nifi   Source File: ContentLengthFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
private void configureAndStartServer(HttpServlet servlet, int maxFormContentSize) throws Exception {
    serverUnderTest = new Server();
    localConnector = new LocalConnector(serverUnderTest);
    localConnector.setIdleTimeout(SERVER_IDLE_TIMEOUT);
    serverUnderTest.addConnector(localConnector);

    contextUnderTest = new ServletContextHandler(serverUnderTest, "/");
    if (maxFormContentSize > 0) {
        contextUnderTest.setMaxFormContentSize(maxFormContentSize);
    }
    contextUnderTest.addServlet(new ServletHolder(servlet), "/*");

    // This only adds the ContentLengthFilter if a valid maxFormContentSize is not provided
    if (maxFormContentSize < 0) {
        FilterHolder holder = contextUnderTest.addFilter(ContentLengthFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        holder.setInitParameter(ContentLengthFilter.MAX_LENGTH_INIT_PARAM, String.valueOf(MAX_CONTENT_LENGTH));
    }
    serverUnderTest.start();
}
 
Example 11
Source Project: micrometer   Source File: TomcatMetricsTest.java    License: Apache License 2.0 6 votes vote down vote up
void runTomcat(HttpServlet servlet, Callable<Void> doWithTomcat) throws Exception {
    Tomcat server = new Tomcat();
    try {
        StandardHost host = new StandardHost();
        host.setName("localhost");
        server.setHost(host);
        server.setPort(0);
        server.start();

        this.port = server.getConnector().getLocalPort();

        Context context = server.addContext("", null);
        server.addServlet("", "servletname", servlet);
        context.addServletMappingDecoded("/", "servletname");

        doWithTomcat.call();

    } finally {
        server.stop();
        server.destroy();

    }
}
 
Example 12
Source Project: nifi   Source File: ContentLengthFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestsWithMissingContentLengthHeader() throws Exception {
    configureAndStartServer(new HttpServlet() {
        @Override
        public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletInputStream input = req.getInputStream();
            while (!input.isFinished()) {
                input.read();
            }
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }, -1);

    // This shows that the ContentLengthFilter allows a request that does not have a content-length header.
    String response = localConnector.getResponse("POST / HTTP/1.0\r\n\r\n");
    Assert.assertFalse(StringUtils.containsIgnoreCase(response, "411 Length Required"));
}
 
Example 13
Source Project: Tomcat7.0.67   Source File: TestExpiresFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSkipBecauseExpiresIsDefined() 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/xml; charset=utf-8");
            response.addDateHeader("Expires", System.currentTimeMillis());
            response.getWriter().print("Hello world");
        }
    };

    validate(servlet, null);
}
 
Example 14
Source Project: tomcatsrc   Source File: TestExpiresFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSkipBecauseCacheControlMaxAgeIsDefined() 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/xml; charset=utf-8");
            response.addHeader("Cache-Control", "private, max-age=232");
            response.getWriter().print("Hello world");
        }
    };

    validate(servlet, Integer.valueOf(232));
}
 
Example 15
Source Project: Whack   Source File: ComponentServlet.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handles a request for a JSP page. It checks to see if a servlet is mapped
 * for the JSP URL. If one is found, request handling is passed to it. If no
 * servlet is found, a 404 error is returned.
 *
 * @param pathInfo the extra path info.
 * @param request  the request object.
 * @param response the response object.
 * @throws ServletException if a servlet exception occurs while handling the
 *                          request.
 * @throws IOException      if an IOException occurs while handling the request.
 */
private void handleJSP(String pathInfo, HttpServletRequest request,
                       HttpServletResponse response) throws ServletException, IOException {
    // Strip the starting "/" from the path to find the JSP URL.
    String jspURL = pathInfo.substring(1);
    HttpServlet servlet = servlets.get(jspURL);
    if (servlet != null) {
        servlet.service(request, response);
        return;
    }
    else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
}
 
Example 16
Source Project: nomulus   Source File: ServletWrapperDelegatorServlet.java    License: Apache License 2.0 5 votes vote down vote up
ServletWrapperDelegatorServlet(
    Class<? extends HttpServlet> servletClass,
    ImmutableList<Class<? extends Filter>> filterClasses,
    Queue<FutureTask<Void>> requestQueue) {
  this.servletClass = servletClass;
  this.filterClasses = filterClasses;
  this.requestQueue = checkNotNull(requestQueue, "requestQueue");
}
 
Example 17
Source Project: sensorhub   Source File: HttpServer.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public synchronized void undeployServlet(HttpServlet servlet)
{
    try
    {
        // there is no removeServlet method so we need to do it manually
        ServletHandler handler = servletHandler.getServletHandler();
        
        // first collect servlets we want to keep
        List<ServletHolder> servlets = new ArrayList<ServletHolder>();
        String nameToRemove = null;
        for( ServletHolder holder : handler.getServlets() )
        {
            if (holder.getServlet() != servlet)
                servlets.add(holder);
            else
                nameToRemove = holder.getName();
        }

        if (nameToRemove == null)
            return;
        
        // also update servlet path mappings
        List<ServletMapping> mappings = new ArrayList<ServletMapping>();
        for (ServletMapping mapping : handler.getServletMappings())
        {
            if (!nameToRemove.contains(mapping.getServletName()))
                mappings.add(mapping);
        }

        // set the new configuration
        handler.setServletMappings( mappings.toArray(new ServletMapping[0]) );
        handler.setServlets( servlets.toArray(new ServletHolder[0]) );
    }
    catch (ServletException e)
    {
        log.error("Error while undeploying servlet", e);
    }       
}
 
Example 18
Source Project: knox   Source File: HttpServer2.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add an internal servlet in the server, with initialization parameters.
 * Note: This method is to be used for adding servlets that facilitate
 * internal communication and not for user facing functionality. For
 * servlets added using this method, filters (except internal Kerberos
 * filters) are not enabled.
 *
 * @param name The name of the servlet (can be passed as null)
 * @param pathSpec The path spec for the servlet
 * @param clazz The servlet class
 * @param params init parameters
 */
public void addInternalServlet(String name, String pathSpec,
                               Class<? extends HttpServlet> clazz, Map<String, String> params) {
  // Jetty doesn't like the same path spec mapping to different servlets, so
  // if there's already a mapping for this pathSpec, remove it and assume that
  // the newest one is the one we want
  final ServletHolder sh = new ServletHolder(clazz);
  sh.setName(name);
  sh.setInitParameters(params);
  final ServletMapping[] servletMappings =
      webAppContext.getServletHandler().getServletMappings();
  for (ServletMapping servletMapping : servletMappings) {
    if (servletMapping.containsPathSpec(pathSpec)) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Found existing " + servletMapping.getServletName() +
                      " servlet at path " + pathSpec + "; will replace mapping" +
                      " with " + sh.getName() + " servlet");
      }
      ServletMapping[] newServletMappings =
          ArrayUtil.removeFromArray(servletMappings, servletMapping);
      webAppContext.getServletHandler()
          .setServletMappings(newServletMappings);
      break;
    }
  }
  webAppContext.addServlet(sh, pathSpec);
}
 
Example 19
Source Project: dagger-servlet   Source File: ServletDefinition.java    License: Apache License 2.0 5 votes vote down vote up
ServletDefinition(String pattern, Class<? extends HttpServlet> servletClass, UriPatternMatcher patternMatcher,
                  Map<String, String> initParams, HttpServlet servletInstance) {
    this.pattern = pattern;
    this.servletClass = servletClass;
    this.patternMatcher = patternMatcher;
    this.initParams = Collections.unmodifiableMap(Maps.newHashMap(initParams));
    this.servletInstance = servletInstance;
}
 
Example 20
Source Project: dropwizard-jaxws   Source File: JAXWSBundleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    when(environment.servlets()).thenReturn(servletEnvironment);
    when(environment.lifecycle()).thenReturn(lifecycleEnvironment);
    when(bootstrap.getMetricRegistry()).thenReturn(mock(MetricRegistry.class));
    when(servletEnvironment.addServlet(anyString(), any(HttpServlet.class))).thenReturn(servlet);
    when(jaxwsEnvironment.buildServlet()).thenReturn(mock(HttpServlet.class));
    when(jaxwsEnvironment.getDefaultPath()).thenReturn("/soap");
}
 
Example 21
Source Project: spring-analysis-note   Source File: ForwardedHeaderFilterTests.java    License: MIT License 5 votes vote down vote up
@Before
@SuppressWarnings("serial")
public void setup() throws Exception {
	this.request = new MockHttpServletRequest();
	this.request.setScheme("http");
	this.request.setServerName("localhost");
	this.request.setServerPort(80);
	this.filterChain = new MockFilterChain(new HttpServlet() {});
}
 
Example 22
Source Project: java-technology-stack   Source File: ForwardedHeaderFilterTests.java    License: MIT License 5 votes vote down vote up
@Before
@SuppressWarnings("serial")
public void setup() throws Exception {
	this.request = new MockHttpServletRequest();
	this.request.setScheme("http");
	this.request.setServerName("localhost");
	this.request.setServerPort(80);
	this.filterChain = new MockFilterChain(new HttpServlet() {});
}
 
Example 23
Source Project: cxf   Source File: ServletControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    req = EasyMock.createMock(HttpServletRequest.class);
    res = EasyMock.createMock(HttpServletResponse.class);
    registry = EasyMock.createMock(DestinationRegistry.class);
    serviceListGenerator = EasyMock.createMock(HttpServlet.class);
}
 
Example 24
Source Project: dagger-servlet   Source File: ServletDefinitionPathsTest.java    License: Apache License 2.0 5 votes vote down vote up
private void servletPath(final String requestPath, String mapping,
                         final String expectedServletPath) throws IOException, ServletException {
    ObjectGraph objectGraph = createMock(ObjectGraph.class);

    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);

    final boolean[] run = new boolean[1];
    //get an instance of this servlet
    expect(objectGraph.get(HttpServlet.class))
            .andReturn(new HttpServlet() {

                @Override
                protected void service(HttpServletRequest servletRequest,
                                       HttpServletResponse httpServletResponse) throws ServletException, IOException {

                    final String path = servletRequest.getServletPath();
                    assertEquals(path, expectedServletPath,
                            String.format("expected [%s] but was [%s]", expectedServletPath, path));
                    run[0] = true;
                }
            });

    expect(request.getServletPath())
            .andReturn(requestPath);

    replay(objectGraph, request);

    ServletDefinition servletDefinition = new ServletDefinition(mapping, HttpServlet.class,
            UriPatternType.get(UriPatternType.SERVLET, mapping), new HashMap<String, String>(), null);

    servletDefinition.init(null, objectGraph,
            Sets.newSetFromMap(Maps.<HttpServlet, Boolean>newIdentityHashMap()));
    servletDefinition.doService(request, response);

    assertTrue(run[0], "Servlet did not run!");

    verify(objectGraph, request);

}
 
Example 25
Source Project: apm-agent-java   Source File: ApmFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testExceptionCapturingShouldContainContextInformation() throws IOException, ServletException {
    filterChain = new MockFilterChain(new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
            tracer.getActive().captureException(new RuntimeException("Test exception capturing"));
        }
    });

    filterChain.doFilter(new MockHttpServletRequest("GET", "/foo"), new MockHttpServletResponse());
    assertThat(reporter.getTransactions()).hasSize(1);
    assertThat(reporter.getErrors()).hasSize(1);
    assertThat(reporter.getFirstError().getContext().getRequest().getUrl().getPathname()).isEqualTo("/foo");
    assertThat(reporter.getFirstError().getTraceContext().isChildOf(reporter.getFirstTransaction().getTraceContext())).isTrue();
}
 
Example 26
Source Project: incubator-retired-wave   Source File: ServerRpcProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add a servlet to the servlet registry. This servlet will be attached to the
 * specified URL pattern when the server is started up.
 *
 * @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'.
 * @param servlet the servlet class to bind to the specified paths.
 * @param initParams the map with init params, can be null or empty.
 * @return the {@link ServletHolder} that holds the servlet.
 */
public ServletHolder addServlet(String urlPattern, Class<? extends HttpServlet> servlet,
    @Nullable Map<String, String> initParams) {
  ServletHolder servletHolder = new ServletHolder(servlet);
  if (initParams != null) {
    servletHolder.setInitParameters(initParams);
  }
  servletRegistry.add(Pair.of(urlPattern, servletHolder));
  return servletHolder;
}
 
Example 27
protected String getServletParameter(HttpServlet servlet, String parameterName) {
    String parameterValue = servlet.getInitParameter(parameterName);
    if (parameterValue == null) {
        parameterValue = servlet.getServletContext().getInitParameter(parameterName);
    }

    return parameterValue;
}
 
Example 28
Source Project: hasor   Source File: WebApiBinder.java    License: Apache License 2.0 5 votes vote down vote up
/** 加载带有 @MappingTo 注解的类。 */
public default WebApiBinder loadMappingTo(Class<?> mappingType, final TypeSupplier typeSupplier) {
    Objects.requireNonNull(mappingType, "class is null.");
    int modifier = mappingType.getModifiers();
    if (AsmTools.checkOr(modifier, Modifier.INTERFACE, Modifier.ABSTRACT) || mappingType.isArray() || mappingType.isEnum()) {
        throw new IllegalStateException(mappingType.getName() + " must be normal Bean");
    }
    MappingTo[] annotationsByType = mappingType.getAnnotationsByType(MappingTo.class);
    if (annotationsByType == null || annotationsByType.length == 0) {
        throw new IllegalStateException(mappingType.getName() + " must be configure @MappingTo");
    }
    //
    if (HttpServlet.class.isAssignableFrom(mappingType)) {
        final Class<? extends HttpServlet> httpServletType = (Class<HttpServlet>) mappingType;
        Arrays.stream(annotationsByType).peek(mappingTo -> {
        }).forEach(mappingTo -> {
            if (!isSingleton(mappingType)) {
                throw new IllegalStateException("HttpServlet " + mappingType + " must be Singleton.");
            }
            if (typeSupplier != null) {
                jeeServlet(mappingTo.value()).with(() -> typeSupplier.get(httpServletType));
            } else {
                jeeServlet(mappingTo.value()).with(httpServletType);
            }
        });
    } else {
        final Class<Object> mappingObjType = (Class<Object>) mappingType;
        Arrays.stream(annotationsByType).peek(mappingTo -> {
        }).forEach(mappingTo -> {
            if (typeSupplier != null) {
                mappingTo(mappingTo.value()).with(mappingObjType, () -> typeSupplier.get(mappingObjType));
            } else {
                mappingTo(mappingTo.value()).with(mappingType);
            }
        });
    }
    return this;
}
 
Example 29
Source Project: dagger-servlet   Source File: ManagedServletPipeline.java    License: Apache License 2.0 5 votes vote down vote up
public void destroy() {
    Set<HttpServlet> destroyedSoFar
            = Sets.newSetFromMap(Maps.<HttpServlet, Boolean>newIdentityHashMap());
    for (ServletDefinition servletDefinition : servletDefinitions) {
        servletDefinition.destroy(destroyedSoFar);
    }
}
 
Example 30
Source Project: micrometer   Source File: TomcatMetricsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void mbeansAvailableAfterBinder() throws Exception {
    TomcatMetrics.monitor(registry, null);

    CountDownLatch latch = new CountDownLatch(1);
    registry.config().onMeterAdded(m -> {
        if (m.getId().getName().equals("tomcat.global.received"))
            latch.countDown();
    });

    HttpServlet servlet = new HttpServlet() {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            IOUtils.toString(req.getInputStream());
            sleep();
            resp.getOutputStream().write("yes".getBytes());
        }
    };

    runTomcat(servlet, () -> {
        assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();

        checkMbeansInitialState();

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost post = new HttpPost("http://localhost:" + this.port + "/");
            post.setEntity(new StringEntity("you there?"));
            CloseableHttpResponse response1 = httpClient.execute(post);

            CloseableHttpResponse response2 = httpClient.execute(
                    new HttpGet("http://localhost:" + this.port + "/nowhere"));

            long expectedSentBytes = response1.getEntity().getContentLength()
                    + response2.getEntity().getContentLength();
            checkMbeansAfterRequests(expectedSentBytes);
        }

        return null;
    });
}