Java 类org.eclipse.jetty.server.handler.StatisticsHandler 实例源码

项目:Patterdale    文件:RegisterExporters.java   
/**
 * @param registry Prometheus CollectorRegistry to register the default exporters.
 * @param httpPort The port the Server runs on.
 * @return a Jetty Server with Prometheus' default exporters registered.
 */
public static Server serverWithStatisticsCollection(CollectorRegistry registry, int httpPort) {
    Server server = new Server(httpPort);

    new StandardExports().register(registry);
    new MemoryPoolsExports().register(registry);
    new GarbageCollectorExports().register(registry);
    new ThreadExports().register(registry);
    new ClassLoadingExports().register(registry);
    new VersionInfoExports().register(registry);

    HandlerCollection handlers = new HandlerCollection();
    StatisticsHandler statisticsHandler = new StatisticsHandler();
    statisticsHandler.setServer(server);
    handlers.addHandler(statisticsHandler);

    new JettyStatisticsCollector(statisticsHandler).register();
    server.setHandler(handlers);

    return server;
}
项目:microservice-mock    文件:StatsCommand.java   
/**
 * Auxiliary method that reports the statistics. Note that the StatisticsHandler is fetched from the Registry,
 * which is in fact a Jetty component.
 *
 * @param exchange
 *  The Camel Exchange associated with the report/stats. When the type is 'html' the report is generated in HTML
 *  format, otherwise a custom String is returned.
 *
 * @return
 *  The result of the stats command.
 */
@Override
public ResponseContext executeCommand(Exchange exchange) {
    LOGGER.debug("Stats command called...");
    Map<String, Object> commands = exchange.getIn().getHeaders();
    String type = (String) commands.get(STATS);
    ResponseContext responseContext = new ResponseContext();
    StatisticsHandler statisticsHandler = MockRegistry.findStatisticsHandler();
    if (statisticsHandler != null) {
        switch (type.toUpperCase()) {
            case "HTML":
                responseContext.setResponse(statisticsHandler.toStatsHTML());
                responseContext.setContentType(ResponseContext.HTML_CONTENT_TYPE);
                break;
            default:
                responseContext.setResponse(statisticsAsString(statisticsHandler));
                responseContext.setContentType(ResponseContext.PLAIN_TEXT_CONTENT_TYPE);
                break;
        }
    } else {
        responseContext.setResponse("Unable to retrieve statistics (no handler configured)");
        responseContext.setErrorCode(String.valueOf(HttpURLConnection.HTTP_NOT_FOUND));
    }
    return responseContext;
}
项目:microservice-mock    文件:ResetCommand.java   
/**
 * Auxiliary method that resets the statistics. Note that the StatisticsHandler is fetched from the Registry, which
 * is in fact a Jetty component.
 *
 * @return
 *  The result of the reset command.
 */
@Override
public ResponseContext executeCommand(Exchange exchange) {
    LOGGER.debug("Reset command called...");
    ResponseContext responseContext = new ResponseContext();
    responseContext.setContentType(ResponseContext.PLAIN_TEXT_CONTENT_TYPE);
    StatisticsHandler statisticsHandler = MockRegistry.findStatisticsHandler();
    if (statisticsHandler != null) {
        statisticsHandler.statsReset();
        responseContext.setResponse("Statistics has been reset");
    } else {
        responseContext.setResponse("Unable to retrieve statistics (no handler configured)");
        responseContext.setErrorCode(String.valueOf(HttpURLConnection.HTTP_NOT_FOUND));
    }
    return responseContext;
}
项目:KeyServer    文件:StatusController.java   
/**
 * This method shows a formated message with Jetty statistics elements.
 * @param statistics Jetty statistics object.
 * @since v0.4.0
 */
