@Override
 public Handler createHandler() throws ConfigurationException {
   // set up jersey servlet
   ResourceConfig config = new ResourceConfig();
   // we package everything into a runnable jar using OneJAR, which provides its own class loader.
   // as the result, Jersey classpath scanning won't work properly for now.
   // hopefully this can be fixed soon. right now we need to specify classes.
   config.register(Echo.class);
   config.register(LogService.class);
   config.register(PageService.class);
   config.register(TaskService.class);
   // binder for HK2 to inject the controller to Jersey resource instances
   config.register(
       new AbstractBinder() {
         @Override
         protected void configure() {
           bind(controller).to(Controller.class);
         }
       });
   ServletContainer container = new ServletContainer(config);
   ServletContextHandler handler = new ServletContextHandler();
   handler.setContextPath("/DownloaderPool");
   handler.addServlet(new ServletHolder(container), "/*");
   return handler;
 }
Exemplo n.º 2
0
 public static ResourceConfig registerHK2Services(final ResourceConfig rc) {
   rc.register(
           new AbstractBinder() {
             @Override
             protected void configure() {
               bind(BuilderHelper.link(HK2ServiceSingleton.class).in(Singleton.class).build());
             }
           })
       .register(
           new AbstractBinder() {
             @Override
             protected void configure() {
               bind(
                   BuilderHelper.link(HK2ServiceRequestScoped.class)
                       .in(RequestScoped.class)
                       .build());
             }
           })
       .register(
           new AbstractBinder() {
             @Override
             protected void configure() {
               bind(BuilderHelper.link(HK2ServicePerLookup.class).in(PerLookup.class).build());
             }
           });
   return rc;
 }
Exemplo n.º 3
0
 @Override
 protected Application configure() {
   ResourceConfig resourceConfig = new ResourceConfig();
   ExampleApplicationConfiguration exampleApplicationConfiguration =
       new ExampleApplicationConfiguration();
   exampleApplicationConfiguration.setName("Ray");
   resourceConfig.registerInstances(new UrsusApplicationBinder(exampleApplicationConfiguration));
   resourceConfig.register(HelloWorldResource.class);
   return resourceConfig;
 }
Exemplo n.º 4
0
  @Override
  protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);

    ResourceConfig config = new ResourceConfig();
    // config.register(new FastJsonFeature()).register(FastJsonProvider.class);
    config.register(new FastJsonFeature()).register(new FastJsonProvider().setPretty(true));
    config.packages("com.alibaba.fastjson");
    return config;
  }
  @Override
  protected Application configure() {
    faker = new Faker();

    final Configuration configuration;
    try {
      configuration = new Configuration(CONFIG);
    } catch (IOException | NumberFormatException e) {
      System.out.println("Properties error:");
      System.out.println(e.getMessage());
      System.exit(1);
      return null;
    }

    final AccountServiceImpl accountService;
    try {
      accountService =
          new AccountServiceImpl(
              configuration.getDbName(),
              configuration.getDbHost(),
              configuration.getDbPort(),
              configuration.getDbUsername(),
              configuration.getDbPassword());
    } catch (SQLException | IOException e) {
      e.printStackTrace();
      System.exit(1);
      return null;
    }

    final ResourceConfig config = new ResourceConfig(Session.class, Users.class);
    config.register(new AccountServiceAbstractBinder(accountService));
    final HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
    final HttpSession httpSession = mock(HttpSession.class);
    final String sessionId = faker.lorem().fixedString(15);
    Mockito.when(httpServletRequest.getSession()).thenReturn(httpSession);
    Mockito.when(httpSession.getId()).thenReturn(sessionId);

    config.register(new ServletAbstractBinder(httpServletRequest));
    return config;
  }
Exemplo n.º 6
0
 /**
  * Construct a new instance with an application descriptor that defines how the test container is
  * configured.
  *
  * @param jaxrsApplication an application describing how to configure the test container.
  * @throws TestContainerException if the default test container factory cannot be obtained, or the
  *     application descriptor is not supported by the test container factory.
  */
 public JerseyTest(Application jaxrsApplication) throws TestContainerException {
   ResourceConfig config = getResourceConfig(jaxrsApplication);
   config.register(
       new ServiceFinderBinder<TestContainerFactory>(
           TestContainerFactory.class, null, RuntimeType.SERVER));
   if (isLogRecordingEnabled()) {
     registerLogHandler();
   }
   this.application = new ApplicationHandler(config);
   this.tc = getContainer(application, getTestContainerFactory());
   if (isLogRecordingEnabled()) {
     loggedStartupRecords.addAll(loggedRuntimeRecords);
     loggedRuntimeRecords.clear();
     unregisterLogHandler();
   }
 }
