com.google.inject.servlet.GuiceServletContextListener Java Examples

The following examples show how to use com.google.inject.servlet.GuiceServletContextListener. 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: SiestaTestSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Before
public void startJetty() throws Exception {
  servletTester = new ServletTester();
  servletTester.getContext().addEventListener(new GuiceServletContextListener()
  {
    final Injector injector = Guice.createInjector(new TestModule());

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

  url = servletTester.createConnector(true) + TestModule.MOUNT_POINT;
  servletTester.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
  servletTester.addServlet(DummyServlet.class, "/*");
  servletTester.start();

  client = ClientBuilder.newClient();
}
 
Example #2
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 #3
Source File: ServletScanner.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void createServletEventListener(Environment environment, final Injector injector) {
    environment.getApplicationContext().addEventListener(new GuiceServletContextListener() {
        @Override
        protected Injector getInjector() {
            return injector;
        }
    });
}
 
Example #4
Source File: AbstractServiceInterfaceTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    // starts the server with a random port
    jettyServer = new Server(0);

    WebAppContext bpCtrlWebapp = new WebAppContext();
    bpCtrlWebapp.setResourceBase("./src/main/java");
    bpCtrlWebapp.setParentLoaderPriority(true);

    bpCtrlWebapp.addFilter(GuiceFilter.class, "/*", null);
    bpCtrlWebapp.addEventListener(new GuiceServletContextListener() {

        private Injector injector;

        @Override
        public void contextInitialized(ServletContextEvent servletContextEvent) {
            injector = Guice.createInjector(getServletTestModule());
            super.contextInitialized(servletContextEvent);
        }

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

    jettyServer.setHandler(bpCtrlWebapp);

    jettyServer.start();

    int port = ((ServerConnector) jettyServer.getConnectors()[0]).getLocalPort();
    serverUrl = String.format("http://localhost:%d", port);
}
 
Example #5
Source File: GuiceBundle.java    From dropwizard-guicier with 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 #6
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 #7
Source File: WebServer.java    From AisAbnormal with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void start() throws Exception {
    ((ServerConnector) server.getConnectors()[0]).setReuseAddress(true);

    // Root context
    context.setContextPath("/abnormal");

    // Setup static content
    context.setResourceBase("src/main/webapp/");
    context.addServlet(DefaultServlet.class, "/");

    // Enable Jersey debug output
    context.setInitParameter("com.sun.jersey.config.statistic.Trace", "true");

    // Enable CORS - cross origin resource sharing
    FilterHolder cors = new FilterHolder();
    cors.setInitParameter("allowedOrigins", "https?://localhost:*, https?://*.e-navigation.net:*");
    cors.setInitParameter("allowedHeaders", "*");
    cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
    cors.setFilter(new CrossOriginFilter());
    context.addFilter(cors, "*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC, DispatcherType.INCLUDE));

    // Little hack to satisfy OpenLayers URLs in DMA context
    RewritePatternRule openlayersRewriteRule = new RewritePatternRule();
    openlayersRewriteRule.setPattern("/abnormal/theme/*");
    openlayersRewriteRule.setReplacement("/abnormal/js/theme/");

    RewriteHandler rewrite = new RewriteHandler();
    rewrite.setRewriteRequestURI(true);
    rewrite.setRewritePathInfo(false);
    rewrite.setOriginalPathAttribute("requestedPath");
    rewrite.addRule(openlayersRewriteRule);
    rewrite.setHandler(context);
    server.setHandler(rewrite);

    // Setup Guice-Jersey integration
    context.addEventListener(new GuiceServletContextListener() {
        @Override
        protected Injector getInjector() {
            return Guice.createInjector(new RestModule(
                    repositoryName,
                    pathToEventDatabase,
                    eventRepositoryType,
                    eventDataDbHost,
                    eventDataDbPort,
                    eventDataDbName,
                    eventDataDbUsername,
                    eventDataDbPassword
            ));
        }
    });
    context.addFilter(com.google.inject.servlet.GuiceFilter.class, "/rest/*", EnumSet.allOf(DispatcherType.class));

    // Start the server
    server.start();
}