Search in sources :

Example 96 with Provider

use of com.google.inject.Provider in project ninja by ninjaframework.

the class RouteBuilderImplTest method testThatGlobalFiltersInRouteReplaceGlobalFiltersInConfFilters.

@Test
public void testThatGlobalFiltersInRouteReplaceGlobalFiltersInConfFilters() throws Exception {
    // DummyFilter is defined in conf.Filters, but .globalFilters(DummyFilter2.class) should
    // override that.
    // given
    // different setup that uses com.example packages and thus reads the Filters there
    Mockito.when(ninjaProperties.get(NinjaConstant.APPLICATION_MODULES_BASE_PACKAGE)).thenReturn("com.example");
    this.ninjaBaseDirectoryResolver = new NinjaBaseDirectoryResolver(ninjaProperties);
    this.routeBuilder = new RouteBuilderImpl(ninjaProperties, ninjaBaseDirectoryResolver);
    DummyFilter2 dummyFilter2 = new DummyFilter2();
    Result expectedResult = Mockito.mock(Result.class);
    Context context = Mockito.mock(Context.class);
    Provider filterProvider = Mockito.mock(Provider.class);
    Mockito.when(injector.getProvider(DummyFilter2.class)).thenReturn(filterProvider);
    Mockito.when(filterProvider.get()).thenReturn(dummyFilter2);
    routeBuilder.GET().route("/").globalFilters(DummyFilter2.class).with(() -> expectedResult);
    Route route = routeBuilder.buildRoute(injector);
    FilterChain filterChain = route.getFilterChain();
    // when
    Result result = filterChain.next(context);
    // then
    Mockito.verify(injector, Mockito.never()).getProvider(DummyFilter.class);
    Mockito.verify(injector).getProvider(DummyFilter2.class);
    assertThat(dummyFilter2.executed, Matchers.equalTo(1));
    assertThat(result, org.hamcrest.Matchers.equalTo(expectedResult));
}
Also used : NinjaBaseDirectoryResolver(ninja.utils.NinjaBaseDirectoryResolver) Provider(com.google.inject.Provider) Test(org.junit.Test)

Example 97 with Provider

use of com.google.inject.Provider in project ninja by ninjaframework.

the class RouteBuilderImplTest method testWithGlobalFiltersClass.

@Test
public void testWithGlobalFiltersClass() throws Exception {
    // given        
    DummyFilter dummyFilter = new DummyFilter();
    Result expectedResult = Mockito.mock(Result.class);
    Context context = Mockito.mock(Context.class);
    Provider filterProvider = Mockito.mock(Provider.class);
    Mockito.when(injector.getProvider(DummyFilter.class)).thenReturn(filterProvider);
    Mockito.when(filterProvider.get()).thenReturn(dummyFilter);
    routeBuilder.GET().route("/").globalFilters(DummyFilter.class).with(() -> expectedResult);
    Route route = routeBuilder.buildRoute(injector);
    FilterChain filterChain = route.getFilterChain();
    // when
    Result result = filterChain.next(context);
    // then
    assertThat(dummyFilter.executed, Matchers.equalTo(1));
    assertThat(result, org.hamcrest.Matchers.equalTo(expectedResult));
}
Also used : Provider(com.google.inject.Provider) Test(org.junit.Test)

Example 98 with Provider

use of com.google.inject.Provider in project ninja by ninjaframework.

the class LifecycleServiceImpl method start.

@Override
public void start() {
    startTime = System.currentTimeMillis();
    log.info("Starting Ninja application...");
    state = State.STARTING;
    // until they are instantiated that LifecycleSupport has an opportunity to register them.
    for (final Binding binding : injector.getBindings().values()) {
        binding.acceptScopingVisitor(new DefaultBindingScopingVisitor() {

            @Override
            public Object visitEagerSingleton() {
                injector.getInstance(binding.getKey());
                return null;
            }

            @Override
            public Object visitScope(Scope scope) {
                if (scope.equals(Scopes.SINGLETON)) {
                    Object target = injector.getInstance(binding.getKey());
                    if (binding instanceof ProviderInstanceBinding) {
                        Provider providerInstance = ((ProviderInstanceBinding) binding).getProviderInstance();
                        if (providerInstance instanceof ProviderMethod) {
                            // @Provides methods don't get picked up by TypeListeners, so we need to manually register them
                            if (lifecycleSupport.hasLifecycleMethod(target.getClass())) {
                                lifecycleSupport.registerLifecycle(target);
                            }
                        }
                    }
                }
                return null;
            }
        });
    }
    lifecycleRegister.start();
    long time = System.currentTimeMillis() - startTime;
    log.info("Ninja application started in {}ms", time);
    state = lifecycleRegister.isStarted() ? State.STARTED : State.STOPPED;
}
Also used : ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) Binding(com.google.inject.Binding) Scope(com.google.inject.Scope) DefaultBindingScopingVisitor(com.google.inject.spi.DefaultBindingScopingVisitor) ProviderMethod(com.google.inject.internal.ProviderMethod) ProviderInstanceBinding(com.google.inject.spi.ProviderInstanceBinding) Provider(com.google.inject.Provider)

