org.glassfish.hk2.api.ServiceLocator Java Examples

The following examples show how to use org.glassfish.hk2.api.ServiceLocator. 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: Jersey2BackstopperConfigHelperTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void backstopperOnlyExceptionMapperFactory_removes_all_exception_mappers_except_Jersey2ApiExceptionHandler()
    throws NoSuchFieldException, IllegalAccessException {
    // given
    AbstractBinder lotsOfExceptionMappersBinder = new AbstractBinder() {
        @Override
        protected void configure() {
            bind(JsonMappingExceptionMapper.class).to(ExceptionMapper.class).in(Singleton.class);
            bind(JsonParseExceptionMapper.class).to(ExceptionMapper.class).in(Singleton.class);
            bind(generateJerseyApiExceptionHandler(projectApiErrors, utils)).to(ExceptionMapper.class);
        }
    };

    ServiceLocator locator = ServiceLocatorUtilities.bind(lotsOfExceptionMappersBinder);

    // when
    BackstopperOnlyExceptionMapperFactory overrideExceptionMapper = new BackstopperOnlyExceptionMapperFactory(locator);

    // then
    Set<Object> emTypesLeft = overrideExceptionMapper.getFieldObj(
        ExceptionMapperFactory.class, overrideExceptionMapper, "exceptionMapperTypes"
    );
    assertThat(emTypesLeft).hasSize(1);
    ServiceHandle serviceHandle = overrideExceptionMapper.getFieldObj(emTypesLeft.iterator().next(), "mapper");
    assertThat(serviceHandle.getService()).isInstanceOf(Jersey2ApiExceptionHandler.class);
}
 
Example #2
Source File: GuiceComponentProviderTest.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
private <T> void givenInjections(ServiceBindingBuilder<T> bindingBuilder) {
    new MockUp<GuiceComponentProvider>() {
        @Mock
        DynamicConfiguration getConfiguration(final ServiceLocator locator) {
            return dynamicConfiguration;
        }

        @Mock
        ServiceBindingBuilder<T> newFactoryBinder(final Factory<T> factory) {
            return bindingBuilder;
        }

        @Mock
        void addBinding(final BindingBuilder<T> builder, final DynamicConfiguration configuration) {
        }
    };
}
 
Example #3
Source File: GuiceFeature.java    From jrestless-examples with Apache License 2.0 6 votes vote down vote up
@Override
public boolean configure(FeatureContext context) {
	InjectionManager injectionManager = InjectionManagerProvider.getInjectionManager(context);
	ServiceLocator locator;
	if (injectionManager instanceof ImmediateHk2InjectionManager) {
		locator = ((ImmediateHk2InjectionManager) injectionManager).getServiceLocator();
	} else if (injectionManager instanceof DelayedHk2InjectionManager) {
		locator = ((DelayedHk2InjectionManager) injectionManager).getServiceLocator();
	} else {
		throw new IllegalStateException("expected an hk2 injection manager");
	}
	GuiceBridge.getGuiceBridge().initializeGuiceBridge(locator);
	// register all your modules, here
	Injector injector = Guice.createInjector(new GreetingModule());
	GuiceIntoHK2Bridge guiceBridge = locator.getService(GuiceIntoHK2Bridge.class);
	guiceBridge.bridgeGuiceInjector(injector);
	return true;
}
 
Example #4
Source File: RestApplication.java    From jerseyoauth2 with MIT License 6 votes vote down vote up
@Inject
   public RestApplication(ServiceLocator serviceLocator) {
	DynamicConfiguration dc = Injections.getConfiguration(serviceLocator);

       Injections.addBinding(Injections.newBinder(DatabaseClientService.class).to(IClientService.class),dc);
       Injections.addBinding(Injections.newBinder(Configuration.class).to(IConfiguration.class),dc);
       Injections.addBinding(Injections.newBinder(Configuration.class).to(IRSConfiguration.class),dc);
       Injections.addBinding(Injections.newBinder(DefaultPrincipalUserService.class).to(IUserService.class),dc);
       Injections.addBinding(Injections.newBinder(CachingAccessTokenStorage.class).to(IAccessTokenStorageService.class),dc);
       Injections.addBinding(Injections.newBinder(IntegratedAccessTokenVerifier.class).to(IAccessTokenVerifier.class),dc);
       Injections.addBinding(Injections.newBinder(RequestFactory.class).to(IRequestFactory.class),dc);
       Injections.addBinding(Injections.newBinder(MD5TokenGenerator.class).to(ITokenGenerator.class),dc);
       Injections.addBinding(Injections.newBinder(UUIDClientIdGenerator.class).to(IClientIdGenerator.class),dc);
	
	EntityManagerFactory emf = new PersistenceProvider().get();
       Injections.addBinding(Injections.newBinder(emf).to(EntityManagerFactory.class),dc);
       
       CacheManager cacheManager = new DefaultCacheManagerProvider().get();
       Injections.addBinding(Injections.newBinder(cacheManager).to(CacheManager.class),dc);
       
       dc.commit();
}
 
