@Override public void run( ConerCoreConfiguration conerCoreConfiguration, Environment environment ) throws Exception { initComponents(conerCoreConfiguration); JerseyEnvironment jersey = environment.jersey(); jersey.register(components.eventsResource()); jersey.register(components.eventRegistrationsResource()); jersey.register(components.eventRunsResource()); jersey.register(components.eventResultsResource()); jersey.register(components.handicapGroupsResource()); jersey.register(components.handicapGroupSetsResource()); jersey.register(components.competitionGroupsResource()); jersey.register(components.competitionGroupSetsResource()); jersey.register(components.domainServiceExceptionMapper()); jersey.register(components.runtimeExceptionUnwrappingMapper()); optionallyRegisterHsqlDatabaseManagerSwingTask(environment, conerCoreConfiguration); }
/** * Registers any Guice-bound providers or root resources. */ public static void registerGuiceBound(Injector injector, final JerseyEnvironment environment) { while (injector != null) { for (Key<?> key : injector.getBindings().keySet()) { Type type = key.getTypeLiteral().getType(); if (type instanceof Class) { Class<?> c = (Class) type; if (isProviderClass(c)) { logger.info("Registering {} as a provider class", c.getName()); environment.register(c); } else if (isRootResourceClass(c)) { // Jersey rejects resources that it doesn't think are acceptable // Including abstract classes and interfaces, even if there is a valid Guice binding. if(Resource.isAcceptable(c)) { logger.info("Registering {} as a root resource class", c.getName()); environment.register(c); } else { logger.warn("Class {} was not registered as a resource. Bind a concrete implementation instead.", c.getName()); } } } } injector = injector.getParent(); } }
private void checkAdminGuiceFeature(final Environment environment, final JerseyEnvironment jerseyEnvironment) { try { Feature feature = new Feature() { @Override public boolean configure(FeatureContext context) { for ( Object obj : environment.jersey().getResourceConfig().getSingletons() ) { if ( obj instanceof InternalFeatureRegistrations ) { ((InternalFeatureRegistrations)obj).apply(context); } } return true; } }; jerseyEnvironment.register(feature); } catch ( Exception ignore ) { // ignore - GuiceBundle not added } }
@Override protected void internalRun(Configuration configuration, Environment environment) { Metric metric = new Gauge<Integer>() { final Random random = new Random(); @Override public Integer getValue() { return random.nextInt(100); } }; environment.metrics().register("goodbye-random", metric); environment.jersey().register(GoodbyeResource.class); JerseyEnvironment adminJerseyEnvironment = SoaBundle.getFeatures(environment).getNamedRequired(JerseyEnvironment.class, SoaFeatures.ADMIN_NAME); adminJerseyEnvironment.register(GoodbyeAdminResource.class); }
/** * Registers any Guice-bound providers or root resources. */ public static void registerGuiceBound(Injector injector, final JerseyEnvironment environment) { while (injector != null) { for (Key<?> key : injector.getBindings().keySet()) { Type type = key.getTypeLiteral().getType(); if (type instanceof Class) { Class<?> c = (Class) type; if (isProviderClass(c)) { logger.info("Registering {} as a provider class", c.getName()); environment.register(c); } else if (isRootResourceClass(c)) { // Jersey rejects resources that it doesn't think are acceptable // Including abstract classes and interfaces, even if there is a valid Guice binding. if (Resource.isAcceptable(c)) { logger.info("Registering {} as a root resource class", c.getName()); environment.register(c); } else { logger.warn("Class {} was not registered as a resource. Bind a concrete implementation instead.", c.getName()); } } } } injector = injector.getParent(); } }
@Override public void run(Object configuration, Environment environment) { boolean debuggable = false; if(configuration instanceof JerseyDebuggable) { debuggable = ((JerseyDebuggable) configuration).isJerseyDebuggable(); } JerseyEnvironment jersey = environment.jersey(); jersey.register(new DebugErrorMessageJsonMessageBodyWriter(objectMapper)); jersey.register(new DebugErrorMessagePlainMessageBodyWriter()); jersey.register(new ErrorMessagePlainMessageBodyWriter()); jersey.register(new LoggingDebugExceptionMapper<Throwable>(debuggable) {}); jersey.register(new LoggingDebugExceptionMapper<BaseWebApplicationException>(debuggable) {}); //enable returning validation errors jersey.enable("jersey.config.beanValidation.enableOutputValidationErrorEntity.server"); }
@Test public void givenHealthCheckManagerWithPassingTest_whenInitialized_thenTestsAreHealthy() throws Exception{ JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); ArgumentCaptor<TestStatusResource> argumentCaptor = ArgumentCaptor.forClass(TestStatusResource.class); new Atam4j.Atam4jBuilder(jerseyEnvironment) .withTestClasses(PassingTestWithNoCategory.class) .withInitialDelay(0) .build() .initialise(); verify(jerseyEnvironment).register(argumentCaptor.capture()); TestStatusResource value = argumentCaptor.getValue(); assertNotNull(value); checkThatWeEventuallyGetSuccess(value); }
@Test public void givenHealthCheckManagerUsingAnnotationScanning_whenInitialized_thenTestsAreHealthy() throws Exception{ JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); ArgumentCaptor<TestStatusResource> argumentCaptor = ArgumentCaptor.forClass(TestStatusResource.class); new Atam4j.Atam4jBuilder(jerseyEnvironment) .withInitialDelay(0) .build() .initialise(); verify(jerseyEnvironment).register(argumentCaptor.capture()); TestStatusResource value = argumentCaptor.getValue(); assertNotNull(value); checkThatWeEventuallyGetSuccess(value); }
@Override public void run(final CredentialStorageConfiguration configuration, final Environment environment) throws Exception { final JedisManaged jedisManaged = this.buildJedis(configuration.getRedis()); environment.lifecycle().manage(jedisManaged); final PetiteContainer petiteContainer = this.petite.getPetiteContainer(); this.registerExternalDependencies(configuration, environment, jedisManaged, petiteContainer); environment.getObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); environment.jersey().register(petiteContainer.getBean(CredentialResource.class)); // Admin resources. final JerseyEnvironment adminJerseyEnvironment = this.adminResourceBundle .getJerseyEnvironment(); adminJerseyEnvironment.register(petiteContainer.getBean(AuditResource.class)); // Health checks environment.healthChecks().register("redis", this.petite.getPetiteContainer().getBean(RedisHealthCheck.class)); }
@Override public void run(ApiConfig configuration, Environment environment) throws Exception { LOGGER.info("api started up"); injector = guiceBundle.getInjector(); JerseyEnvironment jersey = environment.jersey(); register(environment.lifecycle(), REFLECTIONS.getSubTypesOf(Managed.class)); // registers NbdServer // injector.getInstance(SessionFactory.class); //init DB installCorsFilter(environment); //init all Singletons semi-eagerly REFLECTIONS.getTypesAnnotatedWith(Singleton.class).forEach(injector::getInstance); final Set<Class<?>> resources = REFLECTIONS.getTypesAnnotatedWith(Path.class); register(jersey, resources); jersey.register(new LoggingExceptionMapper<Throwable>() { @Override protected String formatErrorMessage(long id, Throwable exception) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); return sw.toString(); } }); jersey.register(new JsonProcessingExceptionMapper(true)); jersey.register(new EarlyEofExceptionMapper()); final TrivialAuthenticator instance = injector.getInstance(TrivialAuthenticator.class); environment.jersey().register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<Principal>() .setAuthenticator(instance) .setAuthorizer((principal, role) -> false) .buildAuthFilter())); environment.jersey().register(RolesAllowedDynamicFeature.class); }
public AuthenticationBootstrap(JerseyEnvironment environment, UserDAO userDAO) { requireNonNull(environment); requireNonNull(environment); this.environment = environment; this.userDAO = userDAO; }
private static AuthenticationBootstrap createTypicalAuthBootstrap() { final UserDAO userDAO = mock(UserDAO.class); final Server s = new Server(0); final Servlet se = new ServletContainer(); final JerseyEnvironment env = new JerseyEnvironment(new JerseyContainerHolder(se), new DropwizardResourceConfig()); return new AuthenticationBootstrap(env, userDAO); }
@Override public void run(T configuration, Environment environment) throws Exception { JerseyEnvironment jersey = environment.jersey(); JerseyClientConfiguration clientConfiguration = clientConfigurationProvider.apply(configuration); Client client = getClient(environment, clientConfiguration); rxJerseyClientFeature.register(client); jersey.register(rxJerseyServerFeature); jersey.register(rxJerseyClientFeature); }
@Before public void setUp() throws Exception { mockConfiguration = mock(DummyConfiguration.class); mockEnvironment = mock(Environment.class); mockLifecycle = mock(LifecycleEnvironment.class); mockJersey = mock(JerseyEnvironment.class); mockHealthchecks = mock(HealthCheckRegistry.class); when(mockEnvironment.lifecycle()).thenReturn(mockLifecycle); when(mockEnvironment.healthChecks()).thenReturn(mockHealthchecks); }
@Override public void run(DuctileDBServerConfiguration configuration, Environment environment) throws Exception { MetricRegistry metrics = environment.metrics(); Metrics.initialize(metrics); HealthCheckRegistry healthChecks = environment.healthChecks(); JerseyEnvironment jersey = environment.jersey(); jersey.setUrlPattern("/rest"); }
private void attachExceptionMappersTo(JerseyEnvironment jersey) { jersey.register(CreateChargeExceptionMapper.class); jersey.register(GetChargeExceptionMapper.class); jersey.register(GetEventsExceptionMapper.class); jersey.register(SearchChargesExceptionMapper.class); jersey.register(CancelChargeExceptionMapper.class); jersey.register(ValidationExceptionMapper.class); jersey.register(BadRequestExceptionMapper.class); jersey.register(CreateRefundExceptionMapper.class); jersey.register(GetRefundExceptionMapper.class); jersey.register(GetRefundsExceptionMapper.class); }
@Test public void sanintyCheck() throws URISyntaxException { RestAssured.get(new URI("http://localhost:8886/hello")).then().assertThat().body(Matchers.containsString("Hello from configuration! (class " + JerseyEnvironment.class.getName() + ")")); //RestAssured.get(new URI("http://localhost:8886/swagger#!/hello/hello")).then().assertThat().body(Matchers.containsString("swagger-section")); }
private void initJerseyAdmin(SoaConfiguration configuration, SoaFeaturesImpl features, Ports ports, final Environment environment, AbstractBinder binder) { if ( (configuration.getAdminJerseyPath() == null) || !ports.adminPort.hasPort() ) { return; } String jerseyRootPath = configuration.getAdminJerseyPath(); if ( !jerseyRootPath.endsWith("/*") ) { if ( jerseyRootPath.endsWith("/") ) { jerseyRootPath += "*"; } else { jerseyRootPath += "/*"; } } DropwizardResourceConfig jerseyConfig = new DropwizardResourceConfig(environment.metrics()); jerseyConfig.setUrlPattern(jerseyRootPath); JerseyContainerHolder jerseyServletContainer = new JerseyContainerHolder(new ServletContainer(jerseyConfig)); environment.admin().addServlet("soa-admin-jersey", jerseyServletContainer.getContainer()).addMapping(jerseyRootPath); JerseyEnvironment jerseyEnvironment = new JerseyEnvironment(jerseyServletContainer, jerseyConfig); features.putNamed(jerseyEnvironment, JerseyEnvironment.class, SoaFeatures.ADMIN_NAME); jerseyEnvironment.register(SoaApis.class); jerseyEnvironment.register(DiscoveryApis.class); jerseyEnvironment.register(DynamicAttributeApis.class); jerseyEnvironment.register(LoggingApis.class); jerseyEnvironment.register(binder); jerseyEnvironment.setUrlPattern(jerseyConfig.getUrlPattern()); jerseyEnvironment.register(new JacksonMessageBodyProvider(environment.getObjectMapper())); checkCorsFilter(configuration, environment.admin()); checkAdminGuiceFeature(environment, jerseyEnvironment); }
private Environment getEnvironment() { Environment environment = mock(Environment.class); JerseyEnvironment jersey = mock(JerseyEnvironment.class); when(environment.jersey()).thenReturn(jersey); LifecycleEnvironment lifecycle = mock(LifecycleEnvironment.class); when(environment.lifecycle()).thenReturn(lifecycle); HealthCheckRegistry healthchecks = mock(HealthCheckRegistry.class); when(environment.healthChecks()).thenReturn(healthchecks); return environment; }
public Atam4j(JerseyEnvironment jerseyEnvironment, TestRunListener testRunListener, AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler) { this.jerseyEnvironment = jerseyEnvironment; this.testRunListener = testRunListener; this.acceptanceTestsRunnerTaskScheduler = acceptanceTestsRunnerTaskScheduler; }
void addWriters(JerseyEnvironment environment) throws Exception { for (ClassInfo classInfo: ClassPath.from(getClass().getClassLoader()).getTopLevelClasses("io.scigraph.services.jersey.writers")) { if (!Modifier.isAbstract(classInfo.load().getModifiers())) { environment.register(factory.getInjector().getInstance(classInfo.load())); } } }
@Override public void run(ItEventsConfiguration configuration, Environment environment) throws Exception { final String template = configuration.getTemplate(); final String defaultName = configuration.getDefaultName(); JerseyEnvironment jersey = environment.jersey(); jersey.register(new HelloWorldResource(template, defaultName)); jersey.register(new EventResource()); }
private void register(JerseyEnvironment jersey, Iterable<Class<?>> resources) { for (Class<?> resourceClass : resources) { jersey.register(resourceClass); } }
public JerseyEnvironment getEnvironment() { return environment; }
@Override public void run(BitShadowConfiguration configuration, Environment environment) throws Exception { JerseyEnvironment jersey = environment.jersey(); jersey.packages("uk.co.littlemike.bitshadow.web"); }
public ThreadLocalUserContext(JerseyEnvironment jersey) { jersey.getResourceConfig().register(new CleanUserContextHolderFilter()); }
@SuppressWarnings("unchecked") @Override public void run(KeywhizConfig config, Environment environment) throws Exception { if (injector == null) { logger.debug("No existing guice injector; creating new one"); injector = Guice.createInjector(new ServiceModule(config, environment)); } JerseyEnvironment jersey = environment.jersey(); logger.debug("Registering resource filters"); jersey.register(injector.getInstance(ClientCertificateFilter.class)); logger.debug("Registering servlet filters"); environment.servlets().addFilter("security-headers-filter", injector.getInstance(SecurityHeadersFilter.class)) .addMappingForUrlPatterns(null, /* Default is for requests */ false /* Can be after other filters */, "/*" /* Every request */); jersey.register(injector.getInstance(CookieRenewingFilter.class)); environment.servlets().addFilter("xsrf-filter", injector.getInstance(XsrfServletFilter.class)) .addMappingForUrlPatterns(null /* Default is for requests */, false /* Can be after other filters */, "/admin/*" /* Path to filter on */); logger.debug("Registering providers"); jersey.register(new AuthResolver.Binder(injector.getInstance(ClientAuthFactory.class), injector.getInstance(AutomationClientAuthFactory.class), injector.getInstance(UserAuthFactory.class))); logger.debug("Registering resources"); jersey.register(injector.getInstance(ClientResource.class)); jersey.register(injector.getInstance(ClientsResource.class)); jersey.register(injector.getInstance(GroupResource.class)); jersey.register(injector.getInstance(GroupsResource.class)); jersey.register(injector.getInstance(MembershipResource.class)); jersey.register(injector.getInstance(SecretsDeliveryResource.class)); jersey.register(injector.getInstance(SecretResource.class)); jersey.register(injector.getInstance(SecretsResource.class)); jersey.register(injector.getInstance(SecretDeliveryResource.class)); jersey.register(injector.getInstance(SessionLoginResource.class)); jersey.register(injector.getInstance(SessionLogoutResource.class)); jersey.register(injector.getInstance(SessionMeResource.class)); jersey.register(injector.getInstance(AutomationClientResource.class)); jersey.register(injector.getInstance(AutomationGroupResource.class)); jersey.register(injector.getInstance(AutomationSecretResource.class)); jersey.register(injector.getInstance(AutomationEnrollClientGroupResource.class)); jersey.register(injector.getInstance(AutomationSecretAccessResource.class)); jersey.register(injector.getInstance(StatusResource.class)); jersey.register(injector.getInstance(BackupResource.class)); ManualStatusHealthCheck mshc = new ManualStatusHealthCheck(); environment.healthChecks().register("manualStatus", mshc); environment.admin().addServlet("manualStatus", new ManualStatusServlet(mshc)).addMapping("/status/*"); validateDatabase(config); logger.debug("Keywhiz configuration complete"); }
public JerseyEnvironment jersey() { return this.environment.jersey(); }
@Override protected Handler createAppServlet(Server server, JerseyEnvironment jersey, ObjectMapper objectMapper, Validator validator, MutableServletContextHandler handler, @Nullable Servlet jerseyContainer, MetricRegistry metricRegistry) { if (jerseyContainer != null) { jersey.register(new LoggingExceptionMapper<Throwable>() { @Override public Response toResponse(Throwable exception) { final int status; final StatusEntity statusEntity; if (exception instanceof WebApplicationException) { final Response response = ((WebApplicationException) exception).getResponse(); if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SERVER_ERROR)) { logException(exception); } status = response.getStatus(); statusEntity = new StatusEntity(status, new StatusMessage(µService.WEB_APPLICATION_ERROR, exception.getLocalizedMessage())); } else { final long id = logException(exception); status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); StatusMessage message = new StatusMessage(StatusMessage.Type.ERROR, String.format("%016x", id), µService.INTERNAL_SERVER_ERROR, formatErrorMessage(id, exception), null); statusEntity = new StatusEntity(status, message); } return Response.status(status) .type(MediaType.APPLICATION_JSON_TYPE) .entity(statusEntity) .build(); } }); jersey.register(new ConstraintViolationExceptionMapper()); jersey.register(new JsonProcessingExceptionMapper()); jersey.register(new EarlyEofExceptionMapper()); } Handler appServlet = super.createAppServlet(server, jersey, objectMapper, validator, handler, jerseyContainer, metricRegistry); return appServlet; }
@Test public void sanintyCheck() throws URISyntaxException { RestAssured.get(new URI("http://localhost:8884/hello")).then().assertThat().body(Matchers.containsString("Hello from configuration! (class " + JerseyEnvironment.class.getName() + ")")); }
@Test public void sanintyCheck() throws URISyntaxException { RestAssured.get(new URI("http://localhost:8880/hello")).then().assertThat().body(Matchers.containsString("Hello from configuration! (class " + JerseyEnvironment.class.getName() + ")")); }
@Test public void sanintyCheck() throws URISyntaxException { RestAssured.get(new URI("http://localhost:8882/hello")).then().assertThat().body(Matchers.containsString("Hello from configuration! (class " + JerseyEnvironment.class.getName() + ")")); }
public Atam4jBuilder(JerseyEnvironment jerseyEnvironment) { this.jerseyEnvironment = jerseyEnvironment; }
@Test public void givenBuilderConstructedWithHealthCheckRegistry_whenBuildCalled_thenManagerReturned() { Atam4j.Atam4jBuilder builder = new Atam4j.Atam4jBuilder( new JerseyEnvironment(null,null)).withTestClasses(PassingTestWithNoCategory.class); Assert.assertNotNull(builder.build()); }