com.google.inject.servlet.ServletModule Java Examples

The following examples show how to use com.google.inject.servlet.ServletModule. 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: ServerProvider.java    From angulardemorestful with MIT License 6 votes vote down vote up
public void createServer() throws IOException {
    System.out.println("Starting grizzly...");

    Injector injector = Guice.createInjector(new ServletModule() {
        @Override
        protected void configureServlets() {
            bind(UserService.class).to(UserServiceImpl.class);
            bind(UserRepository.class).to(UserMockRepositoryImpl.class);
            bind(DummyService.class).to(DummyServiceImpl.class);
            bind(DummyRepository.class).to(DummyMockRepositoryImpl.class);

            // hook Jackson into Jersey as the POJO <-> JSON mapper
            bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);
        }
    });

    ResourceConfig rc = new PackagesResourceConfig("ngdemo.web");
    IoCComponentProviderFactory ioc = new GuiceComponentProviderFactory(rc, injector);
    server = GrizzlyServerFactory.createHttpServer(BASE_URI + "web/", rc, ioc);

    System.out.println(String.format("Jersey app started with WADL available at "
            + "%srest/application.wadl\nTry out %sngdemo\nHit enter to stop it...",
            BASE_URI, BASE_URI));
}
 
Example #2
Source File: NgDemoApplicationSetup.java    From angulardemorestful with MIT License 6 votes vote down vote up
@Override
protected Injector getInjector() {
    return Guice.createInjector(new ServletModule() {

        @Override
        protected void configureServlets() {

            super.configureServlets();

            // Configuring Jersey via Guice:
            ResourceConfig resourceConfig = new PackagesResourceConfig("ngdemo/web");
            for (Class<?> resource : resourceConfig.getClasses()) {
                bind(resource);
            }

            // hook Jackson into Jersey as the POJO <-> JSON mapper
            bind(JacksonJsonProvider.class).in(Scopes.SINGLETON);

            serve("/web/*").with(GuiceContainer.class);

            filter("/web/*").through(ResponseCorsFilter.class);
        }
    }, new UserModule());
}
 
Example #3
Source File: ShiroKerberosAuthenticationFilterTest.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
public Function<ServletContext, Module> getChildServletModule() {
  return (servletContext) -> new ServletModule() {
    @Override
    protected void configureServlets() {
      filter(PATH).through(filter);
      serve(PATH).with(new HttpServlet() {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

          getMockServlet().service(req, resp);
          resp.setStatus(HttpServletResponse.SC_OK);
        }
      });
    }
  };
}
 
Example #4
Source File: TestModule.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void configure() {
  install(new ResteasyModule());
  install(new ValidationModule());

  install(new ServletModule()
  {
    @Override
    protected void configureServlets() {
      serve(MOUNT_POINT + "/*").with(SiestaServlet.class, ImmutableMap.of(
          "resteasy.servlet.mapping.prefix", MOUNT_POINT
      ));
    }
  });

  // register exception mappers required by tests
  register(ValidationErrorsExceptionMapper.class);
  register(WebappExceptionMapper.class);

  // register test resources
  register(EchoResource.class);
  register(ErrorsResource.class);
  register(UserResource.class);
  register(ValidationErrorsResource.class);
}
 
Example #5
Source File: ShiroKerberosPermissiveAuthenticationFilterTest.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
public Function<ServletContext, Module> getChildServletModule() {
  return (servletContext) -> new ServletModule() {
    @Override
    protected void configureServlets() {
      filter(PATH).through(filter);
      serve(PATH).with(new HttpServlet() {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

          mockServlet.service(req, resp);
          resp.setStatus(HttpServletResponse.SC_OK);
        }
      });
    }
  };
}
 
