Java Code Examples for com.google.inject.servlet.ServletModule

The following examples show how to use com.google.inject.servlet.ServletModule. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: nexus-public   Source File: TestModule.java    License: 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 2
Source Project: nexus-public   Source File: WebResourcesModule.java    License: 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 3
Source Project: nexus-public   Source File: RaptureModule.java    License: 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 4
Source Project: swellrt   Source File: ServerRpcProvider.java    License: 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 5
Source Project: spectator   Source File: GuiceServletFilterTest.java    License: 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 6
Source Project: incubator-retired-wave   Source File: ServerRpcProvider.java    License: 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
@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 8
@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 9
Source Project: angulardemorestful   Source File: NgDemoApplicationSetup.java    License: 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 10
Source Project: angulardemorestful   Source File: ServerProvider.java    License: 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 11
Source Project: rejoiner   Source File: GraphQlServer.java    License: 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 12
Source Project: hadoop   Source File: TestHsWebServicesJobs.java    License: 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 13
Source Project: mycore   Source File: MCRDefaultModule.java    License: 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 14
Source Project: big-c   Source File: TestHsWebServicesJobs.java    License: 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 15
Source Project: nexus-public   Source File: SiestaModule.java    License: 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 16
Source Project: nexus-public   Source File: ExtDirectModule.java    License: 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 17
Source Project: nexus-public   Source File: WebModule.java    License: 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 18
Source Project: openid4java   Source File: ServletContextListener.java    License: 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 19
Source Project: dropwizard-guicey   Source File: GuiceModelParser.java    License: 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 20
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 21
/**
 * 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 22
Source Project: rome   Source File: ServerModule.java    License: 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 23
Source Project: suro   Source File: StatusServer.java    License: 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 24
Source Project: EVCache   Source File: StartServer.java    License: 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 25
Source Project: nexus-public   Source File: MetricsModule.java    License: 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 Project: che   Source File: CheBootstrap.java    License: 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 27
Source Project: dropwizard-guicier   Source File: GuiceBundle.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void run(final T configuration, final Environment environment) throws Exception {
  for (DropwizardAwareModule<T> dropwizardAwareModule : dropwizardAwareModules) {
    dropwizardAwareModule.setBootstrap(bootstrap);
    dropwizardAwareModule.setConfiguration(configuration);
    dropwizardAwareModule.setEnvironment(environment);
  }

  final DropwizardModule dropwizardModule = new DropwizardModule(environment);
  // We assume that the next service locator will be the main application one
  final String serviceLocatorName = getNextServiceLocatorName();
  ImmutableSet.Builder<Module> modulesBuilder =
      ImmutableSet.<Module>builder()
          .addAll(guiceModules)
          .addAll(dropwizardAwareModules)
          .add(new ServletModule())
          .add(dropwizardModule)
          .add(new JerseyGuiceModule(serviceLocatorName))
          .add(new JerseyGuicierModule())
          .add(binder -> {
            binder.bind(Environment.class).toInstance(environment);
            binder.bind(configClass).toInstance(configuration);
          });
  if (enableGuiceEnforcer) {
    modulesBuilder.add(new GuiceEnforcerModule());
  }
  this.injector = injectorFactory.create(guiceStage, modulesBuilder.build());

  JerseyGuiceUtils.install((name, parent) -> {
    if (!name.startsWith("__HK2_")) {
      return null;
    } else if (serviceLocatorName.equals(name)) {
      return injector.getInstance(ServiceLocator.class);
    } else {
      LOG.debug("Returning a new ServiceLocator for name '{}'", name);
      return JerseyGuiceUtils.newServiceLocator(name, parent);
    }
  });

  dropwizardModule.register(injector);

  environment.servlets().addFilter("Guice Filter", GuiceFilter.class).addMappingForUrlPatterns(null, false, "/*");
  environment.servlets().addServletListeners(new GuiceServletContextListener() {

    @Override
    protected Injector getInjector() {
      return injector;
    }
  });
}
 
Example 28
private Injector createInjector(final Config config, final Optional<LeaderFinder<URIMetadata>> leaderFinder) {
  final SharedResourcesBroker<ThrottlingServerScopes> topLevelBroker =
      SharedResourcesBrokerFactory.createDefaultTopLevelBroker(config, ThrottlingServerScopes.GLOBAL.defaultScopeInstance());

  return Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
      try {

        if (_sleeper == null) {
          _sleeper = new Sleeper();
        }

        RestLiConfig restLiConfig = new RestLiConfig();
        restLiConfig.setResourcePackageNames("org.apache.gobblin.restli.throttling");
        bind(RestLiConfig.class).toInstance(restLiConfig);
        bind(Sleeper.class).toInstance(_sleeper);

        bind(SharedResourcesBroker.class).annotatedWith(Names.named(LimiterServerResource.BROKER_INJECT_NAME)).toInstance(topLevelBroker);

        MetricContext metricContext =
            topLevelBroker.getSharedResource(new MetricContextFactory<ThrottlingServerScopes>(), new MetricContextKey());
        Timer timer = metricContext.timer(LimiterServerResource.REQUEST_TIMER_NAME);

        bind(MetricContext.class).annotatedWith(Names.named(LimiterServerResource.METRIC_CONTEXT_INJECT_NAME)).toInstance(metricContext);
        bind(Timer.class).annotatedWith(Names.named(LimiterServerResource.REQUEST_TIMER_INJECT_NAME)).toInstance(timer);

        bind(new TypeLiteral<Optional<LeaderFinder<URIMetadata>>>() {
        }).annotatedWith(Names.named(LimiterServerResource.LEADER_FINDER_INJECT_NAME)).toInstance(leaderFinder);

        List<RestFilter> restFilters = new ArrayList<>();
        restFilters.add(new ServerCompressionFilter(EncodingType.SNAPPY.getHttpName()));
        List<StreamFilter> streamFilters = new ArrayList<>();
        streamFilters.add(new SimpleLoggingFilter());
        FilterChain filterChain = FilterChains.create(restFilters, streamFilters);
        bind(FilterChain.class).toInstance(filterChain);
      } catch (NotConfiguredException nce) {
        throw new RuntimeException(nce);
      }
    }
  }, new ServletModule() {
    @Override
    protected void configureServlets() {
      serve("/*").with(GuiceRestliServlet.class);
    }
  });
}
 
Example 29
Source Project: everrest   Source File: BaseTest.java    License: Eclipse Public License 2.0 4 votes vote down vote up
protected ServletModule getServletModule() {
    return new ServletModule();
}
 
Example 30
Source Project: incubator-retired-wave   Source File: ServerRpcProvider.java    License: 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.");
}