Java Code Examples for org.eclipse.jetty.servlet.ServletContextHandler#setAttribute()

The following examples show how to use org.eclipse.jetty.servlet.ServletContextHandler#setAttribute() . 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: AbstractParentSpanResolutionTest.java    From java-jaxrs with Apache License 2.0 6 votes vote down vote up
@Override
protected void initTracing(ServletContextHandler context) {
    client.register(new ClientTracingFeature.Builder(mockTracer).build());

    ServerTracingDynamicFeature.Builder builder = new ServerTracingDynamicFeature.Builder(mockTracer);
    if (shouldUseParentSpan()) {
        builder = builder.withJoinExistingActiveSpan(true);
    }
    ServerTracingDynamicFeature serverTracingFeature = builder.build();

    context.addFilter(new FilterHolder(new SpanFinishingFilter()),
            "/*", EnumSet.of(DispatcherType.REQUEST));

    context.setAttribute(TRACER_ATTRIBUTE, mockTracer);
    context.setAttribute(CLIENT_ATTRIBUTE, client);
    context.setAttribute(SERVER_TRACING_FEATURE, serverTracingFeature);
}
 
Example 2
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Jetty context handler that can be used to expose the cross-domain functionality as implemented by
 * {@link FlashCrossDomainServlet}.
 *
 * Note that an invocation of this method will not register the handler (and thus make the related functionality
 * available to the end user). Instead, the created handler is returned by this method, and will need to be
 * registered with the embedded Jetty webserver by the caller.
 *
 * @return A Jetty context handler (never null).
 */
protected Handler createCrossDomainHandler()
{
    final ServletContextHandler context = new ServletContextHandler( null, "/crossdomain.xml", ServletContextHandler.SESSIONS );

    // Ensure the JSP engine is initialized correctly (in order to be able to cope with Tomcat/Jasper precompiled JSPs).
    final List<ContainerInitializer> initializers = new ArrayList<>();
    initializers.add( new ContainerInitializer( new JasperInitializer(), null ) );
    context.setAttribute( "org.eclipse.jetty.containerInitializers", initializers );
    context.setAttribute( InstanceManager.class.getName(), new SimpleInstanceManager() );

    // Generic configuration of the context.
    context.setAllowNullPathInfo( true );

    // Add the functionality-providers.
    context.addServlet( new ServletHolder( new FlashCrossDomainServlet() ), "" );

    return context;
}
 
Example 3
Source File: AbstractJettyTest.java    From java-jaxrs with Apache License 2.0 6 votes vote down vote up
protected void initTracing(ServletContextHandler context) {
    client.register(new Builder(mockTracer).build());

    ServerTracingDynamicFeature serverTracingFeature =
        new ServerTracingDynamicFeature.Builder(mockTracer)
            .withOperationNameProvider(HTTPMethodOperationName.newBuilder())
            .withDecorators(Collections.singletonList(ServerSpanDecorator.STANDARD_TAGS))
            .withSkipPattern("/health")
        .build();
    // TODO clarify dispatcher types
    context.addFilter(new FilterHolder(new SpanFinishingFilter()), "/*",
        EnumSet.of(
            DispatcherType.REQUEST,
            // TODO CXF does not call AsyncListener#onComplete() without this (it calls only onStartAsync)
            DispatcherType.ASYNC));

    context.setAttribute(CLIENT_ATTRIBUTE, client);
    context.setAttribute(TRACER_ATTRIBUTE, mockTracer);
    context.setAttribute(SERVER_TRACING_FEATURE, serverTracingFeature);
}
 
Example 4
Source File: WorkerServer.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public static ServletContextHandler newServletContextHandler(String contextPath, ResourceConfig config, WorkerService workerService, boolean requireAuthentication) {
    final ServletContextHandler contextHandler =
            new ServletContextHandler(ServletContextHandler.NO_SESSIONS);

    contextHandler.setAttribute(FunctionApiResource.ATTRIBUTE_FUNCTION_WORKER, workerService);
    contextHandler.setAttribute(WorkerApiV2Resource.ATTRIBUTE_WORKER_SERVICE, workerService);
    contextHandler.setAttribute(WorkerStatsApiV2Resource.ATTRIBUTE_WORKERSTATS_SERVICE, workerService);
    contextHandler.setContextPath(contextPath);

    final ServletHolder apiServlet =
            new ServletHolder(new ServletContainer(config));
    contextHandler.addServlet(apiServlet, "/*");
    if (workerService.getWorkerConfig().isAuthenticationEnabled() && requireAuthentication) {
        FilterHolder filter = new FilterHolder(new AuthenticationFilter(workerService.getAuthenticationService()));
        contextHandler.addFilter(filter, MATCH_ALL, EnumSet.allOf(DispatcherType.class));
    }

    return contextHandler;
}
 