Exemplo n.º 7
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public Task<Void> start() {

    // Ensuring that jersey will use singletons from the orbit container.
    ServiceLocator locator = Injections.createLocator();
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    final List<Class<?>> classes = new ArrayList<>(providers);
    if (container != null) {
      classes.addAll(container.getClasses());
      for (final Class<?> c : container.getClasses()) {
        if (c.isAnnotationPresent(Singleton.class)) {
          Injections.addBinding(
              Injections.newFactoryBinder(
                      new Factory() {
                        @Override
                        public Object provide() {
                          return container.get(c);
                        }

                        @Override
                        public void dispose(final Object instance) {}
                      })
                  .to(c),
              dc);
        }
      }
    }
    dc.commit();

    final ResourceConfig resourceConfig = new ResourceConfig();

    // installing jax-rs classes known by the orbit container.
    for (final Class c : classes) {
      if (c.isAnnotationPresent(javax.ws.rs.Path.class)
          || c.isAnnotationPresent(javax.ws.rs.ext.Provider.class)) {
        resourceConfig.register(c);
      }
    }

    final WebAppContext webAppContext = new WebAppContext();
    final ProtectionDomain protectionDomain = EmbeddedHttpServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    logger.info(location.toExternalForm());
    webAppContext.setInitParameter("useFileMappedBuffer", "false");
    webAppContext.setWar(location.toExternalForm());
    // this sets the default service locator to one that bridges to the orbit container.
    webAppContext.getServletContext().setAttribute(ServletProperties.SERVICE_LOCATOR, locator);
    webAppContext.setContextPath("/*");
    webAppContext.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    final ContextHandler resourceContext = new ContextHandler();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});
    resourceHandler.setBaseResource(Resource.newClassPathResource("/web"));

    resourceContext.setHandler(resourceHandler);
    resourceContext.setInitParameter("useFileMappedBuffer", "false");
    final ContextHandlerCollection contexts = new ContextHandlerCollection();

    contexts.setHandlers(
        new Handler[] {
          wrapHandlerWithMetrics(resourceContext, "resourceContext"),
          wrapHandlerWithMetrics(webAppContext, "webAppContext")
        });

    server = new Server(port);
    server.setHandler(contexts);
    try {
      /// Initialize javax.websocket layer
      final ServerContainer serverContainer =
          WebSocketServerContainerInitializer.configureContext(webAppContext);

      for (Class c : classes) {
        if (c.isAnnotationPresent(ServerEndpoint.class)) {
          final ServerEndpoint annotation = (ServerEndpoint) c.getAnnotation(ServerEndpoint.class);

          final ServerEndpointConfig serverEndpointConfig =
              ServerEndpointConfig.Builder.create(c, annotation.value())
                  .configurator(
                      new ServerEndpointConfig.Configurator() {
                        @Override
                        public <T> T getEndpointInstance(final Class<T> endpointClass)
                            throws InstantiationException {
                          return container.get(endpointClass);
                        }
                      })
                  .build();

          serverContainer.addEndpoint(serverEndpointConfig);
        }
      }
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }

    try {
      server.start();
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }
    return Task.done();
  }
 @Override
 protected ResourceConfig configureApplication() {
   final ResourceConfig application = new ResourceConfig();
   application.register(DefaultWishlistsResource.class);
   return application;
 }
Exemplo n.º 9
0
  private void run() throws Exception {
    InetSocketAddress address;

    if (this.host != null) {
      address = new InetSocketAddress(this.host, this.port);
    } else {
      address = new InetSocketAddress(this.port);
    }

    Server server = new Server(address);

    ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ModelRegistry modelRegistry = new ModelRegistry();

    final MetricRegistry metricRegistry = new MetricRegistry();

    Binder binder =
        new AbstractBinder() {

          @Override
          protected void configure() {
            bind(modelRegistry).to(ModelRegistry.class);
            bind(metricRegistry).to(MetricRegistry.class);
          }
        };

    ResourceConfig config = new ResourceConfig(ModelResource.class);
    config.register(binder);
    config.register(JacksonFeature.class);
    config.register(MultiPartFeature.class);
    config.register(ObjectMapperProvider.class);
    config.register(RolesAllowedDynamicFeature.class);

    // Naive implementation that grants the "admin" role to all local network users
    config.register(NetworkSecurityContextFilter.class);

    ServletContextHandler servletHandler = new ServletContextHandler();
    servletHandler.setContextPath(this.contextPath);

    ServletContainer jerseyServlet = new ServletContainer(config);

    servletHandler.addServlet(new ServletHolder(jerseyServlet), "/*");

    InstrumentedHandler instrumentedHandler = new InstrumentedHandler(metricRegistry);
    instrumentedHandler.setHandler(servletHandler);

    handlerCollection.addHandler(instrumentedHandler);

    if (this.consoleWar != null) {
      WebAppContext consoleHandler = new WebAppContext();
      consoleHandler.setContextPath(this.contextPath + "/console"); // XXX
      consoleHandler.setWar(this.consoleWar.getAbsolutePath());

      handlerCollection.addHandler(consoleHandler);
    }

    server.setHandler(handlerCollection);

    DirectoryDeployer deployer = null;

    if (this.modelDir != null) {

      if (!this.modelDir.isDirectory()) {
        throw new IOException(this.modelDir.getAbsolutePath() + " is not a directory");
      }

      deployer = new DirectoryDeployer(modelRegistry, this.modelDir.toPath());
    }

    server.start();

    if (deployer != null) {
      deployer.start();
    }

    server.join();

    if (deployer != null) {
      deployer.interrupt();

      deployer.join();
    }
  }
Exemplo n.º 10
0
 @Override
 protected Application configure() {
   ResourceConfig config = new ResourceConfig(HttpMethodResource.class);
   config.register(new LoggingFilter(LOGGER, true));
   return config;
 }