javax.servlet.http.HttpServlet Java Examples

The following examples show how to use javax.servlet.http.HttpServlet. 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 File: ApmFilterTest.java    From apm-agent-java with 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 #2
Source File: ForwardedHeaderFilterTests.java    From spring-analysis-note with 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 #3
Source File: HttpServer.java    From incubator-tajo with 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 #4
Source File: TestExpiresFilter.java    From Tomcat7.0.67 with 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 #5
Source File: ContentLengthFilterTest.java    From nifi with 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 #6
Source File: TestExpiresFilter.java    From tomcatsrc with 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 #7
Source File: TomcatMetricsTest.java    From micrometer with 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 #8
Source File: ContentLengthFilterTest.java    From nifi with 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 #9
Source File: WebSessionSelfTest.java    From ignite with 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 #10
Source File: TestExpiresFilter.java    From Tomcat8-Source-Read with 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 #11
Source File: TestExpiresFilter.java    From Tomcat8-Source-Read with 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 #12
Source File: WebServletInstaller.java    From dropwizard-guicey with 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 #13
Source File: TestRequestBodyCapturing.java    From apm-agent-java with 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 #14
Source File: TestServletConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: HttpServer.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
/**
 * Add an internal servlet in the server.
 * @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
 * @deprecated this is a temporary method
 */
@Deprecated
public void addInternalServlet(String name, String pathSpec,
    Class<? extends HttpServlet> clazz) {
  ServletHolder holder = new ServletHolder(clazz);
  if (name != null) {
    holder.setName(name);
  }
  webAppContext.addServlet(holder, pathSpec);
}
 
Example #16
Source File: ServletWrapperDelegatorServlet.java    From nomulus with 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 File: FakeGoServer.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void start() throws Exception {
    server = new Server();
    ServerConnector connector = new ServerConnector(server);
    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())
    );
    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();
}
 
Example #18
Source File: GerritRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
public String startJetty(Class<? extends HttpServlet> loginServletClass) throws Exception {
    Server server = new Server(0);

    ResourceHandler resourceHandler = new ResourceHandler();
    MimeTypes mimeTypes = new MimeTypes();
    mimeTypes.addMimeMapping("json", "application/json");
    resourceHandler.setMimeTypes(mimeTypes);
    URL url = this.getClass().getResource(".");
    resourceHandler.setBaseResource(new FileResource(url));
    resourceHandler.setWelcomeFiles(new String[] {"changes.json", "projects.json", "account.json"});

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.addServlet(loginServletClass, "/login/");

    ServletContextHandler basicAuthContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
    basicAuthContextHandler.setSecurityHandler(basicAuth("foo", "bar", "Gerrit Auth"));
    basicAuthContextHandler.setContextPath("/a");

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {
        servletContextHandler,
        resourceHandler,
        basicAuthContextHandler
    });
    server.setHandler(handlers);

    server.start();

    Connector connector = server.getConnectors()[0];
    String host = "localhost";
    int port = connector.getLocalPort();
    return String.format("http://%s:%s", host, port);
}
 
Example #19
Source File: InvokerWebApiBinder.java    From hasor with Apache License 2.0 5 votes vote down vote up
/** HttpServlet 转换为 MappingTo 形式 */
protected void jeeServlet(int index, String pattern, BindInfo<? extends HttpServlet> servletRegister, Map<String, String> initParams) {
    if (!this.isSingleton(servletRegister)) {
        throw new IllegalStateException("HttpServlet must be Singleton.");
    }
    OneConfig oneConfig = new OneConfig(servletRegister.getBindID(), initParams, getProvider(AppContext.class));
    Supplier<? extends Servlet> j2eeServlet = getProvider(servletRegister);
    mappingTo(pattern).with(index, new J2eeServletAsMapping(oneConfig, j2eeServlet));
}
 
Example #20
Source File: VelocityWrapper.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public VelocityWrapper(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response) {
	engine = (VelocityEngine) servlet.getServletContext().getAttribute(VELOCITY_ENGINE_INSTANCE);
	// TODO: Init context with default variables shared by all/many servlets
	Context defaultContext = (Context) servlet.getServletContext().getAttribute(VELOCITY_DEFAULT_CONTEXT);
	context = new VelocityContext(defaultContext);
	this.request = request;
	this.response = response;
}
 
Example #21
Source File: ComponentServlet.java    From Whack with Apache License 2.0 5 votes vote down vote up
/**
 * Handles a request for a Servlet. 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 handleServlet(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 #22
Source File: ExpandServer.java    From grain with MIT License 5 votes vote down vote up
@Override
public void init(HttpServlet servlet) throws Exception {
	HttpManager.addMapping("1", GetTokenC.class, GetTokenS.class);
	HttpManager.addMapping("2", GetTokenC.class, GetTokenS.class);
	HttpManager.addMapping("3", GetTokenC.class, GetTokenS.class);
	HttpManager.addMapping("4", GetTokenC.class, GetTokenS.class);
	HttpManager.addMapping("5", GetTokenC.class, GetTokenS.class);
	HttpManager.addMapping("6", GetTokenC.class, GetTokenS.class);
	TestHttpService testHttpService = new TestHttpService();
	HttpManager.addHttpListener(testHttpService);

}
 
Example #23
Source File: WebApps.java    From big-c with Apache License 2.0 5 votes vote down vote up
public Builder<T> withServlet(String name, String pathSpec, 
    Class<? extends HttpServlet> servlet) {
  ServletStruct struct = new ServletStruct();
  struct.clazz = servlet;
  struct.name = name;
  struct.spec = pathSpec;
  servlets.add(struct);
  return this;
}
 
Example #24
Source File: ShiroKerberosAuthenticationFilterTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  subject = createMock(Subject.class);
  mockServlet = createMock(HttpServlet.class);

  filter = new ShiroKerberosAuthenticationFilter(Providers.of(subject));
}
 
Example #25
Source File: HttpServer2.java    From knox with Apache License 2.0 5 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 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 requireAuth Require Kerberos authenticate to access servlet
 */
public void addInternalServlet(String name, String pathSpec,
                               Class<? extends HttpServlet> clazz, boolean requireAuth) {
  ServletHolder holder = new ServletHolder(clazz);
  if (name != null) {
    holder.setName(name);
  }
  // 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 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 " + holder.getName() + " servlet");
      }
      ServletMapping[] newServletMappings =
          ArrayUtil.removeFromArray(servletMappings, servletMapping);
      webAppContext.getServletHandler()
          .setServletMappings(newServletMappings);
      break;
    }
  }
  webAppContext.addServlet(holder, pathSpec);

  if(requireAuth && UserGroupInformation.isSecurityEnabled()) {
    LOG.info("Adding Kerberos (SPNEGO) filter to " + name);
    ServletHandler handler = webAppContext.getServletHandler();
    FilterMapping fmap = new FilterMapping();
    fmap.setPathSpec(pathSpec);
    fmap.setFilterName(SPNEGO_FILTER);
    fmap.setDispatches(FilterMapping.ALL);
    handler.addFilterMapping(fmap);
  }
}
 
Example #26
Source File: ServerRpcProvider.java    From incubator-retired-wave with 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
Source File: RootServlet.java    From reinvent2013-mobile-photo-share with Apache License 2.0 5 votes vote down vote up
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 File: WebApiBinder.java    From hasor with 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 File: TomcatMetricsTest.java    From micrometer with 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;
    });
}
 
Example #30
Source File: ManagedServletPipeline.java    From dagger-servlet with 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);
    }
}