Example 5
Source File: WebServerModule.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideJMX(final MetricRegistry metrics) {
  return new ContextConfigurator() {
    private JmxReporter reporter;
    @Override
    public void init(ServletContextHandler context) {
      context.setAttribute("com.codahale.metrics.servlets.MetricsServlet.registry", metrics);
      ServletHolder servlet = new ServletHolder(new JMXJsonServlet());
      context.addServlet(servlet, "/rest/v1/system/jmx");
    }

    @Override
    public void start() {
      reporter = JmxReporter.forRegistry(metrics).build();
      reporter.start();
    }

    @Override
    public void stop() {
      if(reporter != null) {
        reporter.stop();
        reporter.close();
      }
    }
  };
}
 
Example 6
Source File: Poseidon.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private ServletContextHandler getMetricsHandler() {
    MetricRegistry registry = Metrics.getRegistry();
    HealthCheckRegistry healthCheckRegistry = Metrics.getHealthCheckRegistry();
    healthCheckRegistry.register("rotation", new Rotation(configuration.getRotationStatusFilePath()));

    registry.registerAll(new GarbageCollectorMetricSet());
    registry.registerAll(new MemoryUsageGaugeSet());
    registry.registerAll(new ThreadStatesGaugeSet());
    registry.registerAll(new JvmAttributeGaugeSet());

    ServletContextHandler servletContextHandler = new ServletContextHandler();
    servletContextHandler.setContextPath("/__metrics");
    servletContextHandler.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry);
    servletContextHandler.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", healthCheckRegistry);
    servletContextHandler.addServlet(new ServletHolder(new AdminServlet()), "/*");

    return servletContextHandler;
}
 
Example 7
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator providePipelineStateManager(final Manager pipelineManager) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      context.setAttribute(StandAndClusterManagerInjector.PIPELINE_MANAGER_MGR, pipelineManager);
    }
  };
}
 
Example 8
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideStageLibrary(final StageLibraryTask stageLibrary) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      context.setAttribute(StageLibraryInjector.STAGE_LIBRARY, stageLibrary);
    }
  };
}
 
Example 9
Source File: HttpBindManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Jetty context handler that can be used to expose BOSH (HTTP-Bind) functionality.
 *
 * Note that an invocation of this method will not register the handler (and thus make the related functionality
 * available to the end user). Instead, the created handler is returned by this method, and will need to be
 * registered with the embedded Jetty webserver by the caller.
 *
 * @return A Jetty context handler (never null).
 */
protected Handler createBoshHandler()
{
    final int options;
    if(isHttpCompressionEnabled()) {
        options = ServletContextHandler.SESSIONS | ServletContextHandler.GZIP;
    } else {
        options = ServletContextHandler.SESSIONS;
    }
    final ServletContextHandler context = new ServletContextHandler( null, "/http-bind", options );

    // Ensure the JSP engine is initialized correctly (in order to be able to cope with Tomcat/Jasper precompiled JSPs).
    final List<ContainerInitializer> initializers = new ArrayList<>();
    initializers.add( new ContainerInitializer( new JasperInitializer(), null ) );
    context.setAttribute( "org.eclipse.jetty.containerInitializers", initializers );
    context.setAttribute( InstanceManager.class.getName(), new SimpleInstanceManager() );

    // Generic configuration of the context.
    context.setAllowNullPathInfo( true );

    // Add the functionality-providers.
    context.addServlet( new ServletHolder( new HttpBindServlet() ), "/*" );

    // Add compression filter when needed.
    if (isHttpCompressionEnabled()) {
        final GzipHandler gzipHandler = context.getGzipHandler();
        gzipHandler.addIncludedPaths("/*");
        gzipHandler.addIncludedMethods(HttpMethod.POST.asString());
    }

    return context;
}
 
Example 10
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideSupportBundleManager(final SupportBundleManager supportBundleManager) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      context.setAttribute(SupportBundleInjector.SUPPORT_BUNDLE_MANAGER, supportBundleManager);
    }
  };
}
 
Example 11
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideAclStore(final AclStoreTask aclStore) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      context.setAttribute(AclStoreInjector.ACL_STORE, aclStore);
    }
  };
}
 
Example 12
Source File: ITSpanCustomizingHandlerInterceptor.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void init(ServletContextHandler handler) {
  StaticWebApplicationContext wac = new StaticWebApplicationContext();
  wac.getBeanFactory()
    .registerSingleton("httpTracing", httpTracing);

  wac.getBeanFactory()
    .registerSingleton("testController", new TestController(httpTracing)); // the test resource

  DefaultAnnotationHandlerMapping mapping = new DefaultAnnotationHandlerMapping();
  mapping.setInterceptors(new Object[] {new SpanCustomizingHandlerInterceptor()});
  mapping.setApplicationContext(wac);

  wac.getBeanFactory().registerSingleton(HANDLER_MAPPING_BEAN_NAME, mapping);
  wac.getBeanFactory()
    .registerSingleton(HANDLER_ADAPTER_BEAN_NAME, new AnnotationMethodHandlerAdapter());

  handler.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
  handler.addServlet(new ServletHolder(new DispatcherServlet() {
    {
      wac.refresh();
      setDetectAllHandlerMappings(false);
      setDetectAllHandlerAdapters(false);
      setPublishEvents(false);
    }

    @Override protected WebApplicationContext initWebApplicationContext() throws BeansException {
      onRefresh(wac);
      return wac;
    }
  }), "/*");
  handler.addFilter(DelegatingTracingFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
}
 
Example 13
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideCredentialStoreTask(final CredentialStoresTask credentialStoreTask) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      context.setAttribute(CredentialStoreTaskInjector.CREDENTIAL_STORE_TASK, credentialStoreTask);
    }
  };
}
 