Example #5
Source File: JerseyApplication.java    From onedev with MIT License 6 votes vote down vote up
@Inject
public JerseyApplication(ServiceLocator serviceLocator) {
	GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
	GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
    guiceBridge.bridgeGuiceInjector(AppLoader.injector);
    
    String disableMoxy = PropertiesHelper.getPropertyNameForRuntime(
    		CommonProperties.MOXY_JSON_FEATURE_DISABLE,
               getConfiguration().getRuntimeType());
       property(disableMoxy, true);
       property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);

       // add the default Jackson exception mappers
       register(JacksonFeature.class);
       
       packages(JerseyApplication.class.getPackage().getName());
       
    for (JerseyConfigurator configurator: AppLoader.getExtensions(JerseyConfigurator.class)) {
    	configurator.configure(this);
    }
}
 
Example #6
Source File: WorkersCommand.java    From dropwizard-experiment with MIT License 6 votes vote down vote up
private void setupWorkers(List<WorkerConfiguration> configurations, Environment environment, ServiceLocator locator) {
    configurations.forEach(config -> {
            Class<? extends QueueWorker> workerClass = config.getWorker();
            ExecutorService executorService = environment.lifecycle()
                    .executorService(workerClass.getSimpleName() + "-%d")
                    .maxThreads(config.getThreads())
                    .build();

            for (int i = 0; i < config.getThreads(); i++) {
                QueueWorker<?> worker = locator.getService(workerClass);
                executorService.submit(worker);
                workers.add(worker);
            }
            log.info("Created {} thread{} for worker {}.", config.getThreads(), config.getThreads() > 1 ? "s" : "", workerClass.getSimpleName());
        });
}
 
Example #7
Source File: WorkersCommand.java    From dropwizard-experiment with MIT License 6 votes vote down vote up
@Override
protected void run(Environment environment, Namespace namespace, T configuration) throws Exception {
    ServiceLocator locator = HK2Utils.getServiceLocator(environment);

    if (!configuration.getWorkers().isEmpty()) {
        setupWorkers(configuration.getWorkers(), environment, locator);
        log.info("Created {} workers.", workers.size());
    }

    if (!configuration.getSchedules().isEmpty()) {
        Quartz quartz = new Quartz(configuration.getQuartz(), configuration.getDatabaseConfig(), locator);
        environment.lifecycle().manage(quartz);

        setupSchedules(configuration.getSchedules(), quartz.getScheduler());
    }

    if (configuration.getWorkers().isEmpty() && configuration.getSchedules().isEmpty()) {
        log.error("Server started with no workers and no scheduled jobs configured. Is that on purpose?");
    }
}
 
Example #8
Source File: ZeppelinServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static void setupClusterManagerServer(ServiceLocator serviceLocator) {
  if (conf.isClusterMode()) {
    LOG.info("Cluster mode is enabled, starting ClusterManagerServer");
    ClusterManagerServer clusterManagerServer = ClusterManagerServer.getInstance(conf);

    NotebookServer notebookServer = serviceLocator.getService(NotebookServer.class);
    clusterManagerServer.addClusterEventListeners(ClusterManagerServer.CLUSTER_NOTE_EVENT_TOPIC, notebookServer);

    AuthorizationService authorizationService = serviceLocator.getService(AuthorizationService.class);
    clusterManagerServer.addClusterEventListeners(ClusterManagerServer.CLUSTER_AUTH_EVENT_TOPIC, authorizationService);

    InterpreterSettingManager interpreterSettingManager = serviceLocator.getService(InterpreterSettingManager.class);
    clusterManagerServer.addClusterEventListeners(ClusterManagerServer.CLUSTER_INTP_SETTING_EVENT_TOPIC, interpreterSettingManager);

    // Since the ClusterInterpreterLauncher is lazy, dynamically generated, So in cluster mode,
    // when the zeppelin service starts, Create a ClusterInterpreterLauncher object,
    // This allows the ClusterInterpreterLauncher to listen for cluster events.
    try {
      InterpreterSettingManager intpSettingManager = sharedServiceLocator.getService(InterpreterSettingManager.class);
      RecoveryStorage recoveryStorage = ReflectionUtils.createClazzInstance(
              conf.getRecoveryStorageClass(),
              new Class[] {ZeppelinConfiguration.class, InterpreterSettingManager.class},
              new Object[] {conf, intpSettingManager});
      recoveryStorage.init();
      PluginManager.get().loadInterpreterLauncher(InterpreterSetting.CLUSTER_INTERPRETER_LAUNCHER_NAME, recoveryStorage);
    } catch (IOException e) {
      LOG.error(e.getMessage(), e);
    }

    clusterManagerServer.start();
  } else {
    LOG.info("Cluster mode is disabled");
  }
}
 
