com.google.inject.servlet.GuiceFilter Java Examples

The following examples show how to use com.google.inject.servlet.GuiceFilter. 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: JettyServerProvider.java    From browserup-proxy with Apache License 2.0 8 votes vote down vote up
@Inject
public JettyServerProvider(@Named("port") int port, @Named("address") String address, MitmProxyManager proxyManager) throws UnknownHostException {
    OpenApiResource openApiResource = new OpenApiResource();
    openApiResource.setConfigLocation(SWAGGER_CONFIG_NAME);

    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.packages(SWAGGER_PACKAGE);
    resourceConfig.register(openApiResource);
    resourceConfig.register(proxyManagerToHkBinder(proxyManager));
    resourceConfig.register(JacksonFeature.class);
    resourceConfig.register(ConstraintViolationExceptionMapper.class);
    resourceConfig.registerClasses(LoggingFilter.class);

    resourceConfig.property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    resourceConfig.property(ServerProperties.WADL_FEATURE_DISABLE, true);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    context.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));;
    context.addServlet(DefaultServlet.class, "/");
    context.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    server = new Server(new InetSocketAddress(InetAddress.getByName(address), port));
    server.setHandler(context);
}
 
Example #2
Source File: ExplorerAppTest.java    From Nicobar with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void init() throws Exception {
    System.setProperty("archaius.deployment.applicationId","scriptmanager-app");
    System.setProperty("archaius.deployment.environment","dev");

    server = new Server(TEST_LOCAL_PORT);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addEventListener(new KaryonGuiceContextListener());

    context.addFilter(GuiceFilter.class, "/*", 1);
    context.addServlet(DefaultServlet.class, "/");

    server.setHandler(context);

    server.start();
}
 
Example #3
Source File: AbstractJoynrServletModule.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Override
final protected void configureServlets() {

    // GuiceFilter is instantiated here instead of configured in
    // web.xml to allow for more than one servlet per servlet
    // container.
    // See documentation of web.xml for details.
    bind(GuiceFilter.class);

    configureJoynrServlets();

    // Route all requests through GuiceContainer
    bindStaticWebResources();
    bindJoynrServletClass();

    bindAnnotatedFilters();
}
 
Example #4
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 #5
Source File: NexusContextModule.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void configure() {

  // we will look these up later...
  requireBinding(GuiceFilter.class);
  requireBinding(BeanManager.class);
  requireBinding(ApplicationVersion.class);

  bind(ServletContext.class).toInstance(servletContext);
  bind(ParameterKeys.PROPERTIES).toInstance(nexusProperties);

  install(new StateGuardModule());
  install(new TransactionModule());
  install(new TimeTypeConverter());
  install(new WebSecurityModule(servletContext));

  // enable OSGi service lookup of Karaf components
  final MutableBeanLocator locator = new DefaultBeanLocator();
  locator.add(new ServiceBindings(bundleContext, ALLOW_SERVICES, IGNORE_SERVICES, Integer.MIN_VALUE));
  bind(MutableBeanLocator.class).toInstance(locator);

  bind(ManagedLifecycleManager.class).toInstance(new NexusLifecycleManager(locator, bundleContext.getBundle(0)));
}
 
Example #6
Source File: OrienteerFilter.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
private void initFilter(final FilterConfig filterConfig) throws ServletException {
    filter = new GuiceFilter();
    try {
        filter.init(filterConfig);
        if (OrienteerClassLoader.isUseUnTrusted())
            OrienteerClassLoader.clearDisabledModules();
        OrienteerWebApplication app = OrienteerWebApplication.lookupApplication();
        if (app != null) {
            OModulesLoadFailedPanel.clearInfoAboutUsers();
            app.setLoadInSafeMode(!OrienteerClassLoader.isUseUnTrusted() || OrienteerClassLoader.isUseOrienteerClassLoader());
            app.setLoadWithoutModules(OrienteerClassLoader.isUseOrienteerClassLoader());
        }
    } catch (Throwable t) {
        if (OrienteerClassLoader.isUseUnTrusted()) {
            LOG.warn("Can't run Orienteer with untrusted classloader. Orienteer runs with trusted classloader.", t);
            useTrustedClassLoader();
        } else {
            LOG.warn("Can't run Orienteer with trusted classloader. Orienteer runs with custom classloader.", t);
            useOrienteerClassLoader();
        }
        reloading = false;
        instance.reload(1000);
    }
}
 