public static void showKsStats(StatisticsHandler statistics) {
    System.out.println("\n"
            + "                         - Connection Status -\n"
            + "                         ---------------------\n"
            + "  Stats" + "\n"
            + "  -----" + "\n"
            + "   - Total dispatched: " + statistics.getDispatched() +"\n"
            + "   - Current dispatches active: " + statistics.getDispatchedActive() +"\n"
            + "   - Current active requests: " + statistics.getRequestsActive() +"\n"
            + "   - Max number of dispatched: " + statistics.getDispatchedActiveMax() +"\n"
            + "   - Request dispatch time (Max / Mean): " + statistics.getDispatchedTimeMax() + "ms / "+ statistics.getDispatchedTimeMean() +"ms\n"
            + "   - Number of requests expired while suspended: " + statistics.getExpires() +"\n"
            + "   - Dispatched request time (Max / Mean): " + statistics.getRequestTimeMax() + "ms / "+ statistics.getRequestTimeMean() +"ms\n"
            + "   - Total request handled: " + statistics.getRequests() +"\n"
            + "   - Maximum number of active requests: " + statistics.getRequestsActiveMax() +"\n\n"
            + "  HTTP Response Status Codes" + "\n"
            + "  --------------------------" + "\n"
            + "   - 1xx (Informational):\t" + statistics.getResponses1xx() + "\n"
            + "   - 2xx (Success):\t\t" + statistics.getResponses2xx() + "\n"
            + "   - 3xx (Redirection):\t\t" + statistics.getResponses3xx() + "\n"
            + "   - 4xx (Client Error):\t" + statistics.getResponses4xx() + "\n"
            + "   - 5xx (Server Error):\t" + statistics.getResponses5xx() + "\n");
}
项目:OHMS    文件:JettyMonitorUtil.java   
@SuppressWarnings( "deprecation" )
public static ServerComponentEvent getServerMeanResponseTime()
{

    ServerComponentEvent sensor = new ServerComponentEvent();

    sensor.setComponentId( "HMS_OOB_AGENT_RESTHANDLER" );
    sensor.setUnit( EventUnitType.DISCRETE );
    if ( statHandler != null && statHandler instanceof StatisticsHandler )
    {
        sensor.setDiscreteValue( String.valueOf( ( (StatisticsHandler) statHandler ).getDispatchedTimeMean() ) );
    }

    sensor.setEventName( NodeEvent.HMS_OOB_AGENT_RESTHANDLER_MEAN_RESPONSETIME );

    return sensor;
}
项目:OHMS    文件:JettyMonitorUtil.java   
@SuppressWarnings( "deprecation" )
public static ServerComponentEvent getIncomingMessagesCount()
{
    ServerComponentEvent sensor = new ServerComponentEvent();

    sensor.setComponentId( "HMS_OOB_AGENT_RESTHANDLER" );
    sensor.setUnit( EventUnitType.OTHER );
    if ( statHandler != null && statHandler instanceof StatisticsHandler )
    {
        sensor.setValue( ( (StatisticsHandler) statHandler ).getRequests() );
    }

    sensor.setEventName( NodeEvent.HMS_OOB_AGENT_RESTHANDLER_MESSAGE_IN_COUNT );

    return sensor;
}
项目:OHMS    文件:JettyMonitorUtil.java   
@SuppressWarnings( "deprecation" )
public static ServerComponentEvent getOutgoingMessagesCount()
{
    ServerComponentEvent sensor = new ServerComponentEvent();

    sensor.setComponentId( "HMS_OOB_AGENT_RESTHANDLER" );
    sensor.setUnit( EventUnitType.OTHER );
    if ( statHandler != null && statHandler instanceof StatisticsHandler )
    {
        StatisticsHandler handler = (StatisticsHandler) statHandler;
        int responseCount = handler.getResponses1xx() + handler.getResponses2xx() + handler.getResponses3xx()
            + handler.getResponses4xx() + handler.getResponses5xx();
        sensor.setValue( responseCount );
    }

    sensor.setEventName( NodeEvent.HMS_OOB_AGENT_RESTHANDLER_MESSAGE_OUT_COUNT );

    return sensor;
}
项目:vespa    文件:JettyHttpServer.java   
@SuppressWarnings("deprecation")
private void setServerMetrics(StatisticsHandler statistics) {
    long timeSinceStarted = System.currentTimeMillis() - timeStarted;
    metric.set(Metrics.STARTED_MILLIS, timeSinceStarted, null);
    metric.set(Metrics.MANHATTAN_STARTED_MILLIS, timeSinceStarted, null);

    metric.add(Metrics.RESPONSES_1XX, statistics.getResponses1xx(), null);
    metric.add(Metrics.RESPONSES_2XX, statistics.getResponses2xx(), null);
    metric.add(Metrics.RESPONSES_3XX, statistics.getResponses3xx(), null);
    metric.add(Metrics.RESPONSES_4XX, statistics.getResponses4xx(), null);
    metric.add(Metrics.RESPONSES_5XX, statistics.getResponses5xx(), null);

    // Reset to only add the diff for count metrics.
    // (The alternative to reset would be to preserve the previous value, and only add the diff.)
    statistics.statsReset();
}
项目:bigdataviewer-server    文件:ManagerHandler.java   
public ManagerHandler(
        final String baseURL,
        final Server server,
        final ConnectorStatistics connectorStats,
        final StatisticsHandler statHandler,
        final ContextHandlerCollection handlers,
        final String thumbnailsDirectoryName )
                throws IOException, URISyntaxException
{
    this.baseURL = baseURL;
    this.server = server;
    this.handlers = handlers;
    this.statHandler = statHandler;
    this.connectorStats = connectorStats;
    this.thumbnailsDirectoryName = thumbnailsDirectoryName;
    setContextPath( "/" + Constants.MANAGER_CONTEXT_NAME );
}
项目:client_java    文件:JettyStatisticsCollectorTest.java   
@Before
public void setUp() throws Exception {
  server.addConnector(connector);
  HandlerCollection handlers = new HandlerCollection();

  ServletContextHandler context = new ServletContextHandler();
  context.setContextPath("/");
  handlers.setHandlers(new Handler[]{context});

  StatisticsHandler stats = new StatisticsHandler();
  stats.setHandler(handlers);
  server.setHandler(stats);

  // register collector
  new JettyStatisticsCollector(stats).register();

  server.setHandler(stats);
  server.start();
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
@Override
public void bindTo(MeterRegistry reg) {
    bindTimer(reg,"jetty.requests", "Request duration", StatisticsHandler::getRequests, StatisticsHandler::getRequestTimeTotal);
    bindTimer(reg,"jetty.dispatched", "Dispatch duration", StatisticsHandler::getDispatched, StatisticsHandler::getDispatchedTimeTotal);

    bindCounter(reg,"jetty.async.requests", "Total number of async requests", StatisticsHandler::getAsyncRequests);
    bindCounter(reg,"jetty.async.dispatches", "Total number of requests that have been asynchronously dispatched", StatisticsHandler::getAsyncDispatches);
    bindCounter(reg,"jetty.async.expires", "Total number of async requests that have expired", StatisticsHandler::getExpires);
    FunctionCounter.builder("jetty.responses.size", statisticsHandler, StatisticsHandler::getResponsesBytesTotal)
        .description("Total number of bytes across all responses")
        .baseUnit("bytes")
        .register(reg);

    bindGauge(reg,"jetty.requests.active", "Number of requests currently active", StatisticsHandler::getRequestsActive);
    bindGauge(reg,"jetty.dispatched.active", "Number of dispatches currently active", StatisticsHandler::getDispatchedActive);
    bindGauge(reg,"jetty.dispatched.active.max", "Maximum number of active dispatches being handled", StatisticsHandler::getDispatchedActiveMax);

    bindTimeGauge(reg,"jetty.dispatched.time.max", "Maximum time spent in dispatch handling", StatisticsHandler::getDispatchedTimeMax);

    bindGauge(reg,"jetty.async.requests.waiting", "Currently waiting async requests", StatisticsHandler::getAsyncRequestsWaiting);
    bindGauge(reg,"jetty.async.requests.waiting.max", "Maximum number of waiting async requests", StatisticsHandler::getAsyncRequestsWaitingMax);

    bindTimeGauge(reg,"jetty.request.time.max", "Maximum time spent handling requests", StatisticsHandler::getRequestTimeMax);
    bindTimeGauge(reg,"jetty.stats", "Time stats have been collected for", StatisticsHandler::getStatsOnMs);

    bindStatusCounters(reg);
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
private void bindStatusCounters(MeterRegistry reg) {
    buildStatusCounter(reg,"1xx", StatisticsHandler::getResponses1xx);
    buildStatusCounter(reg,"2xx", StatisticsHandler::getResponses2xx);
    buildStatusCounter(reg,"3xx", StatisticsHandler::getResponses3xx);
    buildStatusCounter(reg,"4xx", StatisticsHandler::getResponses4xx);
    buildStatusCounter(reg,"5xx", StatisticsHandler::getResponses5xx);
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
private void buildStatusCounter(MeterRegistry reg, String status, ToDoubleFunction<StatisticsHandler> consumer) {
    FunctionCounter.builder("jetty.responses", statisticsHandler, consumer)
        .tags(tags)
        .description("Number of requests with response status")
        .tags("status", status)
        .register(reg);
}
项目:javalin    文件:TestCustomJetty.java   
@Test
public void test_embeddedServer_withStatisticsHandler() throws Exception {
    StatisticsHandler statisticsHandler = new StatisticsHandler();

    Javalin app = Javalin.create()
        .port(0)
        .embeddedServer(new EmbeddedJettyFactory(() -> {
            Server server = new Server();
            server.setHandler(statisticsHandler);
            return server;
        }))
        .get("/", ctx -> ctx.result("Hello World"))
        .start();

    String origin = "http://localhost:" + app.port();

    int requests = 5;
    for (int i = 0; i < requests; i++) {
        assertThat(Unirest.get(origin + "/").asString().getBody(), is("Hello World"));
        assertThat(Unirest.get(origin + "/not_there").asString().getStatus(), is(404));
    }

    assertThat(statisticsHandler.getDispatched(), is(requests * 2));
    assertThat(statisticsHandler.getResponses2xx(), is(requests));
    assertThat(statisticsHandler.getResponses4xx(), is(requests));
    app.stop();
}
项目:javalin    文件:TestCustomJetty.java   
@Test
public void test_embeddedServer_withHandlerChain() throws Exception {
    AtomicLong logCount = new AtomicLong(0);
    RequestLog requestLog = (request, response) -> logCount.incrementAndGet();
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    requestLogHandler.setRequestLog(requestLog);
    StatisticsHandler handlerChain = new StatisticsHandler();
    handlerChain.setHandler(requestLogHandler);

    Javalin app = Javalin.create()
        .port(0)
        .embeddedServer(new EmbeddedJettyFactory(() -> {
            Server server = new Server();
            server.setHandler(handlerChain);
            return server;
        }))
        .get("/", ctx -> ctx.result("Hello World"))
        .start();

    String origin = "http://localhost:" + app.port();

    int requests = 10;
    for (int i = 0; i < requests; i++) {
        assertThat(Unirest.get(origin + "/").asString().getBody(), is("Hello World"));
        assertThat(Unirest.get(origin + "/not_there").asString().getStatus(), is(404));
    }

    assertThat(handlerChain.getDispatched(), is(requests * 2));
    assertThat(handlerChain.getResponses2xx(), is(requests));
    assertThat(handlerChain.getResponses4xx(), is(requests));

    assertThat(logCount.get(), is((long) (requests * 2)));

    app.stop();
}
项目:microservice-mock    文件:MockRegistry.java   
/**
 * Auxiliary method to register beans to the Main component, but after the Main has started. Typically the
 * underlying Server is also started and instantiated.
 */
public static void registerBeansInRegistryAfterStart() {
    StatisticsHandler statisticsHandler = findStatisticsHandler();
    Server server = statisticsHandler.getServer();
    main.bind(BEAN_JETTY_SERVER, server);
    InfoFilter.registerFilterDirectlyWithServer(server);
}
项目:microservice-mock    文件:StatsCommand.java   
private static String statisticsAsString(StatisticsHandler statisticsHandler) {
    StringBuilder buffer = new StringBuilder();
    buffer.append("Total requests: ").append(statisticsHandler.getDispatched());
    buffer.append(", total request time: ").append(statisticsHandler.getRequestTimeTotal());
    buffer.append(", mean time: ").append(statisticsHandler.getRequestTimeMean());
    buffer.append(", max time: ").append(statisticsHandler.getRequestTimeMax());
    buffer.append(", std dev: ").append(statisticsHandler.getRequestTimeStdDev());
    buffer.append(", last reset/start: ").append(statisticsHandler.getStatsOnMs()).append(" ms ago");
    return buffer.toString();
}
项目:microservice-mock    文件:StatsCommandTest.java   
@Test (description = "Test stats command with actual endpoint")
public void testStatsCommand() throws Exception{
    LOGGER.info("About to send stats command, total routes: {}", super.getProducerTemplate().getCamelContext().getRoutes().size());
    Exchange response = super.getProducerTemplate().request("jetty:http://localhost:" + super.getAvailablePort() + "/mock/cmd", exchange -> {
        exchange.getIn().setHeader(Exchange.HTTP_METHOD, ConfigurationManager.HTTP_GET);
        exchange.getIn().setHeader("stats", "html");
    });
    StatisticsHandler statisticsHandler = MockRegistry.findStatisticsHandler();
    Assert.assertTrue(statisticsHandler.getRequests() == 1);
    String html = response.getOut().getBody(String.class);
    LOGGER.info("Got html: {}", html);
}
项目:KeyServer    文件:StatusControllerTest.java   
/**
 * Test of showKsStats method, of class StatusController.
 * @since v0.4.4
 */
@Test
public void testShowKsStats() {
    System.out.println("showKsStats");
    StatisticsHandler statistics = ksMonitor.getStatistics();
    StatusController.showKsStats(statistics);
    assertTrue(ksMonitor.isCorrectlyInitialized());
}
项目:KeyServer    文件:KsMonitorTest.java   
/**
 * Test of getStatistics method, of class KsMonitor.
 * @since v0.4.4
 */
@Test
public void testGetStatistics() {
    System.out.println("getStatistics");
    StatisticsHandler result = this.ksMonitor.getStatistics();
    assertEquals(0, result.getRequests());
}
项目:OHMS    文件:JettyMonitorUtil.java   
public static int getActiveRequestsCount()
{

    int count = -1;

    if ( statHandler != null && statHandler instanceof StatisticsHandler )
    {

        StatisticsHandler handler = (StatisticsHandler) statHandler;
        count = handler.getRequestsActive();
    }
    return count;
}
项目:vespa    文件:JettyHttpServer.java   
private HandlerCollection getHandlerCollection(
        ServerConfig serverConfig,
        ServletPathsConfig servletPathsConfig,
        ServletHolder jdiscServlet,
        ComponentRegistry<ServletHolder> servletHolders,
        FilterHolder jDiscFilterInvokerFilter,
        RequestLog requestLog) {

    ServletContextHandler servletContextHandler = createServletContextHandler();

    servletHolders.allComponentsById().forEach((id, servlet) -> {
        String path = getServletPath(servletPathsConfig, id);
        servletContextHandler.addServlet(servlet, path);
        servletContextHandler.addFilter(jDiscFilterInvokerFilter, path, EnumSet.allOf(DispatcherType.class));
    });

    servletContextHandler.addServlet(jdiscServlet, "/*");

    GzipHandler gzipHandler = newGzipHandler(serverConfig);
    gzipHandler.setHandler(servletContextHandler);

    StatisticsHandler statisticsHandler = newStatisticsHandler();
    statisticsHandler.setHandler(gzipHandler);

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    requestLogHandler.setRequestLog(requestLog);

    HandlerCollection handlerCollection = new HandlerCollection();
    handlerCollection.setHandlers(new Handler[]{statisticsHandler, requestLogHandler});
    return handlerCollection;
}
项目:vespa    文件:JettyHttpServer.java   
@Override
public void run() {
    StatisticsHandler statisticsHandler = ((AbstractHandlerContainer)server.getHandler())
            .getChildHandlerByClass(StatisticsHandler.class);
    if (statisticsHandler == null)
        return;

    setServerMetrics(statisticsHandler);

    for (Connector connector : server.getConnectors()) {
        setConnectorMetrics((JDiscServerConnector)connector);
    }
}
项目:amv-access-api-poc    文件:JettyMetricsCustomizer.java   
JettyMetricsCustomizer(StatisticsHandler statisticsHandler) {
    this.statisticsHandler = requireNonNull(statisticsHandler);
}
项目:amv-access-api-poc    文件:JettyConfiguration.java   
@Bean
public StatisticsHandler statisticsHandler() {
    return new StatisticsHandler();
}
项目:amv-access-api-poc    文件:JettyConfiguration.java   
@Bean
public JettyStatisticsCollector jettyStatisticsCollector(CollectorRegistry collectorRegistry,
                                                         StatisticsHandler statisticsHandler) {
    return new JettyStatisticsCollector(statisticsHandler)
            .register(collectorRegistry);
}
项目:amv-access-api-poc    文件:JettyConfiguration.java   
@Bean
public JettyCustomizer jettyMetricsCustomizer(StatisticsHandler statisticsHandler) {
    return new JettyMetricsCustomizer(statisticsHandler);
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
public static void monitor(MeterRegistry meterRegistry, StatisticsHandler statisticsHandler, String... tags) {
    monitor(meterRegistry, statisticsHandler, Tags.zip(tags));
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
public static void monitor(MeterRegistry meterRegistry, StatisticsHandler statisticsHandler, Iterable<Tag> tags) {
    new JettyStatisticsMetrics(statisticsHandler, tags).bindTo(meterRegistry);
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
public JettyStatisticsMetrics(StatisticsHandler statisticsHandler, Iterable<Tag> tags) {
    this.tags = tags;
    this.statisticsHandler = statisticsHandler;
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
private void bindGauge(MeterRegistry reg, String name, String desc, ToDoubleFunction<StatisticsHandler> func) {
    Gauge.builder(name, statisticsHandler, func)
        .tags(tags)
        .description(desc)
        .register(reg);
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
private void bindTimer(MeterRegistry reg, String name, String desc, ToLongFunction<StatisticsHandler> countFunc, ToDoubleFunction<StatisticsHandler> consumer) {
    FunctionTimer.builder(name, statisticsHandler, countFunc, consumer, TimeUnit.MILLISECONDS)
        .tags(tags)
        .description(desc)
        .register(reg);
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
private void bindTimeGauge(MeterRegistry reg, String name, String desc, ToDoubleFunction<StatisticsHandler> consumer) {
    TimeGauge.builder(name, statisticsHandler, TimeUnit.MILLISECONDS, consumer)
        .tags(tags)
        .description(desc)
        .register(reg);
}
项目:micrometer    文件:JettyStatisticsMetrics.java   
private void bindCounter(MeterRegistry reg, String name, String desc, ToDoubleFunction<StatisticsHandler> consumer) {
    FunctionCounter.builder(name, statisticsHandler, consumer)
        .tags(tags)
        .description(desc)
        .register(reg);
}
项目:micrometer    文件:JettyStatisticsMetricsTest.java   
@BeforeEach
void setup() throws SQLException {
    this.registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock());
    this.handler = new StatisticsHandler();
    JettyStatisticsMetrics.monitor(registry, handler);
}
项目:Patterdale    文件:JettyStatisticsCollector.java   
public JettyStatisticsCollector(StatisticsHandler statisticsHandler) {
    this.statisticsHandler = statisticsHandler;
}
项目:kafka-0.11.0.0-src-with-comment    文件:RestServer.java   
public void start(Herder herder) {
    log.info("Starting REST server");

    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.register(new JacksonJsonProvider());

    resourceConfig.register(RootResource.class);
    resourceConfig.register(new ConnectorsResource(herder));
    resourceConfig.register(new ConnectorPluginsResource(herder));

    resourceConfig.register(ConnectExceptionMapper.class);

    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder servletHolder = new ServletHolder(servletContainer);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");

    String allowedOrigins = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_ORIGIN_CONFIG);
    if (allowedOrigins != null && !allowedOrigins.trim().isEmpty()) {
        FilterHolder filterHolder = new FilterHolder(new CrossOriginFilter());
        filterHolder.setName("cross-origin");
        filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins);
        String allowedMethods = config.getString(WorkerConfig.ACCESS_CONTROL_ALLOW_METHODS_CONFIG);
        if (allowedMethods != null && !allowedOrigins.trim().isEmpty()) {
            filterHolder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods);
        }
        context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    }

    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLog requestLog = new Slf4jRequestLog();
    requestLog.setLoggerName(RestServer.class.getCanonicalName());
    requestLog.setLogLatency(true);
    requestLogHandler.setRequestLog(requestLog);

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[]{context, new DefaultHandler(), requestLogHandler});

    /* Needed for graceful shutdown as per `setStopTimeout` documentation */
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);
    jettyServer.setHandler(statsHandler);
    jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
    jettyServer.setStopAtShutdown(true);

    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new ConnectException("Unable to start REST server", e);
    }

    log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl());
}
项目:graviteeio-access-management    文件:JettyServerFactory.java   
@Override
public Server getObject() throws Exception {

    // Setup ThreadPool
    QueuedThreadPool threadPool = new QueuedThreadPool(
            jettyConfiguration.getPoolMaxThreads(),
            jettyConfiguration.getPoolMinThreads(),
            jettyConfiguration.getPoolIdleTimeout(),
            new ArrayBlockingQueue<>(jettyConfiguration.getPoolQueueSize())
    );
    threadPool.setName("graviteeam-listener");

    Server server = new Server(threadPool);

    // Extra options
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);

    // Setup JMX
    if (jettyConfiguration.isJmxEnabled()) {
        MBeanContainer mbContainer = new MBeanContainer(
                ManagementFactory.getPlatformMBeanServer());
        server.addBean(mbContainer);
    }

    // HTTP Configuration
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme("https");
    httpConfig.setSecurePort(8443);
    httpConfig.setOutputBufferSize(32768);
    httpConfig.setRequestHeaderSize(8192);
    httpConfig.setResponseHeaderSize(8192);
    httpConfig.setSendServerVersion(false);
    httpConfig.setSendDateHeader(false);

    // Setup Jetty HTTP Connector
    ServerConnector http = new ServerConnector(server,
            new HttpConnectionFactory(httpConfig));
    http.setPort(jettyConfiguration.getHttpPort());
    http.setIdleTimeout(jettyConfiguration.getIdleTimeout());

    server.addConnector(http);

    // Setup Jetty statistics
    if (jettyConfiguration.isStatisticsEnabled()) {
        StatisticsHandler stats = new StatisticsHandler();
        stats.setHandler(server.getHandler());
        server.setHandler(stats);
    }

    if (jettyConfiguration.isAccessLogEnabled()) {
        AsyncNCSARequestLog requestLog = new AsyncNCSARequestLog(
                jettyConfiguration.getAccessLogPath());
        requestLog.setRetainDays(90);
        requestLog.setExtended(true);
        requestLog.setLogLatency(true);
        requestLog.setLogTimeZone("GMT");

        server.setRequestLog(requestLog);
    }

    return server;
}
项目:microservice-mock    文件:MockRegistry.java   
public static StatisticsHandler findStatisticsHandler() {
    return main.lookup(BEAN_METRICS, StatisticsHandler.class);
}
项目:KeyServer    文件:KsJetty.java   
/**
 * Class constructor.
 * @param parameters Jetty HTTPS service configuration object.
 * @param objDB Redis database object.
 * @since v0.4.0
 */