Example #6
Source File: ServerRpcProvider.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
public ServletModule getServletModule() {

    return new ServletModule() {
      @Override
      protected void configureServlets() {
        // We add servlets here to override the DefaultServlet automatic registered by WebAppContext
        // in path "/" with our WaveClientServlet. Any other way to do this?
        // Related question (unanswered 08-Apr-2011)
        // http://web.archiveorange.com/archive/v/d0LdlXf1kN0OXyPNyQZp
        for (Pair<String, ServletHolder> servlet : servletRegistry) {
          String url = servlet.getFirst();
          @SuppressWarnings("unchecked")
          Class<HttpServlet> clazz = (Class<HttpServlet>) servlet.getSecond().getHeldClass();
          Map<String,String> params = servlet.getSecond().getInitParameters();
          serve(url).with(clazz,params);
          bind(clazz).in(Singleton.class);
        }
        for (Pair<String, Class<? extends Filter>> filter : filterRegistry) {
          filter(filter.first).through(filter.second);
        }
      }
    };
  }
 
Example #7
Source File: WebResourcesModule.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void configure() {
  final Binder lowPriorityBinder = binder().withSource(Sources.prioritize(Integer.MIN_VALUE));

  lowPriorityBinder.install(new ServletModule()
  {
    @Override
    protected void configureServlets() {
      serve("/*").with(WebResourceServlet.class);
      filter("/*").through(SecurityFilter.class);
    }
  });

  lowPriorityBinder.install(new FilterChainModule()
  {
    @Override
    protected void configure() {
      addFilterChain("/**", AnonymousFilter.NAME, AntiCsrfFilter.NAME);
    }
  });
}
 
Example #8
Source File: RaptureModule.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void configure() {
  bind(filterKey(SessionAuthenticationFilter.NAME)).to(SessionAuthenticationFilter.class);

  install(new ServletModule()
  {
    @Override
    protected void configureServlets() {
      serve(SESSION_MP).with(SessionServlet.class);
      filter(SESSION_MP).through(SecurityFilter.class);
      filter(SESSION_MP).through(CookieFilter.class);
    }
  });

  install(new FilterChainModule()
  {
    @Override
    protected void configure() {
      addFilterChain(SESSION_MP, SessionAuthenticationFilter.NAME);
    }
  });
}
 
Example #9
Source File: ServerRpcProvider.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public ServletModule getServletModule() {

    return new ServletModule() {
      @Override
      protected void configureServlets() {
        // We add servlets here to override the DefaultServlet automatic
        // registered by WebAppContext
        // in path "/" with our WaveClientServlet. Any other way to do this?
        // Related question (unanswered 08-Apr-2011)
        // http://web.archiveorange.com/archive/v/d0LdlXf1kN0OXyPNyQZp
        for (Pair<String, ServletHolder> servlet : servletRegistry) {
          String url = servlet.getFirst();
          @SuppressWarnings("unchecked")
          Class<HttpServlet> clazz = (Class<HttpServlet>) servlet.getSecond().getHeldClass();
          Map<String, String> params = servlet.getSecond().getInitParameters();
          serve(url).with(clazz, params);
          bind(clazz).in(Singleton.class);
        }
        for (Pair<String, Class<? extends Filter>> filter : filterRegistry) {
          filter(filter.first).through(filter.second);
        }
        bind(GuiceResteasyBootstrapServletContextListener.class).in(Singleton.class);
      }
    };
  }
 
Example #10
Source File: GuiceServletFilterTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Override
protected Injector getInjector() {
  return Guice.createInjector(
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(Registry.class).toInstance(Spectator.globalRegistry());
        }
      },
      new ServletModule() {
        @Override
        protected void configureServlets() {
          serve("/test/foo/*").with(TestServlet.class);
          serve("/api/*").with(TestServlet.class);
          serve("/*").with(TestServlet.class);
          filter("/*").through(IpcServletFilter.class);
        }
      }
  );
}
 
Example #11
Source File: EverrestGuiceContextListener.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
private List<Module> createModules() {
    List<Module> all = new ArrayList<>();
    ServletModule servletModule = getServletModule();
    if (servletModule != null) {
        all.add(servletModule);
    }
    all.add(new EverrestModule());
    all.add(new EverrestConfigurationModule());
    List<Module> modules = getModules();
    if (modules != null && modules.size() > 0) {
        all.addAll(modules);
    }
    return all;
}
 