Example #9
Source File: GuiceBridgeActivator.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
/**
 * Activate HK2 guice bridge.
 */
public void activate() {
    final ServiceLocator locator = injectionManager.getInstance(ServiceLocator.class);
    GuiceBridge.getGuiceBridge().initializeGuiceBridge(locator);
    final GuiceIntoHK2Bridge guiceBridge = injectionManager.getInstance(GuiceIntoHK2Bridge.class);
    guiceBridge.bridgeGuiceInjector(injector);
}
 
Example #10
Source File: ZeppelinServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private static void setupNotebookServer(
    WebAppContext webapp, ZeppelinConfiguration conf, ServiceLocator serviceLocator) {
  String maxTextMessageSize = conf.getWebsocketMaxTextMessageSize();
  final ServletHolder servletHolder =
      new ServletHolder(serviceLocator.getService(NotebookServer.class));
  servletHolder.setInitParameter("maxTextMessageSize", maxTextMessageSize);

  webapp.addServlet(servletHolder, "/ws/*");
}
 
Example #11
Source File: Jersey2BackstopperConfigHelperTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void exceptionMapperFactoryOverrideBinder_configures_ExceptionMappers_override() {
    // given
    AbstractBinder defaultJersey2ExceptionMapperBinder = new ExceptionMapperFactory.Binder();
    ExceptionMapperFactoryOverrideBinder overrideBinder =  new ExceptionMapperFactoryOverrideBinder();
    ServiceLocator locator = ServiceLocatorUtilities.bind(defaultJersey2ExceptionMapperBinder, overrideBinder);

    // when
    ExceptionMappers result = locator.getService(ExceptionMappers.class);

    // then
    assertThat(result).isInstanceOf(BackstopperOnlyExceptionMapperFactory.class);
}
 
Example #12
Source File: RateLimitBundle.java    From ratelimitj with Apache License 2.0 5 votes vote down vote up
@Inject
public RateLimitingFactoryProvider(final MultivaluedParameterExtractorProvider extractorProvider,
                                   final ServiceLocator injector,
                                   final RateLimiterFactoryProvider rateLimiterFactoryProvider) {
    super(extractorProvider, injector, Parameter.Source.UNKNOWN);
    this.requestRateLimiterFactory = rateLimiterFactoryProvider.factory;
}
 
Example #13
Source File: GuiceFeature.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(FeatureContext context) {

    ServiceLocator serviceLocator = ServiceLocatorProvider.getServiceLocator( context );
    GuiceBridge.getGuiceBridge().initializeGuiceBridge( serviceLocator );

    GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService( GuiceIntoHK2Bridge.class );
    guiceBridge.bridgeGuiceInjector( StartupListener.INJECTOR );

    return true;
}
 
Example #14
Source File: SubmarineServer.java    From submarine with Apache License 2.0 5 votes vote down vote up
private static void setupNotebookServer(WebAppContext webapp,
    SubmarineConfiguration conf, ServiceLocator serviceLocator) {
  String maxTextMessageSize = conf.getWebsocketMaxTextMessageSize();
  final ServletHolder servletHolder =
      new ServletHolder(serviceLocator.getService(NotebookServer.class));
  servletHolder.setInitParameter("maxTextMessageSize", maxTextMessageSize);

  final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
  webapp.addServlet(servletHolder, "/ws/*");
}
 
Example #15
Source File: Quartz.java    From dropwizard-experiment with MIT License 5 votes vote down vote up
@Inject
public Quartz(QuartzConfiguration quartzConfig, DataSourceFactory dbConfig, ServiceLocator locator) throws SchedulerException {
    this.quartzConfig = quartzConfig;
    this.dbConfig = dbConfig;

    SchedulerFactory schedulerFactory = new StdSchedulerFactory(getProperties());
    scheduler = schedulerFactory.getScheduler();
    scheduler.setJobFactory(new HK2JobFactory(locator));

    scheduler.start();
}
 