public KsJetty(ConfigController parameters, DataBase objDB){
    server = new Server();
    // User custom configuration fields
    HttpConfiguration https = getHttpStaticConfig();
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(parameters.getServerKeyStoreFile());
    sslContextFactory.setSessionCachingEnabled(true);
    sslContextFactory.setKeyStorePassword(parameters.getServerKeyStorePassword());
    sslContextFactory.setKeyManagerPassword(parameters.getServerKeyManagerPassword());
    // Set the SSL configuration fields.
    ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory(https));
    // Server listener address and port.
    sslConnector.setPort(parameters.getServerPort());
    sslConnector.setHost(parameters.getServerAddress().getHostAddress());
    sslConnector.setIdleTimeout(parameters.getIdleTimeout());
    server.setConnectors(new Connector[] {sslConnector});
    // Jetty incoming requests handler.
    KeyServerJettyHandler ksHandler = new KeyServerJettyHandler(objDB);
    // Error Handler
    KsJettyErrors ksErrors = new KsJettyErrors();
    ksErrors.setServer(server);
    server.addBean(ksErrors);
    // Security Whitelist filter
    if(parameters.getServerIpWhiteList() != null){
        InetAccessHandler accessControl = new InetAccessHandler();
        for (String tmp :parameters.getServerIpWhiteList()) {
            accessControl.include(tmp.trim());
        }
        accessControl.setHandler(ksHandler);
        server.setHandler(accessControl);
    } else {
        server.setHandler(ksHandler);
        org.slf4j.Logger SECURITY = LoggerFactory.getLogger("security");
        org.slf4j.Logger LOGGER = LoggerFactory.getLogger(KsJetty.class);
        String msg = "There is no 'white list' field defined inside config file."
                + "\n\t\tAllowing KeyServer access to all IPs!";
        SECURITY.warn(msg);
        LOGGER.warn(msg);
    }
    // Statistics handler
    stats = new StatisticsHandler();
    stats.setHandler(server.getHandler());
    server.setHandler(stats);
    ServerConnectionStatistics.addToAllConnectors(server);
}