Example #12
Source File: StartServer.java    From EVCache with Apache License 2.0 5 votes vote down vote up
@Override
    protected ServletModule getServletModule() {
        return new JerseyServletModule() {
            @Override
            protected void configureServlets() {
                logger.info("########## CONFIGURING SERVLETS ##########");

                // initialize NFFilter
                Map<String, String> initParams = new HashMap<String,String>();
//                initParams.put(ServletContainer.JSP_TEMPLATES_BASE_PATH, "/WEB-INF/jsp");
//                initParams.put(ServletContainer.FEATURE_FILTER_FORWARD_ON_404, "true");
//                initParams.put("requestId.accept", "true");
//                initParams.put("requestId.require", "true");
                initParams.put(ResourceConfig.FEATURE_DISABLE_WADL, "true");
                initParams.put(PackagesResourceConfig.PROPERTY_PACKAGES, "com.netflix.evcache.service.resources");
                filter("/*").through(NFFilter.class, initParams);
                filter("/healthcheck", "/status").through(NFFilter.class, initParams);
                serve("/Status", "/status").with(BaseStatusPage.class);
                serve("/healthcheck", "/Healthcheck").with(BaseHealthCheckServlet.class);
                serve("/*").with(GuiceContainer.class, initParams);
                bind(EVCacheRESTService.class).asEagerSingleton();
                binder().bind(GuiceContainer.class).asEagerSingleton();
                
                install(new EVCacheServiceModule());
            }
        };
    }
 
Example #13
Source File: StatusServer.java    From suro with Apache License 2.0 5 votes vote down vote up
public static ServletModule createJerseyServletModule() {
    return new ServletModule() {
        @Override
        protected void configureServlets() {
            bind(HealthCheck.class);
            bind(SinkStat.class);
            bind(GuiceContainer.class).asEagerSingleton();
            serve("/*").with(GuiceContainer.class);
        }
    };
}
 
Example #14
Source File: ServerModule.java    From rome with Apache License 2.0 5 votes vote down vote up
@Override
protected Injector getInjector() {
    return Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
        }

        @Provides
        @Singleton
        public Hub buildHub() {
            final FeedFetcher fetcher = new HttpURLFeedFetcher(new HashMapFeedInfoCache());
            final Hub hub = new Hub(new InMemoryHubDAO(), new UnthreadedVerifier(), new UnthreadedNotifier(), fetcher);

            return hub;
        }

        @Provides
        @Singleton
        public Subscriptions buildSubs() {
            LOG.debug("buildSubs");
            final Subscriptions subs = new Subscriptions(new HashMapFeedInfoCache(), new AsyncRequester(), "http://localhost/webapp/subscriptions/",
                    new InMemorySubDAO());

            return subs;
        }
    }, new ServletModule() {
        @Override
        protected void configureServlets() {
            serve("/hub*").with(HubServlet.class);
            serve("/subscriptions/*").with(SubServlet.class);
            serve("/test/sub").with(SubTest.class);
            serve("/test/pub").with(NotifyTest.class);
        }
    });
}
 
Example #15
Source File: EverrestGuiceContextListener.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create servlet module. By default return module with one component GuiceEverrestServlet.
 *
 * @return ServletModule
 */
protected ServletModule getServletModule() {
    return new ServletModule() {
        @Override
        protected void configureServlets() {
            serve("/*").with(GuiceEverrestServlet.class);
        }
    };
}
 
Example #16
Source File: GraphQlServer.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Server server = new Server(HTTP_PORT);

  ServletContextHandler context = new ServletContextHandler(server, "/", SESSIONS);

  context.addEventListener(
      new GuiceServletContextListener() {
        @Override
        protected Injector getInjector() {
          return Guice.createInjector(
              new ServletModule() {
                @Override
                protected void configureServlets() {
                  serve("/graphql").with(GraphQlServlet.class);
                }
              },
              new DataLoaderModule(),
              new SchemaProviderModule(), // Part of Rejoiner framework (Provides `@Schema
              // GraphQLSchema`)
              new ClientModule(), // Installs all of the client modules
              new SchemaModule() // Installs all of the schema modules
              );
        }
      });

  context.addFilter(GuiceFilter.class, "/*", EnumSet.of(REQUEST, ASYNC));

  context.setBaseResource(
      new PathResource(new File("./src/main/resources").toPath().toRealPath()));
  context.addServlet(DefaultServlet.class, "/");
  server.start();
  logger.info("Server running on port " + HTTP_PORT);
  server.join();
}
 