Example #16
Source File: KatharsisDynamicFeature.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Inject
public KatharsisDynamicFeature(ObjectMapper objectMapper, final ServiceLocator ServiceLocator) {
    super(objectMapper, new QueryParamsBuilder(new DefaultQueryParamsParser()), new JsonServiceLocator() {
        @Override
        public <T> T getInstance(Class<T> clazz) {
            return ServiceLocator.getService(clazz);
        }
    });
}
 
Example #17
Source File: Pac4JValueFactoryProvider.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Inject
protected Pac4JProfileValueFactoryProvider(ProfileManagerFactoryBuilder manager,
        OptionalProfileFactoryBuilder opt, ProfileFactoryBuilder profile,
        MultivaluedParameterExtractorProvider mpep, ServiceLocator locator) {
    super(mpep, locator, Parameter.Source.UNKNOWN);
    this.manager = manager;
    this.optProfile = opt;
    this.profile = profile;
}
 
Example #18
Source File: Control.java    From clouditor with Apache License 2.0 5 votes vote down vote up
public void evaluate(ServiceLocator locator) {
  // clear old results
  this.results.clear();

  if (this.rules.isEmpty()) {
    this.fulfilled = Fulfillment.NOT_EVALUATED;

    return;
  }

  this.fulfilled = Fulfillment.GOOD;

  // retrieve assets that belong to a rule within the control
  for (var rule : this.rules) {
    // TODO: use the new function in RulesService#get
    var assets = locator.getService(AssetService.class).getAssetsWithType(rule.getAssetType());

    for (var asset : assets) {
      this.results.addAll(
          asset.getEvaluationResults().stream()
              .filter(result -> Objects.equals(result.getRule().getId(), rule.getId()))
              .collect(Collectors.toList()));
    }

    if (this.results.stream().anyMatch(EvaluationResult::hasFailedConditions)) {
      this.fulfilled = Fulfillment.WARNING;
    }
  }

  // we should handle this better
  if (this.results.isEmpty()) {
    this.fulfilled = Fulfillment.NOT_EVALUATED;
  }

  this.violations = 0;
}
 
Example #19
Source File: SingularityAuthFactoryProvider.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@javax.inject.Inject
public SingularityAuthFactoryProvider(
  final MultivaluedParameterExtractorProvider extractorProvider,
  ServiceLocator locator,
  SingularityAuthedUserFactory authFactory
) {
  super(extractorProvider, locator, Source.UNKNOWN);
  this.authFactory = authFactory;
}
 
Example #20
Source File: GuiceComponentProviderTest.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testInitializeSaveTheServiceLocator() {
    givenServiceLocator();

    underTest.initialize(serviceLocator);

    ServiceLocator initializedServiceLocator = Deencapsulation.getField(underTest, ServiceLocator.class);
    assertThat(initializedServiceLocator).isEqualTo(serviceLocator);
}
 
Example #21
Source File: GuiceComponentProvider.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
void initialize(ServiceLocator serviceLocator) {
    this.serviceLocator = serviceLocator;
    this.injector = ServletContextUtils.getInjector(getServletContext());
    if (injector == null) {
        throw SeedException.createNew(Jersey2ErrorCode.MISSING_INJECTOR);
    }
    GuiceBridge.getGuiceBridge().initializeGuiceBridge(this.serviceLocator);
    this.serviceLocator.getService(GuiceIntoHK2Bridge.class).bridgeGuiceInjector(this.injector);
}
 
Example #22
Source File: HK2LinkerTest.java    From dropwizard-guicier with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    Environment environment = new Environment("test env", objectMapper, null, new MetricRegistry(), null);
    GuiceBundle guiceBundle = GuiceBundle.defaultBuilder(Configuration.class)
        .modules(new TestModule())
        .build();
    Bootstrap bootstrap = mock(Bootstrap.class);
    when(bootstrap.getObjectMapper()).thenReturn(objectMapper);
    guiceBundle.initialize(bootstrap);
    guiceBundle.run(new Configuration(), environment);

    injector = guiceBundle.getInjector();
    serviceLocator = injector.getInstance(ServiceLocator.class);
}
 
Example #23
Source File: JerseyModule.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void configureServlets() {
    // The order these operations (including the steps in the linker) are important
    ServiceLocator locator = new ServiceLocatorDecorator(BootstrapUtils.newServiceLocator()) {

        @Override
        public void shutdown() {
            // don't shutdown, see issue #67. Remove once jersey2-guice supports Jersey 2.21
        }
    };
    install(new BootstrapModule(locator));

    bind(HK2Linker.class).asEagerSingleton();
}
 