Example #7
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 #8
Source File: ExampleServerTest.java    From rack-servlet with Apache License 2.0 5 votes vote down vote up
public ExampleServer(Module... modules) {
  ServletContextHandler handler = new ServletContextHandler();
  handler.setContextPath("/");
  handler.addEventListener(new GuiceInjectorServletContextListener(modules));
  handler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
  handler.addServlet(DefaultServlet.class, "/");

  server = new Server(0);
  server.setHandler(handler);
}
 
Example #9
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 #10
Source File: PaasLauncher.java    From staash with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    LOG.info("Starting PAAS");
    
    // Create the server.
    Server server = new Server(DEFAULT_PORT);
     
    // Create a servlet context and add the jersey servlet.
    ServletContextHandler sch = new ServletContextHandler(server, "/");
     
    // Add our Guice listener that includes our bindings
    sch.addEventListener(new PaasGuiceServletConfig());
     
    // Then add GuiceFilter and configure the server to 
    // reroute all requests through this filter. 
    sch.addFilter(GuiceFilter.class, "/*", null);
     
    // Must add DefaultServlet for embedded Jetty. 
    // Failing to do this will cause 404 errors.
    // This is not needed if web.xml is used instead.
    sch.addServlet(DefaultServlet.class, "/");
     
    // Start the server
    server.start();
    server.join();  
    
    LOG.info("Stopping PAAS");
}
 
Example #11
Source File: WebPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
private FilterDefinition buildGuiceFilterDefinition() {
    FilterDefinition guiceFilter = new FilterDefinition("guice", GuiceFilter.class);
    guiceFilter.setPriority(SeedFilterPriority.GUICE);
    guiceFilter.setAsyncSupported(true);
    guiceFilter.addMappings(new FilterDefinition.Mapping("/*"));
    return guiceFilter;
}
 
Example #12
Source File: HttpServer.java    From PeerWasp with MIT License 5 votes vote down vote up
private void initHandler() {
	// default servlet required for jetty to accept all requests
	// (guice will define mappings between urls and servlets)
	ServletContextHandler handler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
	handler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
	handler.addServlet(DefaultServlet.class, "/");
}
 
Example #13
Source File: GuiceWebModule.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
protected void configureServlets() {
    // avoid registrations for guice reports (performing modules analysis and so calling this code many times)
    if (currentStage() != Stage.TOOL) {
        final GuiceFilter guiceFilter = new GuiceFilter();
        environment.servlets().addFilter(GUICE_FILTER, guiceFilter)
                .addMappingForUrlPatterns(dispatcherTypes, false, ROOT_PATH);
        environment.admin().addFilter(GUICE_FILTER, new AdminGuiceFilter(guiceFilter))
                .addMappingForUrlPatterns(dispatcherTypes, false, ROOT_PATH);
    }
}
 
Example #14
Source File: GuiceServletFilterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void init() throws Exception {
  server = new Server(new InetSocketAddress("localhost", 0));
  ServletContextHandler handler = new ServletContextHandler(server, "/");
  handler.addEventListener(new TestListener());
  handler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
  server.setHandler(handler);
  server.start();
  baseUri = server.getURI();
}
 