Example #17
Source File: ExtDirectModule.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void configure() {
  install(new ServletModule()
  {
    @Override
    protected void configureServlets() {
      Map<String, String> config = Maps.newHashMap();
      config.put(GlobalParameters.PROVIDERS_URL, MOUNT_POINT.substring(1));
      config.put("minify", Boolean.FALSE.toString());
      config.put(GlobalParameters.DEBUG, Boolean.toString(log.isDebugEnabled()));
      config.put(GlobalParameters.JSON_REQUEST_PROCESSOR_THREAD_CLASS,
          ExtDirectJsonRequestProcessorThread.class.getName());
      config.put(GlobalParameters.GSON_BUILDER_CONFIGURATOR_CLASS,
          ExtDirectGsonBuilderConfigurator.class.getName());

      serve(MOUNT_POINT + "*").with(ExtDirectServlet.class, config);
      filter(MOUNT_POINT + "*").through(SecurityFilter.class);
    }
  });

  install(new FilterChainModule()
  {
    @Override
    protected void configure() {
      addFilterChain(MOUNT_POINT + "/**",
          NexusAuthenticationFilter.NAME,
          AnonymousFilter.NAME,
          AntiCsrfFilter.NAME);
    }
  });
}
 
Example #18
Source File: TestHsWebServicesJobs.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testJobCountersForKilledJob() throws Exception {
  WebResource r = resource();
  appContext = new MockHistoryContext(0, 1, 1, 1, true);
  injector = Guice.createInjector(new ServletModule() {
    @Override
    protected void configureServlets() {

      webApp = mock(HsWebApp.class);
      when(webApp.name()).thenReturn("hsmockwebapp");

      bind(JAXBContextResolver.class);
      bind(HsWebServices.class);
      bind(GenericExceptionHandler.class);
      bind(WebApp.class).toInstance(webApp);
      bind(AppContext.class).toInstance(appContext);
      bind(HistoryContext.class).toInstance(appContext);
      bind(Configuration.class).toInstance(conf);

      serve("/*").with(GuiceContainer.class);
    }
  });
  
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("counters/")
        .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject info = json.getJSONObject("jobCounters");
    WebServicesTestUtils.checkStringMatch("id", MRApps.toString(id),
        info.getString("id"));
    assertTrue("Job shouldn't contain any counters", info.length() == 1);
  }
}
 
Example #19
Source File: MCRDefaultModule.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void configure() {

    // PROCESSING API
    bind(MCRProcessableRegistry.class).to(MCRCentralProcessableRegistry.class);
    if (MCRStartupHandler.isWebApp()) {
        install(new ServletModule());
    }
}
 
Example #20
Source File: TestHsWebServicesJobs.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test
public void testJobCountersForKilledJob() throws Exception {
  WebResource r = resource();
  appContext = new MockHistoryContext(0, 1, 1, 1, true);
  injector = Guice.createInjector(new ServletModule() {
    @Override
    protected void configureServlets() {

      webApp = mock(HsWebApp.class);
      when(webApp.name()).thenReturn("hsmockwebapp");

      bind(JAXBContextResolver.class);
      bind(HsWebServices.class);
      bind(GenericExceptionHandler.class);
      bind(WebApp.class).toInstance(webApp);
      bind(AppContext.class).toInstance(appContext);
      bind(HistoryContext.class).toInstance(appContext);
      bind(Configuration.class).toInstance(conf);

      serve("/*").with(GuiceContainer.class);
    }
  });
  
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("counters/")
        .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject info = json.getJSONObject("jobCounters");
    WebServicesTestUtils.checkStringMatch("id", MRApps.toString(id),
        info.getString("id"));
    assertTrue("Job shouldn't contain any counters", info.length() == 1);
  }
}
 