Example #24
Source File: ServiceLocatorGenerator.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ServiceLocator create(String name, ServiceLocator parent) {
    ServiceLocator retVal = super.create(name, parent);
    DynamicConfigurationService dcs = retVal.getService(DynamicConfigurationService.class);
    Populator populator = dcs.getPopulator();

    try {
        populator.populate();
    } catch (IOException e) {
        throw new MultiException(e);
    }
    return retVal;
}
 
Example #25
Source File: AbstractTemplateProcessor.java    From ameba with MIT License 5 votes vote down vote up
/**
 * <p>getTemplateObjectFactory.</p>
 *
 * @param serviceLocator a {@link org.glassfish.hk2.api.ServiceLocator} object.
 * @param type           a {@link java.lang.Class} object.
 * @param defaultValue   a {@link org.glassfish.jersey.internal.util.collection.Value} object.
 * @param <F>            a F object.
 * @return a F object.
 */
@SuppressWarnings("unchecked")
protected <F> F getTemplateObjectFactory(ServiceLocator serviceLocator, Class<F> type, Value<F> defaultValue) {
    Object objectFactoryProperty = this.config.getProperty(MvcFeature.TEMPLATE_OBJECT_FACTORY + this.suffix);
    if (objectFactoryProperty != null) {
        if (type.isAssignableFrom(objectFactoryProperty.getClass())) {
            return type.cast(objectFactoryProperty);
        }

        Class<F> factoryClass = null;
        if (objectFactoryProperty instanceof String) {
            factoryClass = ReflectionHelper.<F>classForNamePA((String) objectFactoryProperty).run();
        } else if (objectFactoryProperty instanceof Class) {
            factoryClass = (Class<F>) objectFactoryProperty;
        }

        if (factoryClass != null) {
            if (type.isAssignableFrom(factoryClass)) {
                return serviceLocator.create(factoryClass);
            }

            logger.warn(LocalizationMessages.WRONG_TEMPLATE_OBJECT_FACTORY(factoryClass, type));
        }
    }

    return defaultValue.get();
}
 
Example #26
Source File: TokenFactoryProvider.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Inject
public TokenFactoryProvider(
        final MultivaluedParameterExtractorProvider extractorProvider,
        ServiceLocator locator) {

    super(extractorProvider, locator, Parameter.Source.UNKNOWN);
}
 
Example #27
Source File: LocalResourceAddon.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setup(final Application application) {

    final Set<ClassInfo> classInfoSet = Sets.newLinkedHashSet();
    subscribeSystemEvent(ClassFoundEvent.class, event -> event.accept(info -> {
        if (info.containsAnnotations(Service.class)) {
            classInfoSet.add(info);
            return true;
        }
        return false;
    }));

    final Feature localResource = new Feature() {

        @Inject
        private ServiceLocator locator;

        @Override
        public boolean configure(FeatureContext context) {
            for (ClassInfo classInfo : classInfoSet) {
                ServiceLocatorUtilities.addClasses(locator, classInfo.toClass());
            }
            classInfoSet.clear();
            return true;
        }
    };

    application.register(localResource);
}
 
Example #28
Source File: PrincipalValueFactoryProvider.java    From jersey-hmac-auth with Apache License 2.0 5 votes vote down vote up
@Inject
public PrincipalValueFactoryProvider(final MultivaluedParameterExtractorProvider mpep,
        final ServiceLocator locator, final PrincipalFactory<P> factory) {
    super(mpep, locator, UNKNOWN);
    notNull(factory, "factory cannot be null");
    this.factory = factory;
}
 
Example #29
Source File: AuthResolver.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Inject
public AuthValueFactoryProvider(final MultivaluedParameterExtractorProvider extractorProvider,
    final ServiceLocator injector, ClientAuthFactory clientAuthFactory,
    AutomationClientAuthFactory automationClientAuthFactory, UserAuthFactory userAuthFactory) {
  super(extractorProvider, injector, Parameter.Source.UNKNOWN);
  this.clientAuthFactory = clientAuthFactory;
  this.automationClientAuthFactory = automationClientAuthFactory;
  this.userAuthFactory = userAuthFactory;
}
 
Example #30
Source File: SpringContextJerseyTest.java    From demo-restWS-spring-jersey-tomcat-mybatis with MIT License 4 votes vote down vote up
protected ApplicationContext getSpringApplicationContext() {
    ServiceLocator serviceLocator = getApplication().getServiceLocator();
    return serviceLocator.getService(ApplicationContext.class);
}