Example #15
Source File: YanagishimaServer.java    From yanagishima with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Properties properties = loadProperties(args, new OptionParser());
    YanagishimaConfig config = new YanagishimaConfig(properties);

    Injector injector = createInjector(properties);

    createTables(injector.getInstance(TinyORM.class), config.getDatabaseType());

    Server server = new Server(config.getServerPort());
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", -1);

    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    servletContextHandler.addFilter(new FilterHolder(new YanagishimaFilter(config.corsEnabled(), config.getAuditHttpHeaderName())), "/*", EnumSet.of(DispatcherType.REQUEST));
    servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    servletContextHandler.addServlet(DefaultServlet.class, "/");
    servletContextHandler.setResourceBase(properties.getProperty("web.resource.dir", "web"));

    LOGGER.info("Yanagishima Server started...");
    server.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            LOGGER.info("Shutting down Yanagishima Server...");
            try {
                server.stop();
                server.destroy();
            } catch (Exception e) {
                LOGGER.error("Error while shutting down Yanagishima Server", e);
            }
        }
    });
    LOGGER.info("Yanagishima Server running port " + config.getServerPort());
}
 
Example #16
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 #17
Source File: NexusContextListener.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Register our dynamic filter with the bootstrap listener.
 */
private void registerNexusFilter() {
  if (registration == null) {
    final Filter filter = injector.getInstance(GuiceFilter.class);
    final Dictionary<String, ?> filterProperties = new Hashtable<>(singletonMap("name", "nexus"));
    registration = bundleContext.registerService(Filter.class, filter, filterProperties);
  }
}
 
Example #18
Source File: JettyServer.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void start() throws Exception {

    if (server != null) {
        throw new IllegalStateException("Server is already running");
    }

    this.server = new Server(port);

    ServletContextHandler context = new ServletContextHandler();
    context.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    context.setWelcomeFiles(new String[]{"index.html"});

    server.setHandler(context);
    if (getBoolean("enableJMX")) {
        System.out.println("configure MBean container...");
        configureMBeanContainer(server);
    }
    server.start();
    System.out.println("Started server on http://localhost:" + port + "/");
    try {
        if (getBoolean("loadSample")) {
            System.out.println("Creating kitchensink workflow");
            createKitchenSink(port);
        }
    } catch (Exception e) {
        logger.error("Error loading sample!", e);
    }

    if (join) {
        server.join();
    }

}
 
Example #19
Source File: JettyComposer.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
public static void compose(Server server) {
    //Servlets + Guice
    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    servletContextHandler.addServlet(DefaultServlet.class, "/");

    //JMX stuff...
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addEventListener(mbContainer);
    server.addBean(mbContainer);
    server.addBean(Log.getLog());
}
 
Example #20
Source File: JerseyUtil.java    From robe with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void registerGuiceFilter(Environment environment) {
    environment.servlets().addFilter("Guice Filter", GuiceFilter.class)
            .addMappingForUrlPatterns(null, false, environment.getApplicationContext().getContextPath() + "*");
}
 
Example #21
Source File: TestObjectFactory.java    From incubator-myriad with Apache License 2.0 4 votes vote down vote up
public static MyriadWebServer getMyriadWebServer(MyriadConfiguration cfg) {
  Server server = TestObjectFactory.getJettyServer();
  HttpConnectorProvider provider = new HttpConnectorProvider(cfg);
  Connector connector = provider.get();
  return new MyriadWebServer(server, connector, new GuiceFilter());
}
 
Example #22
Source File: AdminGuiceFilter.java    From dropwizard-guicey with MIT License 4 votes vote down vote up
public AdminGuiceFilter(final GuiceFilter filter) {
    this.filter = filter;
}
 
Example #23
Source File: MyriadWebServer.java    From incubator-myriad with Apache License 2.0 4 votes vote down vote up
@Inject
public MyriadWebServer(Server jetty, Connector connector, GuiceFilter filter) {
  this.jetty = jetty;
  this.connector = connector;
  this.filter = filter;
}
 
Example #24
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 #25
Source File: WebModule.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
@Override
protected void configureServlets() {
    bind(GuiceFilter.class).in(Scopes.SINGLETON);
}
 
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: WebApp.java    From big-c with Apache License 2.0 4 votes vote down vote up
void setGuiceFilter(GuiceFilter instance) {
  guiceFilter = instance;
}
 
Example #28
Source File: WebApp.java    From hadoop with Apache License 2.0 4 votes vote down vote up
void setGuiceFilter(GuiceFilter instance) {
  guiceFilter = instance;
}