Example #21
Source File: SiestaModule.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void doConfigure() {
  install(new ResteasyModule());

  install(new ServletModule()
  {
    @Override
    protected void configureServlets() {
      log.debug("Mount point: {}", MOUNT_POINT);

      bind(SiestaServlet.class);
      serve(MOUNT_POINT + "/*").with(SiestaServlet.class, ImmutableMap.of(
          "resteasy.servlet.mapping.prefix", MOUNT_POINT
      ));
      filter(MOUNT_POINT + "/*").through(SecurityFilter.class);
    }
  });

  install(new FilterChainModule()
  {
    @Override
    protected void configure() {
      addFilterChain(MOUNT_POINT + "/**",
          NexusAuthenticationFilter.NAME,
          AnonymousFilter.NAME,
          AntiCsrfFilter.NAME);
    }
  });
}
 
Example #22
Source File: GuiceModelParser.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
private static ModuleDeclaration initModule(final Map<String, ModuleDeclaration> index,
                                            final String name) {
    ModuleDeclaration mod = index.get(name);
    if (mod == null) {
        mod = new ModuleDeclaration();
        mod.setType(BindingUtils.getModuleClass(name));
        if (ServletModule.class.isAssignableFrom(mod.getType())) {
            mod.getMarkers().add("WEB");
        }
        index.put(name, mod);
    }
    return mod;
}
 
Example #23
Source File: WebModule.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void configure() {
  bind(GuiceFilter.class).to(DynamicGuiceFilter.class);

  // our configuration needs to be first-most when calculating order (some fudge room for edge-cases)
  final Binder highPriorityBinder = binder().withSource(Sources.prioritize(0x70000000));

  highPriorityBinder.install(new ServletModule()
  {
    @Override
    protected void configureServlets() {
      bind(HeaderPatternFilter.class);
      bind(EnvironmentFilter.class);
      bind(ErrorPageFilter.class);

      filter("/*").through(HeaderPatternFilter.class);
      filter("/*").through(EnvironmentFilter.class);
      filter("/*").through(ErrorPageFilter.class);

      bind(ErrorPageServlet.class);

      serve("/error.html").with(ErrorPageServlet.class);
      serve("/throw.html").with(ThrowServlet.class);
    }
  });

  highPriorityBinder.install(new MetricsModule());

  if (getBoolean("nexus.orient.enabled", true)) {
    install(new OrientModule());
  }
}
 
Example #24
Source File: ServletContextListener.java    From openid4java with Apache License 2.0 5 votes vote down vote up
@Override
protected Injector getInjector() {
  return Guice.createInjector(
      new ServletModule() {
        @Override
        protected void configureServlets() {
          filter("/*").through(PrepareRequestAttributesFilter.class);
        }
      },
      new AppEngineGuiceModule());
}
 
Example #25
Source File: MetricsModule.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void configure() {
  // NOTE: AdminServletModule (metrics-guice integration) generates invalid links, so wire up servlets ourselves

  final Clock clock = Clock.defaultClock();
  bind(Clock.class).toInstance(clock);

  final JsonFactory jsonFactory = new JsonFactory(new ObjectMapper());
  bind(JsonFactory.class).toInstance(jsonFactory);

  install(new ServletModule()
  {
    @Override
    protected void configureServlets() {
      bind(MetricsServlet.class);
      bind(HealthCheckServlet.class);

      serve(MOUNT_POINT + "/ping").with(new PingServlet());
      serve(MOUNT_POINT + "/threads").with(new ThreadDumpServlet());
      serve(MOUNT_POINT + "/data").with(MetricsServlet.class);
      serve(MOUNT_POINT + "/healthcheck").with(HealthCheckServlet.class);
      serve(MOUNT_POINT + "/prometheus").with(new io.prometheus.client.exporter.MetricsServlet());

      // record metrics for all webapp access
      filter("/*").through(new InstrumentedFilter());

      bind(SecurityFilter.class);

      // configure security
      filter(MOUNT_POINT + "/*").through(SecurityFilter.class);
    }
  });

  // require permission to use endpoints
  install(new FilterChainModule()
  {
    @Override
    protected void configure() {
      addFilterChain(MOUNT_POINT + "/**",
          NexusAuthenticationFilter.NAME,
          AnonymousFilter.NAME,
          AntiCsrfFilter.NAME,
          PermissionsFilter.config("nexus:metrics:read"));
    }
  });

  log.info("Metrics support configured");
}
 