Example 99 with Provider

use of com.google.inject.Provider in project platformlayer by platformlayer.

the class KvmInstance method addChildren.

@Override
protected void addChildren() throws OpsException {
    CloudInstanceMapper instance;
    {
        instance = injected(CloudInstanceMapper.class);
        instance.instance = OpsContext.get().getInstance(DirectInstance.class);
        addChild(instance);
    }
    instance.addChild(ManagedDirectory.build(getInstanceDir(), "700"));
    final NetworkAddressPoolAssignment address4;
    {
        address4 = instance.addChild(NetworkAddressPoolAssignment.class);
        address4.holder = owner;
        address4.poolProvider = DirectCloudUtils.getPrivateAddressPool4();
    }
    final NetworkAddressPoolAssignment address6;
    {
        address6 = instance.addChild(NetworkAddressPoolAssignment.class);
        address6.holder = owner;
        address6.poolProvider = directCloudHelpers.getAddressPool6();
    }
    {
        NetworkTunDevice tun = injected(NetworkTunDevice.class);
        tun.interfaceName = getEthernetDeviceName();
        tun.bridgeName = new Provider<String>() {

            @Override
            public String get() {
                DirectHost host = OpsContext.get().getInstance(DirectHost.class);
                return host.bridge;
            }
        };
        instance.addChild(tun);
    }
    final SocketAddressPoolAssignment assignMonitorPort;
    {
        assignMonitorPort = injected(SocketAddressPoolAssignment.class);
        assignMonitorPort.holder = owner;
        assignMonitorPort.poolProvider = DirectCloudUtils.getKvmMonitorPortPool();
        instance.addChild(assignMonitorPort);
    }
    final SocketAddressPoolAssignment assignVncPort;
    {
        assignVncPort = injected(SocketAddressPoolAssignment.class);
        assignVncPort.holder = owner;
        assignVncPort.poolProvider = DirectCloudUtils.getVncPortPool();
        instance.addChild(assignVncPort);
    }
    {
        ConfigIso iso = injected(ConfigIso.class);
        iso.isoFile = getConfigIsoPath();
        iso.buildDir = new File(getInstanceDir(), "config_iso_src");
        iso.model = new TemplateDataSource() {

            @Override
            public void buildTemplateModel(Map<String, Object> model) throws OpsException {
                InterfaceModel eth0 = InterfaceModel.build("eth0");
                AddressModel ipv4 = address4.get();
                eth0.addAddress(ipv4);
                AddressModel ipv6 = address6.get();
                eth0.addAddress(ipv6);
                List<InterfaceModel> interfaces = Lists.newArrayList();
                interfaces.add(eth0);
                model.put("interfaces", interfaces);
                List<String> authorizedKeys = Lists.newArrayList();
                authorizedKeys.add(OpenSshUtils.serialize(sshPublicKey));
                model.put("authorizedKeys", authorizedKeys);
            }
        };
        instance.addChild(iso);
    }
    {
        DownloadImage download = injected(DownloadImage.class);
        download.imageFile = getImagePath();
        download.recipeKey = recipeId;
        download.imageFormats = Arrays.asList(ImageFormat.DiskRaw, ImageFormat.DiskQcow2);
        instance.addChild(download);
    }
    {
        ManagedKvmInstance kvmInstance = addChild(ManagedKvmInstance.class);
        kvmInstance.id = id;
        kvmInstance.memoryMb = Math.max(256, minimumMemoryMB);
        kvmInstance.vcpus = 1;
        kvmInstance.base = getInstanceDir();
        kvmInstance.monitor = assignMonitorPort;
        kvmInstance.vnc = assignVncPort;
        kvmInstance.nics = buildVnics();
        kvmInstance.drives = buildDrives();
        kvmInstance.addresses.add(address4);
        kvmInstance.addresses.add(address6);
    }
    {
        final DirectInstance model = OpsContext.get().getInstance(DirectInstance.class);
        OpsProvider<TagChanges> tagChanges = new OpsProvider<TagChanges>() {

            @Override
            public TagChanges get() {
                TagChanges tagChanges = new TagChanges();
                tagChanges.addTags.add(Tag.INSTANCE_KEY.build(model.getKey()));
                AddressModel ipv4 = address4.get();
                AddressModel ipv6 = address6.get();
                tagChanges.addTags.add(Tag.NETWORK_ADDRESS.build(ipv4));
                tagChanges.addTags.add(Tag.NETWORK_ADDRESS.build(ipv6));
                return tagChanges;
            }
        };
        addChild(Tagger.build(model, tagChanges));
    }
}
Also used : NetworkAddressPoolAssignment(org.platformlayer.ops.pool.NetworkAddressPoolAssignment) SocketAddressPoolAssignment(org.platformlayer.ops.pool.SocketAddressPoolAssignment) TemplateDataSource(org.platformlayer.ops.templates.TemplateDataSource) DirectInstance(org.platformlayer.service.cloud.direct.model.DirectInstance) TagChanges(org.platformlayer.core.model.TagChanges) OpsProvider(org.platformlayer.ops.OpsProvider) Provider(com.google.inject.Provider) CloudInstanceMapper(org.platformlayer.service.cloud.direct.ops.CloudInstanceMapper) DirectHost(org.platformlayer.service.cloud.direct.model.DirectHost) InterfaceModel(org.platformlayer.ops.networks.InterfaceModel) OpsProvider(org.platformlayer.ops.OpsProvider) AddressModel(org.platformlayer.core.model.AddressModel) File(java.io.File) Map(java.util.Map) DownloadImage(org.platformlayer.service.cloud.direct.ops.DownloadImage)