Example 14
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideConfiguration(final Configuration configuration) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      context.setAttribute(ConfigurationInjector.CONFIGURATION, configuration);
    }
  };
}
 
Example 15
Source File: ProxyServer.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public void addRestResources(String basePath, String javaPackages, String attribute, Object attributeValue) {
    ResourceConfig config = new ResourceConfig();
    config.packages("jersey.config.server.provider.packages", javaPackages);
    config.register(JsonMapperProvider.class);
    ServletHolder servletHolder = new ServletHolder(new ServletContainer(config));
    servletHolder.setAsyncSupported(true);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath(basePath);
    context.addServlet(servletHolder, "/*");
    context.setAttribute(attribute, attributeValue);
    handlers.add(context);
}
 
Example 16
Source File: AbstractClassOperationNameTest.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Override
protected void initTracing(ServletContextHandler context) {
  client.register(new Builder(mockTracer).build());

  ServerTracingDynamicFeature serverTracingBuilder =
      new ServerTracingDynamicFeature.Builder(mockTracer)
          .withOperationNameProvider(ClassNameOperationName.newBuilder())
          .build();
  context.addFilter(new FilterHolder(new SpanFinishingFilter()),
      "/*", EnumSet.of(DispatcherType.REQUEST));

  context.setAttribute(TRACER_ATTRIBUTE, mockTracer);
  context.setAttribute(CLIENT_ATTRIBUTE, client);
  context.setAttribute(SERVER_TRACING_FEATURE, serverTracingBuilder);
}
 
Example 17
Source File: AbstractServerWithTraceNothingTest.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Override
protected void initTracing(ServletContextHandler context) {
    client.register(new ClientTracingFeature.Builder(mockTracer).build());

    ServerTracingDynamicFeature serverTracingBuilder =
            new ServerTracingDynamicFeature.Builder(mockTracer)
                    .withTraceNothing() // This should only trace @Traced annotations, per documentation!
                    .build();
    context.addFilter(new FilterHolder(new SpanFinishingFilter()),
            "/*", EnumSet.of(DispatcherType.REQUEST));

    context.setAttribute(TRACER_ATTRIBUTE, mockTracer);
    context.setAttribute(CLIENT_ATTRIBUTE, client);
    context.setAttribute(SERVER_TRACING_FEATURE, serverTracingBuilder);
}
 
Example 18
Source File: AbstractClientTest.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Override
protected void initTracing(ServletContextHandler context) {
    client.register(new Builder(mockTracer).build());

    Tracer serverTracer = NoopTracerFactory.create();
    ServerTracingDynamicFeature serverTracingBuilder =
            new ServerTracingDynamicFeature.Builder(serverTracer)
                    .build();

    context.setAttribute(TRACER_ATTRIBUTE, serverTracer);
    context.setAttribute(CLIENT_ATTRIBUTE, ClientBuilder.newClient());
    context.setAttribute(SERVER_TRACING_FEATURE, serverTracingBuilder);
}
 
Example 19
Source File: WebServerModule.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Provides(type = Type.SET)
ContextConfigurator provideRuntimeInfo(final RuntimeInfo runtimeInfo) {
  return new ContextConfigurator() {
    @Override
    public void init(ServletContextHandler context) {
      context.setAttribute(RuntimeInfoInjector.RUNTIME_INFO, runtimeInfo);
    }
  };
}
 
Example 20
Source File: DownloadArtifactsTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Override

    @Before
    public void startServer()
        throws Exception
    {
        super.startServer();

        // repo handler

        this.repoServer = new Server(  );
        ServerConnector repoServerConnector = new ServerConnector( this.repoServer, new HttpConnectionFactory());
        this.repoServer.addConnector( repoServerConnector );

        ServletHolder shRepo = new ServletHolder( RepoServlet.class );
        ServletContextHandler contextRepo = new ServletContextHandler();

        contextRepo.setContextPath( "/" );
        contextRepo.addServlet( shRepo, "/*" );

        repoServer.setHandler( contextRepo );

        repoServer.start();
        this.repoServerPort = repoServerConnector.getLocalPort();

        //redirect handler

        this.redirectServer = new Server( );
        ServerConnector redirectServerConnector = new ServerConnector( this.redirectServer, new HttpConnectionFactory());
        this.redirectServer.addConnector( redirectServerConnector );

        ServletHolder shRedirect = new ServletHolder( RedirectServlet.class );
        ServletContextHandler contextRedirect = new ServletContextHandler();
        contextRedirect.setAttribute( "redirectToPort", Integer.toString( this.repoServerPort ) );

        contextRedirect.setContextPath( "/" );
        contextRedirect.addServlet( shRedirect, "/*" );

        redirectServer.setHandler( contextRedirect );
        redirectServer.start();
        this.redirectPort = redirectServerConnector.getLocalPort();
        log.info( "redirect server port {}", redirectPort );

    }