Example #26
Source File: ServerRpcProvider.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
public void startWebSocketServer(final Injector injector) {
  httpServer = new Server();

  List<Connector> connectors = getSelectChannelConnectors(httpAddresses);
  if (connectors.isEmpty()) {
    LOG.severe("No valid http end point address provided!");
  }
  for (Connector connector : connectors) {
    httpServer.addConnector(connector);
  }
  final WebAppContext context = new WebAppContext();

  context.setParentLoaderPriority(true);

  if (jettySessionManager != null) {
    // This disables JSessionIDs in URLs redirects
    // see: http://stackoverflow.com/questions/7727534/how-do-you-disable-jsessionid-for-jetty-running-with-the-eclipse-jetty-maven-plu
    // and: http://jira.codehaus.org/browse/JETTY-467?focusedCommentId=114884&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-114884
    jettySessionManager.setSessionIdPathParameterName(null);

    context.getSessionHandler().setSessionManager(jettySessionManager);
  }
  final ResourceCollection resources = new ResourceCollection(resourceBases);
  context.setBaseResource(resources);

  addWebSocketServlets();

  try {

    final ServletModule servletModule = getServletModule();

    ServletContextListener contextListener = new GuiceServletContextListener() {

      private final Injector childInjector = injector.createChildInjector(servletModule);

      @Override
      protected Injector getInjector() {
        return childInjector;
      }
    };

    context.addEventListener(contextListener);
    context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    context.addFilter(GzipFilter.class, "/webclient/*", EnumSet.allOf(DispatcherType.class));
    httpServer.setHandler(context);

    httpServer.start();
    restoreSessions();

  } catch (Exception e) { // yes, .start() throws "Exception"
    LOG.severe("Fatal error starting http server.", e);
    return;
  }
  LOG.fine("WebSocket server running.");
}
 
Example #27
Source File: JettyServerModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static ServletContextListener makeServletContextListener(
    Injector parentInjector,
    Function<ServletContext, Module> childModuleFactory) {

  ServletContextListener contextListener = new GuiceResteasyBootstrapServletContextListener() {
    @Override
    protected List<? extends Module> getModules(ServletContext context) {
      return ImmutableList.of(
          childModuleFactory.apply(context),
          new ServletModule() {
            @Override
            protected void configureServlets() {
              bind(HttpStatsFilter.class).in(Singleton.class);
              filter("*").through(HttpStatsFilter.class);

              bind(LeaderRedirectFilter.class).in(Singleton.class);
              filterRegex(allOf(LEADER_ENDPOINTS))
                  .through(LeaderRedirectFilter.class);

              filterRegex("/assets/scheduler(?:/.*)?").through(LeaderRedirectFilter.class);

              serve("/assets", "/assets/*")
                  .with(new DefaultServlet(), ImmutableMap.of(
                      "cacheControl", "max-age=3600",
                      "resourceBase", STATIC_ASSETS_ROOT,
                      "dirAllowed", "false"));

              for (Class<?> jaxRsHandler : JAX_RS_ENDPOINTS.keySet()) {
                bind(jaxRsHandler);
              }
            }
          }
      );
    }
  };

  // Injects the Injector into GuiceResteasyBootstrapServletContextListener.
  parentInjector.injectMembers(contextListener);

  return contextListener;
}
 
Example #28
Source File: BaseTest.java    From everrest with Eclipse Public License 2.0 4 votes vote down vote up
protected ServletModule getServletModule() {
    return new ServletModule();
}
 
Example #29
Source File: CheBootstrap.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * see http://google-guice.googlecode.com/git/javadoc/com/google/inject/servlet/ServletModule.html
 */
@Override
protected ServletModule getServletModule() {
  // Servlets and other web components may be configured with custom Modules.
  return null;
}
 
Example #30
Source File: ChannelSetUpTest.java    From joynr with Apache License 2.0 4 votes vote down vote up
@Override
protected ServletModule getServletTestModule() {

    return new ServletModule() {

        @Override
        protected void configureServlets() {

            bind(ChannelService.class).toInstance(mock);

            bind(ChannelServiceRestAdapter.class);

            serve("/some-channel-service/*").with(GuiceContainer.class);
        }

    };
}