Example 100 with Provider

use of com.google.inject.Provider in project roboguice by roboguice.

the class InjectorImpl method getProviderOrThrow.

<T> Provider<T> getProviderOrThrow(final Key<T> key, Errors errors) throws ErrorsException {
    final BindingImpl<? extends T> binding = getBindingOrThrow(key, errors, JitLimitation.NO_JIT);
    final Dependency<T> dependency = Dependency.get(key);
    return new Provider<T>() {

        public T get() {
            final Errors errors = new Errors(dependency);
            try {
                T t = callInContext(new ContextualCallable<T>() {

                    public T call(InternalContext context) throws ErrorsException {
                        Dependency previous = context.pushDependency(dependency, binding.getSource());
                        try {
                            return binding.getInternalFactory().get(errors, context, dependency, false);
                        } finally {
                            context.popStateAndSetDependency(previous);
                        }
                    }
                });
                errors.throwIfNewErrors(0);
                return t;
            } catch (ErrorsException e) {
                throw new ProvisionException(errors.merge(e.getErrors()).getMessages());
            }
        }

        @Override
        public String toString() {
            return binding.getInternalFactory().toString();
        }
    };
}
Also used : ProvisionException(com.google.inject.ProvisionException) Dependency(com.google.inject.spi.Dependency) SourceProvider(com.google.inject.internal.util.SourceProvider) Provider(com.google.inject.Provider)

Aggregations

Provider (com.google.inject.Provider)132 Injector (com.google.inject.Injector)72 AbstractModule (com.google.inject.AbstractModule)63 Module (com.google.inject.Module)44 Key (com.google.inject.Key)17 TypeLiteral (com.google.inject.TypeLiteral)10 ArrayList (java.util.ArrayList)10 ProvisionException (com.google.inject.ProvisionException)9 Dependency (com.google.inject.spi.Dependency)9 Map (java.util.Map)8 Before (org.junit.Before)7 CurrentUser (com.google.gerrit.server.CurrentUser)6 RequestContext (com.google.gerrit.server.util.RequestContext)6 ThreadLocalRequestContext (com.google.gerrit.server.util.ThreadLocalRequestContext)6 InMemoryModule (com.google.gerrit.testutil.InMemoryModule)6 PrivateModule (com.google.inject.PrivateModule)6 Scope (com.google.inject.Scope)6 List (java.util.List)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 Annotation (java.lang.annotation.Annotation)5