index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test/mocks/MockHandler.java
package com.netflix.governator.guice.test.mocks; /** * Abstraction for creating/resetting Mocks and Spies. Must have a default constructor. */ public interface MockHandler { <T> T createMock(Class<T> classToMock); <T> T createMock(Class<T> classToMock, Object answerMode); <T> T createSpy(T objectToSpy); void resetMock(Object mockToReset); }
5,600
0
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test/mocks
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test/mocks/mockito/MockitoMockHandler.java
package com.netflix.governator.guice.test.mocks.mockito; import org.mockito.Mockito; import org.mockito.stubbing.Answer; import com.netflix.governator.guice.test.mocks.MockHandler; public class MockitoMockHandler implements MockHandler { @Override public <T> T createMock(Class<T> classToMock) { return Mockito.mock(classToMock); } @Override public <T> T createMock(Class<T> classToMock, Object args) { if (args instanceof Answer<?>) { return Mockito.mock(classToMock, (Answer<?>) args); } else { throw new IllegalArgumentException( "MockitoMockHandler only supports arguments of type " + Answer.class.getName() + ". Provided " + args != null ? args.getClass().getName() : "null"); } } @Override public <T> T createSpy(T objectToSpy) { return Mockito.spy(objectToSpy); } @Override public void resetMock(Object mockToReset) { Mockito.reset(mockToReset); } }
5,601
0
Create_ds/governator/buildSrc/lib
Create_ds/governator/buildSrc/lib/jdiff-1.1.1/Null.java
/** * This class is used only as a "null" argument for Javadoc when comparing * two API files. Javadoc has to have a package, .java or .class file as an * argument, even though JDiff doesn't use it. */ public class Null { public Null() { } }
5,602
0
Create_ds/governator/governator-jersey/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-jersey/src/test/java/com/netflix/governator/guice/jersey/JerseyServerTest.java
package com.netflix.governator.guice.jersey; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Proxy; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.function.UnaryOperator; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.junit.Assert; import org.junit.Test; import com.google.common.io.CharStreams; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.util.Modules; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; import com.netflix.governator.ShutdownHookModule; import com.netflix.governator.guice.jetty.DefaultJettyConfig; import com.netflix.governator.guice.jetty.JettyConfig; import com.netflix.governator.guice.jetty.JettyModule; import com.netflix.governator.guice.jetty.resources3.SampleResource; import com.netflix.governator.providers.Advises; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.api.core.ResourceConfig; import com.sun.jersey.guice.JerseyServletModule; public class JerseyServerTest { @Test public void confirmResourceLoadedWithoutBinding() throws IOException { // Create the injector and autostart Jetty try (LifecycleInjector injector = InjectorBuilder.fromModules( new ShutdownHookModule(), new GovernatorJerseySupportModule(), new JerseyServletModule() { @Override protected void configureServlets() { serve("/*").with(GovernatorServletContainer.class); } @Advises @Singleton @Named("governator") UnaryOperator<DefaultResourceConfig> getResourceConfig() { return config -> { Map<String, Object> props = config.getProperties(); props.put(ResourceConfig.FEATURE_DISABLE_WADL, "false"); config.getClasses().add(SampleResource.class); return config; }; } }, Modules.override(new JettyModule()) .with(new AbstractModule() { @Override protected void configure() { } @Provides JettyConfig getConfig() { // Use emphemeral ports return new DefaultJettyConfig().setPort(0); } })) .createInjector()) { // Determine the emphermal port from jetty Server server = injector.getInstance(Server.class); int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort(); System.out.println("Listening on port : "+ port); URL url = new URL(String.format("http://localhost:%d/", port)); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); Assert.assertEquals(200, conn.getResponseCode()); }; } @Test public void confirmFailedToCreateWithoutRootResources() { // Create the injector and autostart Jetty try (LifecycleInjector injector = InjectorBuilder.fromModules( new ShutdownHookModule(), new GovernatorJerseySupportModule(), new JerseyServletModule() { protected void configureServlets() { serve("/*").with(GovernatorServletContainer.class); } }, Modules.override(new JettyModule()) .with(new AbstractModule() { @Override protected void configure() { } @Provides JettyConfig getConfig() { // Use emphemeral ports return new DefaultJettyConfig().setPort(0); } })) .createInjector()) { Assert.fail(); } catch (Exception e) { Assert.assertTrue(e.getCause().getMessage().contains("The ResourceConfig instance does not contain any root resource classes")); } } @Test public void confirmNoResourceLoadedFromGuiceBinding() throws InterruptedException, MalformedURLException, IOException { try (LifecycleInjector injector = InjectorBuilder.fromModules( new ShutdownHookModule(), new GovernatorJerseySupportModule(), new JerseyServletModule() { protected void configureServlets() { serve("/*").with(GovernatorServletContainer.class); bind(SampleResource.class); } }, Modules.override(new JettyModule()) .with(new AbstractModule() { @Override protected void configure() { } @Provides JettyConfig getConfig() { // Use emphemeral ports return new DefaultJettyConfig().setPort(0); } })) .createInjector()) { Assert.fail(); } catch (Exception e) { Assert.assertTrue(e.getCause().getMessage().contains("The ResourceConfig instance does not contain any root resource classes")); } } @Path("/") @Singleton public static class FieldInjectionResource { private static int createCount = 0; public FieldInjectionResource() { createCount++; } @Inject private String foo; @Context UriInfo uri; @GET public String get() { return foo; } } @Test public void confirmNonJerseySingletonNotEagerOrASingleton() { // Create the injector and autostart Jetty try (LifecycleInjector injector = InjectorBuilder.fromModules( new ShutdownHookModule(), new GovernatorJerseySupportModule(), new JerseyServletModule() { protected void configureServlets() { serve("/*").with(GovernatorServletContainer.class); bind(String.class).toInstance("foo"); } @Advises @Singleton @Named("governator") UnaryOperator<DefaultResourceConfig> getResourceConfig() { return config -> { config.getClasses().add(FieldInjectionResource.class); return config; }; } }, Modules.override(new JettyModule()) .with(new AbstractModule() { @Override protected void configure() { } @Provides JettyConfig getConfig() { // Use emphemeral ports return new DefaultJettyConfig().setPort(0); } })) .createInjector()) { Assert.assertEquals(0, FieldInjectionResource.createCount); // Determine the emphermal port from jetty Server server = injector.getInstance(Server.class); int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort(); System.out.println("Listening on port : "+ port); URL url = new URL(String.format("http://localhost:%d/", port)); { HttpURLConnection conn = (HttpURLConnection)url.openConnection(); Assert.assertEquals(200, conn.getResponseCode()); Assert.assertEquals(1, FieldInjectionResource.createCount); } { HttpURLConnection conn = (HttpURLConnection)url.openConnection(); Assert.assertEquals(200, conn.getResponseCode()); Assert.assertEquals(2, FieldInjectionResource.createCount); } } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } @Path("/") @com.sun.jersey.spi.resource.Singleton public static class UriContextIsRequestScoped { @Context UriInfo uri; @GET @Path("{subResources:.*}") public String get(@PathParam("subResources") String subResources) { Assert.assertTrue(Proxy.isProxyClass(uri.getClass())); return uri.getPath(); } } @Test public void confirmUriInfoContextIsRequestScoped() { // Create the injector and autostart Jetty try (LifecycleInjector injector = InjectorBuilder.fromModules( new ShutdownHookModule(), new GovernatorJerseySupportModule(), new JerseyServletModule() { protected void configureServlets() { serve("/*").with(GovernatorServletContainer.class); bind(String.class).toInstance("foo"); } @Advises @Singleton @Named("governator") UnaryOperator<DefaultResourceConfig> getResourceConfig() { return config -> { config.getClasses().add(UriContextIsRequestScoped.class); return config; }; } }, Modules.override(new JettyModule()) .with(new AbstractModule() { @Override protected void configure() { } @Provides JettyConfig getConfig() { // Use emphemeral ports return new DefaultJettyConfig().setPort(0); } })) .createInjector()) { // Determine the emphermal port from jetty Server server = injector.getInstance(Server.class); int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort(); System.out.println("Listening on port : "+ port); { URL url = new URL(String.format("http://localhost:%d/path1", port)); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); Assert.assertEquals(200, conn.getResponseCode()); Assert.assertEquals("path1", CharStreams.toString(new InputStreamReader(conn.getInputStream()))); } { URL url = new URL(String.format("http://localhost:%d/path2", port)); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); Assert.assertEquals(200, conn.getResponseCode()); Assert.assertEquals("path2", CharStreams.toString(new InputStreamReader(conn.getInputStream()))); } } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } }
5,603
0
Create_ds/governator/governator-jersey/src/test/java/com/netflix/governator/guice/jetty
Create_ds/governator/governator-jersey/src/test/java/com/netflix/governator/guice/jetty/resources3/SampleResource.java
package com.netflix.governator.guice.jetty.resources3; import com.netflix.governator.LifecycleShutdownSignal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicInteger; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("/") @Singleton public class SampleResource { private static final Logger LOG = LoggerFactory.getLogger(SampleResource.class); private AtomicInteger counter = new AtomicInteger(); @Inject public SampleResource(LifecycleShutdownSignal event) { } @GET public String getHello() { LOG.info("Saying hello"); return "hello " + counter.incrementAndGet(); } }
5,604
0
Create_ds/governator/governator-jersey/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-jersey/src/main/java/com/netflix/governator/guice/jersey/GovernatorComponentProviderFactory.java
package com.netflix.governator.guice.jersey; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.ws.rs.WebApplicationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.ConfigurationException; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.ProvisionException; import com.google.inject.Scope; import com.google.inject.Scopes; import com.google.inject.servlet.ServletScopes; import com.google.inject.spi.BindingScopingVisitor; import com.sun.jersey.api.core.ResourceConfig; import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.core.spi.component.ComponentScope; import com.sun.jersey.core.spi.component.ioc.IoCComponentProvider; import com.sun.jersey.core.spi.component.ioc.IoCComponentProviderFactory; import com.sun.jersey.core.spi.component.ioc.IoCInstantiatedComponentProvider; import com.sun.jersey.core.spi.component.ioc.IoCManagedComponentProvider; import com.sun.jersey.core.spi.component.ioc.IoCProxiedComponentProvider; /** * Alternative to Guice's GuiceComponentProviderFactory that does NOT copy Guice bindings into the * Jersey configuration */ final class GovernatorComponentProviderFactory implements IoCComponentProviderFactory { private static final Logger LOGGER = LoggerFactory.getLogger(GovernatorComponentProviderFactory.class); private final Map<Scope, ComponentScope> scopeMap = createScopeMap(); private final Injector injector; /** * Creates a new GuiceComponentProviderFactory. * * @param config the resource configuration * @param injector the Guice injector */ public GovernatorComponentProviderFactory(ResourceConfig config, Injector injector) { if (injector == null) { throw new NullPointerException("Guice Injector can not be null!"); } this.injector = injector; } @Override public IoCComponentProvider getComponentProvider(Class<?> c) { return getComponentProvider(null, c); } @Override public IoCComponentProvider getComponentProvider(ComponentContext cc, Class<?> clazz) { LOGGER.info("getComponentProvider({})", clazz.getName()); Key<?> key = Key.get(clazz); Injector i = findInjector(key); // If there is no explicit binding if (i == null) { // If @Inject is explicitly declared on constructor if (isGuiceConstructorInjected(clazz)) { try { // If a binding is possible if (injector.getBinding(key) != null) { LOGGER.info("Binding {} to GuiceInstantiatedComponentProvider", clazz.getName()); return new GuiceInstantiatedComponentProvider(injector, clazz); } } catch (ConfigurationException e) { // The class cannot be injected. // For example, the constructor might contain parameters that // cannot be injected LOGGER.error("Cannot bind " + clazz.getName(), e); // Guice should have picked this up. We fail-fast to prevent // Jersey from trying to handle injection. throw e; } // If @Inject is declared on field or method } else if (isGuiceFieldOrMethodInjected(clazz)) { LOGGER.info("Binding {} to GuiceInjectedComponentProvider", clazz.getName()); return new GuiceInjectedComponentProvider(injector); } else { return null; } } ComponentScope componentScope = getComponentScope(key, i); LOGGER.info("Binding {} to GuiceManagedComponentProvider with the scope \"{}\"", new Object[]{clazz.getName(), componentScope}); return new GuiceManagedComponentProvider(i, componentScope, clazz); } private ComponentScope getComponentScope(Key<?> key, Injector i) { return i.getBinding(key).acceptScopingVisitor(new BindingScopingVisitor<ComponentScope>() { @Override public ComponentScope visitEagerSingleton() { return ComponentScope.Singleton; } @Override public ComponentScope visitScope(Scope theScope) { ComponentScope cs = scopeMap.get(theScope); return (cs != null) ? cs : ComponentScope.Undefined; } @Override public ComponentScope visitScopeAnnotation(Class scopeAnnotation) { // This method is not invoked for Injector bindings throw new UnsupportedOperationException(); } @Override public ComponentScope visitNoScoping() { return ComponentScope.PerRequest; } }); } private Injector findInjector(Key<?> key) { Injector i = injector; while (i != null) { if (i.getBindings().containsKey(key)) { return i; } i = i.getParent(); } return null; } /** * Determine if a class is an implicit Guice component that can be * instantiated by Guice and the life-cycle managed by Jersey. * * @param c the class. * @return true if the class is an implicit Guice component. * @deprecated see {@link #isGuiceConstructorInjected(java.lang.Class) } */ @Deprecated public boolean isImplicitGuiceComponent(Class<?> c) { return isGuiceConstructorInjected(c); } /** * Determine if a class is an implicit Guice component that can be * instantiated by Guice and the life-cycle managed by Jersey. * * @param c the class. * @return true if the class is an implicit Guice component. */ public boolean isGuiceConstructorInjected(Class<?> c) { for (Constructor<?> con : c.getDeclaredConstructors()) { if (isInjectable(con)) { return true; } } return false; } /** * Determine if a class uses field or method injection via Guice * using the {@code Inject} annotation * * @param c the class. * @return true if the class is an implicit Guice component. */ public boolean isGuiceFieldOrMethodInjected(Class<?> c) { for (Method m : c.getDeclaredMethods()) { if (isInjectable(m)) { return true; } } for (Field f : c.getDeclaredFields()) { if (isInjectable(f)) { return true; } } return !c.equals(Object.class) && isGuiceFieldOrMethodInjected(c.getSuperclass()); } private static boolean isInjectable(AnnotatedElement element) { return (element.isAnnotationPresent(com.google.inject.Inject.class) || element.isAnnotationPresent(javax.inject.Inject.class)); } /** * Maps a Guice scope to a Jersey scope. * * @return the map */ public Map<Scope, ComponentScope> createScopeMap() { Map<Scope, ComponentScope> result = new HashMap<Scope, ComponentScope>(); result.put(Scopes.SINGLETON, ComponentScope.Singleton); result.put(Scopes.NO_SCOPE, ComponentScope.PerRequest); result.put(ServletScopes.REQUEST, ComponentScope.PerRequest); return result; } private static class GuiceInjectedComponentProvider implements IoCProxiedComponentProvider { private final Injector injector; public GuiceInjectedComponentProvider(Injector injector) { this.injector = injector; } @Override public Object getInstance() { throw new IllegalStateException(); } @Override public Object proxy(Object o) { try { injector.injectMembers(o); } catch (ProvisionException e) { if (e.getCause() instanceof WebApplicationException) { throw (WebApplicationException)e.getCause(); } throw e; } return o; } } /** * Guice injects instances while Jersey manages their scope. * * @author Gili Tzabari */ private static class GuiceInstantiatedComponentProvider implements IoCInstantiatedComponentProvider { private final Injector injector; private final Class<?> clazz; /** * Creates a new GuiceManagedComponentProvider. * * @param injector the injector * @param clazz the class */ public GuiceInstantiatedComponentProvider(Injector injector, Class<?> clazz) { this.injector = injector; this.clazz = clazz; } public Class<?> getInjectableClass(Class<?> c) { return c.getSuperclass(); } // IoCInstantiatedComponentProvider @Override public Object getInjectableInstance(Object o) { return o; } @Override public Object getInstance() { try { return injector.getInstance(clazz); } catch (ProvisionException e) { if (e.getCause() instanceof WebApplicationException) { throw (WebApplicationException)e.getCause(); } throw e; } } } /** * Guice injects instances and manages their scope. * * @author Gili Tzabari */ private static class GuiceManagedComponentProvider extends GuiceInstantiatedComponentProvider implements IoCManagedComponentProvider { private final ComponentScope scope; /** * Creates a new GuiceManagedComponentProvider. * * @param injector the injector * @param scope the Jersey scope * @param clazz the class */ public GuiceManagedComponentProvider(Injector injector, ComponentScope scope, Class<?> clazz) { super(injector, clazz); this.scope = scope; } @Override public ComponentScope getScope() { return scope; } } }
5,605
0
Create_ds/governator/governator-jersey/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-jersey/src/main/java/com/netflix/governator/guice/jersey/GovernatorServletContainer.java
package com.netflix.governator.guice.jersey; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import javax.servlet.ServletException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Injector; import com.sun.jersey.api.core.ResourceConfig; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import com.sun.jersey.spi.container.WebApplication; import com.sun.jersey.spi.container.servlet.WebConfig; /** * @see GovernatorJerseySupportModule */ @Singleton public class GovernatorServletContainer extends GuiceContainer { private static final long serialVersionUID = -1350697205980976818L; private static final Logger LOG = LoggerFactory.getLogger(GovernatorServletContainer.class); private final ResourceConfig resourceConfig; private final Injector injector; private WebApplication webapp; @Inject protected GovernatorServletContainer(Injector injector, @Named("governator") ResourceConfig resourceConfig) { super(injector); this.resourceConfig = resourceConfig; this.injector = injector; } @Override protected ResourceConfig getDefaultResourceConfig( Map<String, Object> props, WebConfig webConfig) throws ServletException { if (!props.isEmpty()) { throw new IllegalArgumentException("Passing properties via serve() is no longer supported. ResourceConfig properties should be set by the binding for ResourceConfig"); } return this.resourceConfig; } @Override protected void initiate(ResourceConfig config, WebApplication webapp) { this.webapp = webapp; GovernatorComponentProviderFactory factory = new GovernatorComponentProviderFactory(config, injector); webapp.initiate(config, factory); // Make sure all root resources are created eagerly so they're fully initialized // by the time the injector was created, instead of being created lazily at the // first request. for (Class<?> resource : config.getRootResourceClasses()) { if (resource.isAnnotationPresent(com.google.inject.Singleton.class) || resource.isAnnotationPresent(javax.inject.Singleton.class)) { LOG.warn("Class {} should be annotated with Jersey's com.sun.jersey.spi.resource.Singleton. Also make sure that any JAX-RS clasese (such as UriInfo) are injected using Jersey's @Context instead of @Inject.", resource); } } } public WebApplication getWebApplication() { return webapp; } }
5,606
0
Create_ds/governator/governator-jersey/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-jersey/src/main/java/com/netflix/governator/guice/jersey/GovernatorJerseySupportModule.java
package com.netflix.governator.guice.jersey; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.governator.providers.AdvisableAnnotatedMethodScanner; import com.netflix.governator.providers.ProvidesWithAdvice; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.api.core.ResourceConfig; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import javax.inject.Named; import javax.inject.Singleton; import javax.servlet.ServletContext; /** * Module enabling support for Jersey configuration via advisable bindings for {@link DefaultResourceConfig}. * This module provides an alternative Guice integration based on jersey-guice {@link GuiceContainer} but with * less opinions, such as automatically adding any bound class with {@literal @}Path as a resources. * * Applications are expected to customize {@link DefaultResourceConfig} to provide a whitelist of * root resources to expose. This can be done by adding the following {@link @Advises} method to any * Guice module (normally an implementation of JerseyServletModule) * * <pre>{@code @Advises @Singleton @Named("governator") UnaryOperator<DefaultResourceConfig> adviseWithMyApplicationResources() { return defaultResourceConfig -> { // All customizations on {@link DefaultResourceConfig} will be picked up // Specify list of @Path annotated resourcesto serve defaultResourceConfig.getClasses().addAll(Arrays.asList( MyApplicationResource.class )); return defaultResourceConfig; }; } * }</pre> * * Additionally this module adds a binding to the {@link ServletContext} for Jersey. It can be injected * as {@code @Named("governator") ServletContext} * * @see GovernatorServletContainer */ public final class GovernatorJerseySupportModule extends AbstractModule { @Override protected void configure() { bind(GuiceContainer.class).to(GovernatorServletContainer.class).asEagerSingleton(); install(AdvisableAnnotatedMethodScanner.asModule()); } @ProvidesWithAdvice @Singleton @Named("governator") DefaultResourceConfig getDefaultResourceConfigConfig() { return new DefaultResourceConfig(); } @Singleton @Provides @Named("governator") ResourceConfig getResourceConfig(@Named("governator") DefaultResourceConfig config) { return config; } @Singleton @Provides @Named("governator") ServletContext getServletContext(GovernatorServletContainer container) { return container.getServletContext(); } @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object obj) { return getClass().equals(obj.getClass()); } }
5,607
0
Create_ds/governator/governator-jersey/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-jersey/src/main/java/com/netflix/governator/guice/jetty/GovernatorServletContainer.java
package com.netflix.governator.guice.jetty; import com.google.inject.Injector; import com.netflix.governator.guice.jersey.GovernatorJerseySupportModule; import com.sun.jersey.api.core.ResourceConfig; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; /** * @see GovernatorJerseySupportModule */ @Singleton @Deprecated public final class GovernatorServletContainer extends com.netflix.governator.guice.jersey.GovernatorServletContainer { private static final long serialVersionUID = -1350697205980976818L; @Inject GovernatorServletContainer(Injector injector, @Named("governator") ResourceConfig resourceConfig) { super(injector, resourceConfig); } }
5,608
0
Create_ds/governator/governator-test-spock/src/main/java/com/netflix/governator
Create_ds/governator/governator-test-spock/src/main/java/com/netflix/governator/test/GovernatorExtension.java
package com.netflix.governator.test; import org.spockframework.runtime.extension.AbstractGlobalExtension; import org.spockframework.runtime.model.SpecInfo; import com.netflix.governator.guice.test.AnnotationBasedTestInjectorManager; import com.netflix.governator.guice.test.InjectorCreationMode; import com.netflix.governator.guice.test.ModulesForTesting; import com.netflix.governator.guice.test.ReplaceWithMock; import com.netflix.governator.guice.test.WrapWithSpy; import com.netflix.governator.guice.test.mocks.MockHandler; import com.netflix.governator.test.mock.spock.SpockMockHandler; import spock.lang.Specification; /** * A Spock extension which creates a Governator-Guice * injector from a list of modules, as well as provides utilities for * Mocking/Spying bindings. * * See {@link ModulesForTesting}, {@link ReplaceWithMock}, and * {@link WrapWithSpy} for example usage. */ public class GovernatorExtension extends AbstractGlobalExtension { @Override public void visitSpec(SpecInfo spec) { if(spec.isAnnotationPresent(ModulesForTesting.class)) { AnnotationBasedTestInjectorManager annotationBasedTestInjectorManager = new AnnotationBasedTestInjectorManager(spec.getReflection(), SpockMockHandler.class); annotationBasedTestInjectorManager.prepareConfigForTestClass(spec.getReflection()); //Before test class spec.getSetupSpecInterceptors().add(invocation -> { invocation.proceed(); }); //Before test methods spec.getSetupInterceptors().add(invocation -> { MockHandler mockHandler = annotationBasedTestInjectorManager.getMockHandler(); if(mockHandler instanceof SpockMockHandler && invocation.getInstance() instanceof Specification) { ((SpockMockHandler)mockHandler).setSpecification((Specification) invocation.getInstance()); annotationBasedTestInjectorManager.cleanUpMocks(); } if (InjectorCreationMode.BEFORE_TEST_CLASS == annotationBasedTestInjectorManager.getInjectorCreationMode() && annotationBasedTestInjectorManager.getInjector() == null) { annotationBasedTestInjectorManager.createInjector(); } annotationBasedTestInjectorManager.prepareTestFixture(invocation.getInstance()); annotationBasedTestInjectorManager.prepareTestFixture(invocation.getSharedInstance()); annotationBasedTestInjectorManager.prepareConfigForTestClass(spec.getReflection(), invocation.getFeature().getFeatureMethod().getReflection()); if (InjectorCreationMode.BEFORE_EACH_TEST_METHOD == annotationBasedTestInjectorManager.getInjectorCreationMode()) { annotationBasedTestInjectorManager.createInjector(); } invocation.proceed(); }); //After test methods spec.addCleanupInterceptor(invocation -> { annotationBasedTestInjectorManager.cleanUpMethodLevelConfig(); annotationBasedTestInjectorManager.cleanUpMocks(); if (InjectorCreationMode.BEFORE_EACH_TEST_METHOD == annotationBasedTestInjectorManager.getInjectorCreationMode()) { annotationBasedTestInjectorManager.cleanUpInjector(); } invocation.proceed(); }); //After test class spec.addCleanupSpecInterceptor(invocation -> { annotationBasedTestInjectorManager.cleanUpInjector(); invocation.proceed(); }); } super.visitSpec(spec); } }
5,609
0
Create_ds/governator/governator-test-spock/src/main/java/com/netflix/governator/test/mock
Create_ds/governator/governator-test-spock/src/main/java/com/netflix/governator/test/mock/spock/SpockMockHandler.java
package com.netflix.governator.test.mock.spock; import org.spockframework.mock.MockUtil; import com.netflix.governator.guice.test.mocks.MockHandler; import spock.lang.Specification; import spock.mock.DetachedMockFactory; public class SpockMockHandler implements MockHandler { private final DetachedMockFactory mock = new DetachedMockFactory(); private final MockUtil mockUtil = new MockUtil(); private Specification specification; @Override public <T> T createMock(Class<T> classToMock) { T mocked = mock.Mock(classToMock); mockUtil.attachMock(mocked, getSpecification()); return mocked; } @Override public <T> T createMock(Class<T> classToMock, Object args) { return createMock(classToMock); } @Override public <T> T createSpy(T objectToSpy) { T spy = mock.Spy(objectToSpy); mockUtil.attachMock(spy, getSpecification()); return spy; } @Override public void resetMock(Object mockToReset) { mockUtil.detachMock(mockToReset); mockUtil.attachMock(mockToReset, specification); } public Specification getSpecification() { return specification; } public void setSpecification(Specification specification) { this.specification = specification; } }
5,610
0
Create_ds/governator/governator-providers/src/test/java/com/netflix/governator
Create_ds/governator/governator-providers/src/test/java/com/netflix/governator/providers/TestQualifier.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.providers; import javax.inject.Qualifier; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Qualifier @Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface TestQualifier { String name(); }
5,611
0
Create_ds/governator/governator-providers/src/test/java/com/netflix/governator
Create_ds/governator/governator-providers/src/test/java/com/netflix/governator/providers/AdvisedProviderTest.java
package com.netflix.governator.providers; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.function.UnaryOperator; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; public class AdvisedProviderTest { public static class Bar { final List<String> list; @Inject Bar(@TestQualifier(name="bar") List<String> list) { this.list = list; } } private static final TypeLiteral<List<String>> LIST_TYPE_LITERAL = new TypeLiteral<List<String>>() {}; @Test public void testCombinationOfStringClassAndNoQualifiers() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(AdvisableAnnotatedMethodScanner.asModule()); } @ProvidesWithAdvice @Singleton List<String> getListWithNoQualifiers() { return new ArrayList<>(Arrays.asList("")); } @ProvidesWithAdvice @Singleton String getStringBuilder() { return "0"; } @ProvidesWithAdvice @Singleton @Named("foo") List<String> getListWithStringQualifier() { return new ArrayList<>(Arrays.asList("foo")); } @ProvidesWithAdvice @Singleton @TestQualifier(name="bar") List<String> getListWithTestQualifier() { return new ArrayList<>(Arrays.asList("bar")); } @Advises(order=1) UnaryOperator<List<String>> adviseNoQualifier1() { return list -> { list.add("1"); return list; }; } @Advises(order=2) UnaryOperator<List<String>> adviseNoQualifier2() { return list -> { list.add("2"); return list; }; } @Advises(order=1) UnaryOperator<String> adviseNoQualifierStringBuilder1() { return str -> str + "1"; } @Advises(order=2) UnaryOperator<String> adviseNoQualifierStringBuilder2() { return str -> str + "2"; } @Advises(order=1) @Named("foo") UnaryOperator<List<String>> adviseNamedQualifier1() { return list -> { list.add("foo1"); return list; }; } @Advises(order=2) @Named("foo") UnaryOperator<List<String>> adviseNamedQualifier2() { return list -> { list.add("foo2"); return list; }; } @Advises(order=1) @TestQualifier(name="bar") UnaryOperator<List<String>> adviseTestQualifier1() { return list -> { list.add("bar1"); return list; }; } @Advises(order=2) @TestQualifier(name="bar") UnaryOperator<List<String>> adviseTestQualifier2() { return list -> { list.add("bar2"); return list; }; } }); String noQualifierString = injector.getInstance(String.class); List<String> noQualifier = injector.getInstance(Key.get(LIST_TYPE_LITERAL)); List<String> nameQualifier = injector.getInstance(Key.get(LIST_TYPE_LITERAL, Names.named("foo"))); Bar bar = injector.getInstance(Bar.class); Assert.assertEquals("012", noQualifierString); Assert.assertEquals(Arrays.asList("", "1", "2"), noQualifier); Assert.assertEquals(Arrays.asList("foo", "foo1", "foo2"), nameQualifier); Assert.assertEquals(Arrays.asList("bar", "bar1", "bar2"), bar.list); } @Test public void testDuplicateOrder() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(AdvisableAnnotatedMethodScanner.asModule()); } @ProvidesWithAdvice @Singleton List<String> getListWithNoQualifiers() { return new ArrayList<>(Arrays.asList("")); } @Advises(order=1) UnaryOperator<List<String>> adviseNoQualifier1() { return list -> { list.add("1"); return list; }; } @Advises(order=1) UnaryOperator<List<String>> adviseNoQualifier2() { return list -> { list.add("2"); return list; }; } }); List<String> noQualifier = injector.getInstance(Key.get(LIST_TYPE_LITERAL)); Assert.assertEquals(new HashSet<>(Arrays.asList("", "1", "2")), new HashSet<>(noQualifier)); } }
5,612
0
Create_ds/governator/governator-providers/src/test/java/com/netflix/governator
Create_ds/governator/governator-providers/src/test/java/com/netflix/governator/providers/AdvisesBinderTest.java
package com.netflix.governator.providers; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.UnaryOperator; import javax.inject.Named; public class AdvisesBinderTest { static class AdviseList implements UnaryOperator<List<String>> { @Override public List<String> apply(List<String> t) { t.add("a"); return t; } } @Test public void adviseWithAdvice() { TypeLiteral<List<String>> LIST_TYPE_LITERAL = new TypeLiteral<List<String>>() {}; Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(AdvisableAnnotatedMethodScanner.asModule()); AdvisesBinder.bind(binder(), LIST_TYPE_LITERAL).toInstance(new ArrayList<>()); AdvisesBinder.bindAdvice(binder(), LIST_TYPE_LITERAL, 0).to(AdviseList.class); } }); List<String> list = injector.getInstance(Key.get(LIST_TYPE_LITERAL)); Assert.assertEquals(Arrays.asList("a"), list); } @Test public void provisionWithoutAdviseDoesntBlowUp() { TypeLiteral<List<String>> LIST_TYPE_LITERAL = new TypeLiteral<List<String>>() {}; Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(AdvisableAnnotatedMethodScanner.asModule()); AdvisesBinder.bindAdvice(binder(), LIST_TYPE_LITERAL, 0).to(AdviseList.class); } }); } @Test public void adviseWithoutQualifier() { TypeLiteral<List<String>> LIST_TYPE_LITERAL = new TypeLiteral<List<String>>() {}; Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(AdvisableAnnotatedMethodScanner.asModule()); AdvisesBinder.bind(binder(), LIST_TYPE_LITERAL).toInstance(new ArrayList<>()); AdvisesBinder.bindAdvice(binder(), LIST_TYPE_LITERAL, 0).to(AdviseList.class); } @Advises UnaryOperator<List<String>> advise() { return list -> { list.add("b"); return list; }; } }); List<String> list = injector.getInstance(Key.get(LIST_TYPE_LITERAL)); Assert.assertEquals(Arrays.asList("a", "b"), list); } @Test public void adviseWithQualifier() { TypeLiteral<List<String>> LIST_TYPE_LITERAL = new TypeLiteral<List<String>>() {}; Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(AdvisableAnnotatedMethodScanner.asModule()); AdvisesBinder.bind(binder(), LIST_TYPE_LITERAL, Names.named("test")).toInstance(new ArrayList<>()); AdvisesBinder.bindAdvice(binder(), LIST_TYPE_LITERAL, Names.named("test"), 0).to(AdviseList.class); } @Advises @Named("test") UnaryOperator<List<String>> advise() { return list -> { list.add("b"); return list; }; } }); List<String> list = injector.getInstance(Key.get(LIST_TYPE_LITERAL, Names.named("test"))); Assert.assertEquals(Arrays.asList("a", "b"), list); } @Test public void adviseNoBleedingBetweenQualifiers() { TypeLiteral<List<String>> LIST_TYPE_LITERAL = new TypeLiteral<List<String>>() {}; Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(AdvisableAnnotatedMethodScanner.asModule()); AdvisesBinder.bind(binder(), LIST_TYPE_LITERAL, Names.named("test")).toInstance(new ArrayList<>()); AdvisesBinder.bindAdvice(binder(), LIST_TYPE_LITERAL, Names.named("test"), 0).to(AdviseList.class); AdvisesBinder.bind(binder(), LIST_TYPE_LITERAL).toInstance(new ArrayList<>()); AdvisesBinder.bindAdvice(binder(), LIST_TYPE_LITERAL, 0).to(AdviseList.class); } @Advises @Named("test") UnaryOperator<List<String>> adviseQualified() { return list -> { list.add("qualified"); return list; }; } @Advises UnaryOperator<List<String>> adviseNotQualified() { return list -> { list.add("not qualified"); return list; }; } }); List<String> list; list = injector.getInstance(Key.get(LIST_TYPE_LITERAL, Names.named("test"))); Assert.assertEquals(Arrays.asList("a", "qualified"), list); list = injector.getInstance(Key.get(LIST_TYPE_LITERAL)); Assert.assertEquals(Arrays.asList("a", "not qualified"), list); } }
5,613
0
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator/providers/Advises.java
package com.netflix.governator.providers; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * @see ProvidesWithAdvice */ @Documented @Target(METHOD) @Retention(RUNTIME) public @interface Advises { int order() default 1000; }
5,614
0
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator/providers/AdvisedProvider.java
package com.netflix.governator.providers; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.Dependency; import com.google.inject.spi.HasDependencies; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderWithExtensionVisitor; import com.google.inject.spi.Toolable; import com.google.inject.util.Types; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.UnaryOperator; import javax.inject.Provider; class AdvisedProvider<T> implements ProviderWithExtensionVisitor<T>, HasDependencies { private final Set<Dependency<?>> dependencies = new HashSet<>(); private final String name; private final Provider<T> delegate; private final List<ProvisionAdviceHolder<UnaryOperator<T>>> adviceBindings = new ArrayList<>(); private final TypeLiteral<UnaryOperator<T>> advisesType; public AdvisedProvider(TypeLiteral<T> typeLiteral, String name, Annotation annotation, Provider<T> delegate) { this.name = name; this.delegate = delegate; this.advisesType = (TypeLiteral<UnaryOperator<T>>) TypeLiteral.get(Types.newParameterizedType(UnaryOperator.class, typeLiteral.getType())); } @Override public T get() { return adviceBindings .stream() .map(advice -> advice.binding.getProvider().get()) .reduce(delegate.get(), (advised, advice) -> advice.apply(advised), (current, next) -> next); } @Override public Set<Dependency<?>> getDependencies() { return dependencies; } @Override public <B, V> V acceptExtensionVisitor(BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) { return visitor.visit(binding); } @SuppressWarnings("unchecked") @Toolable @javax.inject.Inject protected void initialize(Injector injector) { for (Binding<?> binding : injector.findBindingsByType(advisesType)) { Key<?> bindingKey = binding.getKey(); if (bindingKey.hasAttributes() && AdviceElement.class.isAssignableFrom(bindingKey.getAnnotationType())) { AdviceElementImpl adviceElement = (AdviceElementImpl) bindingKey.getAnnotation(); if (name.equals(adviceElement.name())) { if (adviceElement.type() == AdviceElement.Type.ADVICE) { adviceBindings.add(new ProvisionAdviceHolder<UnaryOperator<T>>((Binding<UnaryOperator<T>>) binding, adviceElement.getOrder())); } dependencies.add(Dependency.get(bindingKey)); } } } adviceBindings.sort(ByOrder); } static Comparator<ProvisionAdviceHolder<?>> ByOrder = new Comparator<ProvisionAdviceHolder<?>>() { @Override public int compare(ProvisionAdviceHolder<?> o1, ProvisionAdviceHolder<?> o2) { int rv = Integer.compare(o1.order, o2.order); if (rv == 0) { return Integer.compare(System.identityHashCode(o1.hashCode()), System.identityHashCode(o2.hashCode())); } return rv; } }; static class ProvisionAdviceHolder<T> { Binding<T> binding; int order; public ProvisionAdviceHolder(Binding<T> binding, int order) { this.order = order; this.binding = binding; } } }
5,615
0
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator/providers/AdviceElement.java
package com.netflix.governator.providers; import static java.lang.annotation.RetentionPolicy.RUNTIME; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; @Retention(RUNTIME) @BindingAnnotation @interface AdviceElement { enum Type { SOURCE, ADVICE } /** * Unique ID that so multiple @Advice with the same return type may be defined without * resulting in a duplicate binding exception. */ int uniqueId(); /** * Name derived from a toString() of a qualifier and is used to match @Advice annotated method * with their @AdviceProvision */ String name(); AdviceElement.Type type(); }
5,616
0
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator/providers/AdvisesBinder.java
package com.netflix.governator.providers; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.util.Types; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.function.UnaryOperator; /** * AdvisesBinder is a Guice usage pattern whereby a provisioned object may be modified or even * replaced using rules specified as bindings themselves. This customization is done before the * provisioned object is injected. This functionality is useful for frameworks that wish to provide * a default implementation of a type but allow extensions and customizations by installing modules * with AdvisesBinder.bindAdvice() bindings. * * {@link Module} method annotations {@literal @}{@link ProvidesWithAdvice} and {@literal @}{@link Advises} * may be used instead of calling AdvisesBinder directly. * * For example, * * <pre> * {@code static class AdviseList implements UnaryOperator{@literal <}List{@literal <}String{@literal >}{@literal >} { @Override public List{@literal <}String{@literal >} apply(List{@literal <}String{@literal >} t) { t.add("customized"); return t; } } public static class MyModule extends AbstractModule() { TypeLiteral{@literal <}List{@literal <}String{@literal >}{@literal >} LIST_TYPE_LITERAL = new TypeLiteral{@literal <}List{@literal <}String{@literal >}{@literal >}() {}; @Override protected void configure() { install(AdvisableAnnotatedMethodScanner.asModule()); AdvisesBinder.bind(binder(), LIST_TYPE_LITERAL).toInstance(new ArrayList{@literal <}{@literal >}()); AdvisesBinder.bindAdvice(binder(), LIST_TYPE_LITERAL, 0).to(AdviseList.class); } }); } * * will add "customized" to the empty list. When List&ltString&gt is finally injected it'll have * ["customized"]. * * Note that AdvisesBinder can be used with qualifiers such as {@literal @}Named. */ public abstract class AdvisesBinder { private AdvisesBinder() { } public static <T> LinkedBindingBuilder<T> bind(Binder binder, TypeLiteral<T> type) { return newRealAdvisesBinder(binder, Key.get(type)); } public static <T> LinkedBindingBuilder<T> bind(Binder binder, Class<T> type) { return newRealAdvisesBinder(binder, Key.get(type)); } public static <T> LinkedBindingBuilder<T> bind(Binder binder, TypeLiteral<T> type, Annotation annotation) { return newRealAdvisesBinder(binder, Key.get(type, annotation)); } public static <T> LinkedBindingBuilder<T> bind(Binder binder, Class<T> type, Annotation annotation) { return newRealAdvisesBinder(binder, Key.get(type, annotation)); } public static <T> LinkedBindingBuilder<T> bind(Binder binder, TypeLiteral<T> type, Class<? extends Annotation> annotationType) { return newRealAdvisesBinder(binder, Key.get(type, annotationType)); } public static <T> LinkedBindingBuilder<T> bind(Binder binder, Key<T> key) { return newRealAdvisesBinder(binder, key); } public static <T> LinkedBindingBuilder<T> bind(Binder binder, Class<T> type, Class<? extends Annotation> annotationType) { return newRealAdvisesBinder(binder, Key.get(type, annotationType)); } static <T> Key<T> getAdvisesKeyForNewItem(Binder binder, Key<T> key) { binder = binder.skipSources(AdvisesBinder.class); Annotation annotation = key.getAnnotation(); String elementName = key.hasAttributes() ? key.getAnnotation().toString() : ""; AdviceElement element = new AdviceElementImpl(elementName, AdviceElement.Type.SOURCE, 0); Key<T> uniqueKey = Key.get(key.getTypeLiteral(), element); // Bind the original key to a new AdvisedProvider binder.bind(key).toProvider(new AdvisedProvider<T>(key.getTypeLiteral(), element.name(), annotation, binder.getProvider(uniqueKey))); return uniqueKey; } static <T> LinkedBindingBuilder<T> newRealAdvisesBinder(Binder binder, Key<T> key) { Key<T> uniqueKey = getAdvisesKeyForNewItem(binder, key); return binder.bind(uniqueKey); } public static <T> LinkedBindingBuilder<UnaryOperator<T>> bindAdvice(Binder binder, TypeLiteral<T> type, int order) { return newRealAdviceBinder(binder, Key.get(type), order); } public static <T> LinkedBindingBuilder<UnaryOperator<T>> bindAdvice(Binder binder, Class<T> type, int order) { return newRealAdviceBinder(binder, Key.get(type), order); } public static <T> LinkedBindingBuilder<UnaryOperator<T>> bindAdvice(Binder binder, TypeLiteral<T> type, Annotation annotation, int order) { return newRealAdviceBinder(binder, Key.get(type, annotation), order); } public static <T> LinkedBindingBuilder<UnaryOperator<T>> bindAdvice(Binder binder, Class<T> type, Annotation annotation, int order) { return newRealAdviceBinder(binder, Key.get(type, annotation), order); } public static <T> LinkedBindingBuilder<UnaryOperator<T>> bindAdvice(Binder binder, TypeLiteral<T> type, Class<? extends Annotation> annotationType, int order) { return newRealAdviceBinder(binder, Key.get(type, annotationType), order); } public static <T> LinkedBindingBuilder<UnaryOperator<T>> bindAdvice(Binder binder, Key<T> key, int order) { return newRealAdviceBinder(binder, key, order); } public static <T> LinkedBindingBuilder<UnaryOperator<T>> bindAdvice(Binder binder, Class<T> type, Class<? extends Annotation> annotationType, int order) { return newRealAdviceBinder(binder, Key.get(type, annotationType), order); } @SuppressWarnings("unchecked") static <T> Key<UnaryOperator<T>> getAdviceKeyForNewItem(Binder binder, Key<T> key, int order) { binder = binder.skipSources(AdvisesBinder.class); String elementName = key.hasAttributes() ? key.getAnnotation().toString() : ""; @SuppressWarnings("unused") Annotation annotation = key.getAnnotation(); Type adviceType = Types.newParameterizedType(UnaryOperator.class, key.getTypeLiteral().getType()); return (Key<UnaryOperator<T>>) Key.get(adviceType, new AdviceElementImpl(elementName, AdviceElement.Type.ADVICE, order)); } static <T> LinkedBindingBuilder<UnaryOperator<T>> newRealAdviceBinder(Binder binder, Key<T> key, int order) { Key<UnaryOperator<T>> uniqueKey = getAdviceKeyForNewItem(binder, key, order); return binder.bind(uniqueKey); } }
5,617
0
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator/providers/AdvisableAnnotatedMethodScanner.java
package com.netflix.governator.providers; import com.google.common.base.Preconditions; import com.google.inject.AbstractModule; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.spi.InjectionPoint; import com.google.inject.spi.ModuleAnnotatedMethodScanner; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.function.UnaryOperator; public final class AdvisableAnnotatedMethodScanner extends ModuleAnnotatedMethodScanner { private static final AdvisableAnnotatedMethodScanner INSTANCE = new AdvisableAnnotatedMethodScanner(); public static AdvisableAnnotatedMethodScanner scanner() { return INSTANCE; } public static Module asModule() { return new AbstractModule() { @Override protected void configure() { binder().scanModulesForAnnotatedMethods(AdvisableAnnotatedMethodScanner.INSTANCE); } }; } private AdvisableAnnotatedMethodScanner() { } @Override public Set<? extends Class<? extends Annotation>> annotationClasses() { return new HashSet<>(Arrays.asList(ProvidesWithAdvice.class, Advises.class)); } @Override public <T> Key<T> prepareMethod(Binder binder, Annotation annotation, Key<T> key, InjectionPoint injectionPoint) { if (annotation instanceof ProvidesWithAdvice) { return AdvisesBinder.getAdvisesKeyForNewItem(binder, key); } else if (annotation instanceof Advises) { Method method = (Method) injectionPoint.getMember(); Preconditions.checkArgument(UnaryOperator.class.isAssignableFrom(method.getReturnType()), "Return type fo @Advice method must be UnaryOperator"); ParameterizedType unaryOperatorType = (ParameterizedType) method.getGenericReturnType(); Type type = unaryOperatorType.getActualTypeArguments()[0]; return (Key<T>) AdvisesBinder.getAdviceKeyForNewItem(binder, key.ofType(type), ((Advises)annotation).order()); } return key; } }
5,618
0
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator/providers/AdviceElementImpl.java
package com.netflix.governator.providers; import java.lang.annotation.Annotation; import java.util.concurrent.atomic.AtomicInteger; class AdviceElementImpl implements AdviceElement { private static final AtomicInteger counter = new AtomicInteger(); private final int id = counter.incrementAndGet(); private final String name; private final Type type; private final int order; public AdviceElementImpl(String name, Type type, int order) { this.name = name; this.type = type; this.order = order; } @Override public Class<? extends Annotation> annotationType() { return AdviceElement.class; } public int getOrder() { return order; } @Override public int uniqueId() { return id; } @Override public String name() { return name; } @Override public Type type() { return type; } @Override public boolean equals(Object o) { return o instanceof AdviceElement && ((AdviceElement) o).name().equals(name()) && ((AdviceElement) o).uniqueId() == uniqueId() && ((AdviceElement) o).type() == type(); } @Override public int hashCode() { return ((127 * "name".hashCode()) ^ name().hashCode()) + ((127 * "id".hashCode()) ^ uniqueId()) + ((127 * "type".hashCode()) ^ type.hashCode()); } public String toString() { return "@" + getClass().getSimpleName() + "(name=" + name() + ", type=" + type() + ", id=" + uniqueId() + ")"; } }
5,619
0
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator
Create_ds/governator/governator-providers/src/main/java/com/netflix/governator/providers/ProvidesWithAdvice.java
package com.netflix.governator.providers; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * {@literal @}ProvidesWithAdvice is a Guice usage pattern whereby a method of a module can be * annotated with {@literal @}ProvidesWithAdvice to return the initial version of an object and then * have {@literal @}Advises annotated methods that can modify the object. All of this happens BEFORE * the final object is injected. This functionality is useful for frameworks that wish to provide * a default implementation of a type but allow extensions and customizations by installing modules * with {@literal @}Advises annotated methods. * * For example, * * <pre> * {@literal @}ProvidesWithAdvice * List<String> provideList() { return new ArrayList<>(Arrays.asList("a", "b", "c")); } * * {@literal @}Advises * UnaryOperator<List<String>> addMoreToList() { return list -> list.add("d"); } * </pre> * * will add "d" to the original ["a", "b", "c"]. When List&ltString&gt is finally injected it'll have * ["a", "b", "c", "d"]. * * Note that {@literal @}ProvideWithAdvice can be used with qualifiers such as {@literal @}Named * with matching qualifiers added to the {@literal @}Advises methods. * */ @Documented @Target(METHOD) @Retention(RUNTIME) public @interface ProvidesWithAdvice { }
5,620
0
Create_ds/governator/governator-archaius/src/test/java/com/netflix/governator
Create_ds/governator/governator-archaius/src/test/java/com/netflix/governator/lifecycle/TestConfiguration.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import com.netflix.config.ConfigurationManager; import com.netflix.governator.configuration.ArchaiusConfigurationProvider; import com.netflix.governator.configuration.CompositeConfigurationProvider; import com.netflix.governator.configuration.ConfigurationOwnershipPolicies; import com.netflix.governator.configuration.ConfigurationProvider; import com.netflix.governator.configuration.PropertiesConfigurationProvider; import com.netflix.governator.lifecycle.mocks.ObjectWithConfig; import com.netflix.governator.lifecycle.mocks.ObjectWithConfigVariable; import com.netflix.governator.lifecycle.mocks.ObjectWithDynamicConfig; import com.netflix.governator.lifecycle.mocks.ObjectWithIgnoreTypeMismatchConfig; import com.netflix.governator.lifecycle.mocks.PreConfigurationChange; import com.netflix.governator.lifecycle.mocks.SubclassedObjectWithConfig; import org.junit.Assert; import org.junit.Test; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class TestConfiguration { private static final String MAP_OF_MAPS_STRING = "{\"foo\": {\"bar\": \"baz\"}}"; private static final Map<String, Map<String, String>> MAP_OF_MAPS_OBJ = new HashMap<String, Map<String, String>>(); static { MAP_OF_MAPS_OBJ.put("foo", new HashMap<String, String>()); MAP_OF_MAPS_OBJ.get("foo").put("bar", "baz"); } @Test public void testPreConfiguration() throws Exception { Properties properties = new Properties(); properties.setProperty("pre-config-test", "not-default"); LifecycleManagerArguments arguments = new LifecycleManagerArguments(); CompositeConfigurationProvider compositeProvider = new CompositeConfigurationProvider(); arguments.setConfigurationProvider(compositeProvider); compositeProvider.add(new PropertiesConfigurationProvider(properties)); LifecycleManager manager = new LifecycleManager(arguments); PreConfigurationChange test = new PreConfigurationChange(compositeProvider); manager.add(test); manager.start(); // assertions in PreConfigurationChange } @Test public void testConfigSubclass() throws Exception { Properties properties = new Properties(); properties.setProperty("test.b", "true"); properties.setProperty("test.i", "100"); properties.setProperty("test.l", "200"); properties.setProperty("test.d", "300.4"); properties.setProperty("test.s", "a is a"); properties.setProperty("test.main", "2468"); properties.setProperty("test.obj", "[1,2,3,4]"); properties.setProperty("test.mapOfMaps", MAP_OF_MAPS_STRING); LifecycleManagerArguments arguments = new LifecycleManagerArguments(); arguments.setConfigurationProvider(new PropertiesConfigurationProvider(properties)); LifecycleManager manager = new LifecycleManager(arguments); SubclassedObjectWithConfig obj = new SubclassedObjectWithConfig(); manager.add(obj); manager.start(); Assert.assertEquals(obj.aBool, true); Assert.assertEquals(obj.anInt, 100); Assert.assertEquals(obj.aLong, 200); Assert.assertEquals(obj.aDouble, 300.4, 0); Assert.assertEquals(obj.aString, "a is a"); Assert.assertEquals(obj.mainInt, 2468); Assert.assertEquals(obj.ints, Arrays.asList(1,2,3,4)); Assert.assertEquals(obj.mapOfMaps, MAP_OF_MAPS_OBJ); } @Test public void testConfig() throws Exception { Properties properties = new Properties(); properties.setProperty("test.b", "true"); properties.setProperty("test.i", "100"); properties.setProperty("test.l", "200"); properties.setProperty("test.d", "300.4"); properties.setProperty("test.s", "a is a"); properties.setProperty("test.dt", "1964-10-06"); properties.setProperty("test.obj", "[1,2,3,4]"); properties.setProperty("test.mapOfMaps", MAP_OF_MAPS_STRING); LifecycleManagerArguments arguments = new LifecycleManagerArguments(); arguments.setConfigurationProvider(new PropertiesConfigurationProvider(properties)); LifecycleManager manager = new LifecycleManager(arguments); ObjectWithConfig obj = new ObjectWithConfig(); manager.add(obj); manager.start(); Assert.assertEquals(obj.aBool, true); Assert.assertEquals(obj.anInt, 100); Assert.assertEquals(obj.aLong, 200); Assert.assertEquals(obj.aDouble, 300.4, 0); Assert.assertEquals(obj.aString, "a is a"); Assert.assertEquals(obj.ints, Arrays.asList(1,2,3,4)); Assert.assertEquals(obj.mapOfMaps, MAP_OF_MAPS_OBJ); } @Test public void testConfigWithVariable() throws Exception { Properties properties = new Properties(); properties.setProperty("test.b", "true"); properties.setProperty("test.i", "101"); properties.setProperty("test.l", "201"); properties.setProperty("test.d", "301.4"); properties.setProperty("test.s", "b is b"); properties.setProperty("test.dt", "1965-10-06"); properties.setProperty("test.obj", "[1,2,3,4]"); LifecycleManagerArguments arguments = new LifecycleManagerArguments(); arguments.setConfigurationProvider(new PropertiesConfigurationProvider(properties)); LifecycleManager manager = new LifecycleManager(arguments); ObjectWithConfigVariable obj = new ObjectWithConfigVariable("test"); manager.add(obj); manager.start(); Assert.assertEquals(obj.aBool, true); Assert.assertEquals(obj.anInt, 101); Assert.assertEquals(obj.aLong, 201); Assert.assertEquals(obj.aDouble, 301.4, 0); Assert.assertEquals(obj.aString, "b is b"); Assert.assertEquals(obj.ints, Arrays.asList(1,2,3,4)); } @Test public void testConfigTypeMismatchWithPropProvider() throws Exception { Properties properties = new Properties(); properties.setProperty("test.b", "20"); properties.setProperty("test.i", "foo"); properties.setProperty("test.l", "bar"); properties.setProperty("test.d", "zar"); properties.setProperty("test.s", "a is a"); properties.setProperty("test.dt", "dar"); testTypeMismatch(new PropertiesConfigurationProvider(properties)); } @Test public void testConfigTypeMismatchWithArchaius() throws Exception { Map<String, String> properties = new HashMap<String, String>(); properties.put("test.b", "20"); properties.put("test.i", "foo"); properties.put("test.l", "bar"); properties.put("test.d", "zar"); properties.put("test.s", "a is a"); properties.put("test.dt", "dar"); //noinspection deprecation testTypeMismatch(new ArchaiusConfigurationProvider(properties)); } @Test public void testDynamicConfiguration() throws Exception { LifecycleManagerArguments arguments = new LifecycleManagerArguments(); arguments.setConfigurationProvider(ArchaiusConfigurationProvider .builder() .withOwnershipPolicy(ConfigurationOwnershipPolicies.ownsAll()) .build()); LifecycleManager manager = new LifecycleManager(arguments); ObjectWithDynamicConfig obj = new ObjectWithDynamicConfig(); manager.add(obj); manager.start(); Assert.assertEquals(obj.aDynamicBool.get(), Boolean.TRUE); Assert.assertEquals(obj.anDynamicInt.get(), new Integer(1)); Assert.assertEquals(obj.anDynamicInt2.get(), new Integer(1)); Assert.assertEquals(obj.aDynamicLong.get(), new Long(2L)); Assert.assertEquals(obj.aDynamicDouble.get(), 3.4, 0); Assert.assertEquals(obj.aDynamicString.get(), "a is a"); Assert.assertEquals(obj.aDynamicString2.get(), "a is a"); Assert.assertEquals(obj.aDynamicDate.get(), null); Assert.assertEquals(obj.aDynamicObj.get(), Arrays.asList(5, 6, 7)); Assert.assertEquals(obj.aDynamicMapOfMaps.get(), Collections.emptyMap()); ConfigurationManager.getConfigInstance().setProperty("test.dynamic.b", "false"); ConfigurationManager.getConfigInstance().setProperty("test.dynamic.i", "101"); ConfigurationManager.getConfigInstance().setProperty("test.dynamic.l", "201"); ConfigurationManager.getConfigInstance().setProperty("test.dynamic.d", "301.4"); ConfigurationManager.getConfigInstance().setProperty("test.dynamic.s", "a is b"); ConfigurationManager.getConfigInstance().setProperty("test.dynamic.dt", "1964-11-06"); ConfigurationManager.getConfigInstance().setProperty("test.dynamic.obj", "[1,2,3,4]"); ConfigurationManager.getConfigInstance().setProperty("test.dynamic.mapOfMaps", MAP_OF_MAPS_STRING); Assert.assertEquals(obj.aDynamicBool.get(), Boolean.FALSE); Assert.assertEquals(obj.anDynamicInt.get(), new Integer(101)); Assert.assertEquals(obj.aDynamicLong.get(), new Long(201L)); Assert.assertEquals(obj.aDynamicDouble.get(), 301.4, 0); Assert.assertEquals(obj.aDynamicString.get(), "a is b"); Assert.assertEquals(obj.aDynamicObj.get(), Arrays.asList(1, 2, 3, 4)); Assert.assertEquals(obj.aDynamicMapOfMaps.get(), MAP_OF_MAPS_OBJ); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Assert.assertEquals(obj.aDynamicDate.get(), formatter.parse("1964-11-06")); } private void testTypeMismatch(ConfigurationProvider provider) throws Exception { LifecycleManagerArguments arguments = new LifecycleManagerArguments(); arguments.setConfigurationProvider(provider); LifecycleManager manager = new LifecycleManager(arguments); ObjectWithIgnoreTypeMismatchConfig obj = new ObjectWithIgnoreTypeMismatchConfig(); ObjectWithIgnoreTypeMismatchConfig nonGovernatedSample = new ObjectWithIgnoreTypeMismatchConfig(); nonGovernatedSample.aDate = new Date(obj.aDate.getTime()); manager.add(obj); manager.start(); Assert.assertEquals(obj.aBool, nonGovernatedSample.aBool); Assert.assertEquals(obj.anInt, nonGovernatedSample.anInt); Assert.assertEquals(obj.aLong, nonGovernatedSample.aLong); Assert.assertEquals(obj.aDouble, nonGovernatedSample.aDouble, 0); Assert.assertEquals(obj.aDate, nonGovernatedSample.aDate); } }
5,621
0
Create_ds/governator/governator-archaius/src/main/java/com/netflix/governator
Create_ds/governator/governator-archaius/src/main/java/com/netflix/governator/configuration/ArchaiusConfigurationProvider.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.configuration.AbstractConfiguration; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicPropertyFactory; import com.netflix.config.PropertyWrapper; /** * Configuration provider backed by Netflix Archaius (https://github.com/Netflix/archaius) */ public class ArchaiusConfigurationProvider extends AbstractObjectConfigurationProvider { private final Map<String, String> variableValues; private final AbstractConfiguration configurationManager; private final DynamicPropertyFactory propertyFactory; private final ConfigurationOwnershipPolicy ownershipPolicy; public static class Builder { private Map<String, String> variableValues = Maps.newHashMap(); private AbstractConfiguration configurationManager = ConfigurationManager.getConfigInstance(); private DynamicPropertyFactory propertyFactory = DynamicPropertyFactory.getInstance(); private ConfigurationOwnershipPolicy ownershipPolicy = ConfigurationOwnershipPolicies.ownsAll(); private ObjectMapper objectMapper = new ObjectMapper(); /** * Set of variables to use when expanding property key names */ public Builder withVariableValues(Map<String, String> variableValues) { this.variableValues = variableValues; return this; } /** * Archaius configuration manager to use. Defaults to ConfigurationManager.getConfigInstance() */ public Builder withConfigurationManager(AbstractConfiguration configurationManager) { this.configurationManager = configurationManager; return this; } /** * Dynamic property factory to use for Supplier<?> attributes. Defaults to DynamicPropertyFactory.getInstance() */ public Builder withPropertyFactory(DynamicPropertyFactory propertyFactory) { this.propertyFactory = propertyFactory; return this; } /** * When set to true this configuration provider will 'have' all properties regardless of whether they * have been set yet or not. This is very important for dynamic properties that have a default value * but haven't been overriden yet. */ public Builder withOwnershipPolicy(ConfigurationOwnershipPolicy policy) { this.ownershipPolicy = policy; return this; } public Builder withObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } public ArchaiusConfigurationProvider build() { if ( this.ownershipPolicy == null ) { this.ownershipPolicy = new ConfigurationOwnershipPolicy() { @Override public boolean has(ConfigurationKey key, Map<String, String> variables) { return configurationManager.containsKey(key.getKey(variableValues)); } }; } return new ArchaiusConfigurationProvider(this); } private Builder() { } } public static Builder builder() { return new Builder(); } /** * Adapter to convert Archaius internal PropertyWrapper to a standard Guava supplier * * @author elandau */ public static class PropertyWrapperProperty<T> extends Property<T> { private final PropertyWrapper<T> wrapper; public PropertyWrapperProperty(PropertyWrapper<T> wrapper) { this.wrapper = wrapper; } @Override public T get() { return this.wrapper.getValue(); } } @Deprecated public ArchaiusConfigurationProvider() { this(new HashMap<String, String>()); } @Deprecated public ArchaiusConfigurationProvider(Map<String, String> variableValues) { this.variableValues = Maps.newHashMap(variableValues); this.configurationManager = ConfigurationManager.getConfigInstance(); this.propertyFactory = DynamicPropertyFactory.getInstance(); this.ownershipPolicy = new ConfigurationOwnershipPolicy() { @Override public boolean has(ConfigurationKey key, Map<String, String> variables) { return configurationManager.containsKey(key.getKey(variables)); } }; } private ArchaiusConfigurationProvider(Builder builder) { super(builder.objectMapper); this.variableValues = builder.variableValues; this.configurationManager = builder.configurationManager; this.propertyFactory = builder.propertyFactory; this.ownershipPolicy = builder.ownershipPolicy; } protected static Property<?> getDynamicProperty(Class<?> type, String key, String defaultValue, DynamicPropertyFactory propertyFactory) { if ( type.isAssignableFrom(String.class) ) { return new PropertyWrapperProperty<String>( propertyFactory.getStringProperty( key, defaultValue)); } else if ( type.isAssignableFrom(Integer.class) ) { return new PropertyWrapperProperty<Integer>( propertyFactory.getIntProperty( key, defaultValue == null ? 0 : Integer.parseInt(defaultValue))); } else if ( type.isAssignableFrom(Double.class) ) { return new PropertyWrapperProperty<Double>( propertyFactory.getDoubleProperty( key, defaultValue == null ? 0.0 : Double.parseDouble(defaultValue))); } else if ( type.isAssignableFrom(Long.class) ) { return new PropertyWrapperProperty<Long>( propertyFactory.getLongProperty( key, defaultValue == null ? 0L : Long.parseLong(defaultValue))); } else if ( type.isAssignableFrom(Boolean.class) ) { return new PropertyWrapperProperty<Boolean>( propertyFactory.getBooleanProperty( key, defaultValue == null ? false : Boolean.parseBoolean(defaultValue))); } throw new RuntimeException("Unsupported value type " + type.getCanonicalName()); } /** * Change a variable value * * @param name name * @param value value */ public void setVariable(String name, String value) { variableValues.put(name, value); } @Override public boolean has(ConfigurationKey key) { return ownershipPolicy.has(key, variableValues); } @Override public Property<Boolean> getBooleanProperty(ConfigurationKey key, Boolean defaultValue) { return new PropertyWrapperProperty<Boolean>( propertyFactory.getBooleanProperty( key.getKey(variableValues), defaultValue)); } @Override public Property<Integer> getIntegerProperty(ConfigurationKey key, Integer defaultValue) { return new PropertyWrapperProperty<Integer>( propertyFactory.getIntProperty( key.getKey(variableValues), defaultValue)); } @Override public Property<Long> getLongProperty(ConfigurationKey key, Long defaultValue) { return new PropertyWrapperProperty<Long>( propertyFactory.getLongProperty( key.getKey(variableValues), defaultValue)); } @Override public Property<Double> getDoubleProperty(ConfigurationKey key, Double defaultValue) { return new PropertyWrapperProperty<Double>( propertyFactory.getDoubleProperty( key.getKey(variableValues), defaultValue)); } @Override public Property<String> getStringProperty(ConfigurationKey key, String defaultValue) { return new PropertyWrapperProperty<String>( propertyFactory.getStringProperty( key.getKey(variableValues), defaultValue)); } @Override public Property<Date> getDateProperty(ConfigurationKey key, Date defaultValue) { return new DateWithDefaultProperty(getStringProperty(key, null), defaultValue); } }
5,622
0
Create_ds/governator/governator-commons-cli/src/test/java/com/netflix/governator
Create_ds/governator/governator-commons-cli/src/test/java/com/netflix/governator/commons_cli/ExampleMain.java
package com.netflix.governator.commons_cli; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; import com.google.inject.AbstractModule; import com.netflix.governator.commons_cli.modules.OptionsModule; import com.netflix.governator.guice.annotations.GovernatorConfiguration; public class ExampleMain { @GovernatorConfiguration public static class MyBootstrap extends AbstractModule { @Override protected void configure() { bind(ExampleMain.class).asEagerSingleton(); install(new OptionsModule() { @Override protected void configureOptions() { option('f').hasArgs(); } }); } } public static void main(final String args[]) { Cli.start(MyBootstrap.class, args); } @Inject public ExampleMain(@Named("f") String filename) { System.out.println("filename=" + filename); } @PostConstruct public void initialize() { System.out.println("Application starting"); } @PostConstruct public void shutdown() { System.out.println("Application stopping"); } }
5,623
0
Create_ds/governator/governator-commons-cli/src/main/java/com/netflix/governator
Create_ds/governator/governator-commons-cli/src/main/java/com/netflix/governator/commons_cli/Cli.java
package com.netflix.governator.commons_cli; import com.google.inject.AbstractModule; import com.google.inject.ProvisionException; import com.netflix.governator.annotations.binding.Main; import com.netflix.governator.guice.LifecycleInjector; public class Cli { /** * Utility method to start the CommonsCli using a main class and command line arguments * * @param mainClass * @param args */ public static void start(Class<?> mainClass, final String[] args) { try { LifecycleInjector.bootstrap(mainClass, new AbstractModule() { @Override protected void configure() { bind(String[].class).annotatedWith(Main.class).toInstance(args); } }); } catch (Exception e) { throw new ProvisionException("Error instantiating main class", e); } } }
5,624
0
Create_ds/governator/governator-commons-cli/src/main/java/com/netflix/governator/commons_cli
Create_ds/governator/governator-commons-cli/src/main/java/com/netflix/governator/commons_cli/providers/StringOptionProvider.java
package com.netflix.governator.commons_cli.providers; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import com.google.inject.Inject; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderWithExtensionVisitor; import com.google.inject.spi.Toolable; /** * Custom provider that bridges an Option with an injectable String for the option value * * @author elandau * */ public class StringOptionProvider implements ProviderWithExtensionVisitor<String> { private CommandLine commandLine; private Option option; private String defaultValue; public StringOptionProvider(Option option, String defaultValue) { this.option = option; } @Override public String get() { return commandLine.getOptionValue(option.getOpt(), defaultValue); } /** * This is needed for 'initialize(injector)' below to be called so the provider * can get the injector after it is instantiated. */ @Override public <B, V> V acceptExtensionVisitor( BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) { return visitor.visit(binding); } @Inject @Toolable void initialize(CommandLine commandLine) { this.commandLine = commandLine; } }
5,625
0
Create_ds/governator/governator-commons-cli/src/main/java/com/netflix/governator/commons_cli
Create_ds/governator/governator-commons-cli/src/main/java/com/netflix/governator/commons_cli/modules/OptionsModule.java
package com.netflix.governator.commons_cli.modules; import java.lang.annotation.Annotation; import java.util.List; import javax.inject.Inject; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.Parser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.inject.AbstractModule; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.Singleton; import com.google.inject.binder.AnnotatedBindingBuilder; import com.google.inject.name.Names; import com.netflix.governator.annotations.binding.Main; import com.netflix.governator.commons_cli.providers.StringOptionProvider; /** * Guicify Apache Commons CLI. * * Usages * * <pre> * {code * * // When creating Guice * * install(new OptionsModule() { * protected void configure() { * option("f") * .hasArg() * .withLongOpt("filename") * .annotatedWith(Filename.class); // no need to call create() * * } * }) * * // Inject into any class * * @Singleton * public class MyService { * @Inject * public MyService(@Filename String filename) { * } * } * * // You can also inject CommandLine directly * * @Singleton * public class MyService { * @Inject * public MyService(CommandLine commandLine) { * } * } * * } * </pre> * * @author elandau * */ public abstract class OptionsModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(OptionsModule.class); private List<OptionBuilder> builders = Lists.newArrayList(); private boolean parserIsBound = false; /** * Non-static version of commons CLI OptionBuilder * * @author elandau */ protected class OptionBuilder { private String longopt; private String description; private String argName; private boolean required; private int numberOfArgs = Option.UNINITIALIZED; private Object type; private boolean optionalArg; private char valuesep; private String shortopt; private String defaultValue; private Class<? extends Annotation> annot; public OptionBuilder annotatedWith(Class<? extends Annotation> annot) { this.annot = annot; return this; } public OptionBuilder withLongOpt(String longopt) { this.longopt = longopt; return this; } public OptionBuilder withShortOpt(char shortopt) { this.shortopt = Character.toString(shortopt); return this; } public OptionBuilder hasArg() { this.numberOfArgs = 1; return this; } public OptionBuilder hasArg(boolean hasArg) { this.numberOfArgs = hasArg ? 1 : Option.UNINITIALIZED; return this; } public OptionBuilder withArgName(String name) { this.argName = name; return this; } public OptionBuilder isRequired() { this.required = true; return this; } public OptionBuilder withValueSeparator(char sep) { this.valuesep = sep; return this; } public OptionBuilder withValueSeparator() { this.valuesep = '='; return this; } public OptionBuilder isRequired(boolean newRequired) { this.required = newRequired; return this; } public OptionBuilder hasArgs() { this.numberOfArgs = Option.UNLIMITED_VALUES; return this; } public OptionBuilder hasArgs(int num) { this.numberOfArgs = num; return this; } public OptionBuilder hasOptionalArg() { this.numberOfArgs = 1; this.optionalArg = true; return this; } public OptionBuilder hasOptionalArgs() { this.numberOfArgs = Option.UNLIMITED_VALUES; this.optionalArg = true; return this; } public OptionBuilder hasOptionalArgs(int numArgs) { this.numberOfArgs = numArgs; this.optionalArg = true; return this; } public OptionBuilder withType(Object newType) { this.type = newType; return this; } public OptionBuilder withDescription(String newDescription) { this.description = newDescription; return this; } public OptionBuilder withDefaultValue(String defaultValue) { this.defaultValue = defaultValue; return this; } Option create() throws IllegalArgumentException { Preconditions.checkNotNull(shortopt); Option option = null; // create the option option = new Option(shortopt, description); // set the option properties option.setLongOpt(longopt); option.setRequired(required); option.setOptionalArg(optionalArg); option.setArgs(numberOfArgs); option.setType(type); option.setValueSeparator(valuesep); option.setArgName(argName); // return the Option instance return option; } } /** * On injection of CommandLine execute the BasicParser * @author elandau */ @Singleton public static class CommandLineProvider implements Provider<CommandLine> { private final Options options; private final String[] arguments; private final Parser parser; @Inject public CommandLineProvider(Options options, @Main String[] arguments, Parser parser) { this.options = options; this.arguments = arguments; this.parser = parser; } @Override public CommandLine get() { try { return parser.parse(options, arguments); } catch (ParseException e) { throw new ProvisionException("Error parsing command line arguments", e); } } } @Override protected final void configure() { configureOptions(); Options options = new Options(); for (OptionBuilder builder : builders) { Option option = builder.create(); if (builder.annot != null) { bind(String.class) .annotatedWith(builder.annot) .toProvider(new StringOptionProvider(option, builder.defaultValue)) .asEagerSingleton(); LOG.info("Binding option to annotation : " + builder.annot.getName()); } else { bind(String.class) .annotatedWith(Names.named(option.getOpt())) .toProvider(new StringOptionProvider(option, builder.defaultValue)) .asEagerSingleton(); LOG.info("Binding option to String : " + option.getOpt()); } options.addOption(option); } bind(Options.class).toInstance(options); bind(CommandLine.class).toProvider(CommandLineProvider.class); if (!parserIsBound) { bindParser().to(BasicParser.class); } } protected abstract void configureOptions(); /** * @param shortopt * @return Return a builder through which a single option may be configured */ protected OptionBuilder option(char shortopt) { OptionBuilder builder = new OptionBuilder().withShortOpt(shortopt); builders.add(builder); return builder; } /** * Bind any parser. BasicParser is used by default if no other parser is provided. */ protected AnnotatedBindingBuilder<Parser> bindParser() { parserIsBound = true; return bind(Parser.class); } }
5,626
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/ServiceLoaderModuleBuilderTest.java
package com.netflix.governator; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Names; import com.google.inject.util.Types; import com.netflix.governator.guice.serviceloader.MyServiceLoadedModule; import com.netflix.governator.guice.serviceloader.ServiceLoaderTest.BoundServiceImpl; import com.netflix.governator.guice.serviceloader.TestService; import org.junit.Assert; import org.junit.Test; import java.util.Set; public class ServiceLoaderModuleBuilderTest { @Test public void testMultibindings() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Boolean.class).toInstance(true); Multibinder .newSetBinder(binder(), TestService.class) .addBinding() .to(BoundServiceImpl.class); install(new ServiceLoaderModuleBuilder().loadServices(TestService.class)); } }); Set<TestService> services = (Set<TestService>) injector.getInstance(Key.get(Types.setOf(TestService.class))); Assert.assertEquals(2, services.size()); for (TestService service : services) { Assert.assertTrue(service.isInjected()); System.out.println(" " + service.getClass().getName()); } } @Test public void testServiceLoadedModules() { Injector injector = Guice.createInjector( new ServiceLoaderModuleBuilder().loadModules(Module.class)); Assert.assertEquals("loaded", injector.getInstance(Key.get(String.class, Names.named(MyServiceLoadedModule.class.getSimpleName())))); } }
5,627
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/ConfigurationModuleTest.java
package com.netflix.governator; import java.util.Properties; import javax.inject.Singleton; import org.junit.Assert; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.governator.annotations.Configuration; import com.netflix.governator.configuration.ConfigurationProvider; import com.netflix.governator.configuration.PropertiesConfigurationProvider; public class ConfigurationModuleTest { public static class A { @Configuration("foo") public String foo; } @Test public void validateConfigurationMappingWorks() { try (LifecycleInjector injector = InjectorBuilder.fromModules(new AbstractModule() { @Override protected void configure() { install(new ConfigurationModule()); } @Singleton @Provides ConfigurationProvider getConfigurationProvider() { Properties props = new Properties(); props.setProperty("foo", "bar"); return new PropertiesConfigurationProvider(props); } }).createInjector()) { A a = injector.getInstance(A.class); Assert.assertEquals("bar", a.foo); } } }
5,628
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/LifecycleInjectorBuilderProvider.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.guice.LifecycleInjectorMode; import com.tngtech.java.junit.dataprovider.DataProvider; public class LifecycleInjectorBuilderProvider { @DataProvider public static Object[][] builders() { return new Object[][] { new Object[] { LifecycleInjector.builder() }, new Object[] { LifecycleInjector.builder().withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) } }; } }
5,629
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/BootstrapTest.java
package com.netflix.governator; import com.google.inject.AbstractModule; import com.google.inject.CreationException; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Stage; import com.netflix.governator.guice.ModulesEx; import com.netflix.governator.guice.annotations.Bootstrap; import org.junit.Assert; import org.junit.Test; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; public class BootstrapTest { public static interface Foo { } public static class Foo1 implements Foo { } public static class Foo2 implements Foo { } @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Bootstrap(module=FooBootstrap.class) public static @interface FooConfiguration { Class<? extends Foo> foo() default Foo1.class; } public static class FooBootstrap extends AbstractModule { private FooConfiguration config; public FooBootstrap(FooConfiguration config) { this.config = config; } @Override protected void configure() { bind(Foo.class).to(config.foo()); } } @FooConfiguration public static class MyApplication extends AbstractModule { @Override protected void configure() { } } @FooConfiguration public static class MyApplicationWithOverride extends AbstractModule { @Override protected void configure() { bind(Foo.class).to(Foo2.class); } } @Test public void testWithoutOverride() { Injector injector = Guice.createInjector(Stage.DEVELOPMENT, ModulesEx.fromClass(MyApplication.class)); Assert.assertEquals(Foo1.class, injector.getInstance(Foo.class).getClass()); } @Test(expected=CreationException.class) public void testDuplicateWithoutOverride() { Injector injector = Guice.createInjector(Stage.DEVELOPMENT, ModulesEx.fromClass(MyApplicationWithOverride.class, false)); Assert.fail("Should have failed with duplicate binding exception"); } @Test public void testDuplicateWithOverride() { Injector injector = Guice.createInjector(Stage.DEVELOPMENT, ModulesEx.fromClass(MyApplicationWithOverride.class)); Assert.assertEquals(Foo2.class, injector.getInstance(Foo.class).getClass()); } }
5,630
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/configuration/TestKeyParser.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; public class TestKeyParser { private static final String VALUE = "value"; private static final String VARIABLE = "variable"; private static String[][] tests = { {"one two three", VALUE, "one two three"}, {"one ${two} three", VALUE, "one ", VARIABLE, "two", VALUE, " three"}, {"${two}", VARIABLE, "two"}, {"${a}b", VARIABLE, "a", VALUE, "b"}, {"a${b}", VALUE, "a", VARIABLE, "b"}, {"", VALUE, ""}, {"1 ${a} 2 ${b}", VALUE, "1 ", VARIABLE, "a", VALUE, " 2 ", VARIABLE, "b"}, {"1 ${a} 2 ${b}${c}", VALUE, "1 ", VARIABLE, "a", VALUE, " 2 ", VARIABLE, "b", VARIABLE, "c"}, {"${a}${b} one ${two} three", VARIABLE, "a", VARIABLE, "b", VALUE, " one ", VARIABLE, "two", VALUE, " three"}, {"${a}${b}one${two}three", VARIABLE, "a", VARIABLE, "b", VALUE, "one", VARIABLE, "two", VALUE, "three"}, {"${", VALUE, "${"}, {"${foo bar", VALUE, "${foo bar"}, {"${${ foo bar}", VARIABLE, "${ foo bar"}, }; @Test public void runTests() { for ( String[] spec : tests ) { List<ConfigurationKeyPart> parts = KeyParser.parse(spec[0]); Assert.assertEquals(Arrays.toString(spec), parts.size(), (spec.length - 1) / 2); for ( int i = 1; (i + 1) < spec.length; i += 2 ) { ConfigurationKeyPart thisPart = parts.get((i - 1) / 2); boolean isVariable = spec[i].equals(VARIABLE); Assert.assertEquals(Arrays.toString(spec) + " : index " + i, isVariable, thisPart.isVariable()); Assert.assertEquals(Arrays.toString(spec) + " : index " + i, spec[i + 1], thisPart.getValue()); } } } }
5,631
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple/TestAutoBindMultiple.java
package com.netflix.governator.autobindmultiple; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.autobindmultiple.basic.BaseForMocks; import com.netflix.governator.autobindmultiple.generic.BaseForGenericMocks; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Set; @RunWith(DataProviderRunner.class) public class TestAutoBindMultiple extends LifecycleInjectorBuilderProvider { @Singleton public static class Container { private final Set<BaseForMocks> mocks; @Inject public Container(Set<BaseForMocks> mocks) { this.mocks = mocks; } public Set<BaseForMocks> getMocks() { return mocks; } } @Singleton public static class GenericContainer { private final Set<BaseForGenericMocks<Integer>> mocks; @Inject public GenericContainer(Set<BaseForGenericMocks<Integer>> mocks) { this.mocks = mocks; } public Set<BaseForGenericMocks<Integer>> getMocks() { return mocks; } } @Test @UseDataProvider("builders") public void testBasic(LifecycleInjectorBuilder lifecycleInjectorBuilder) { Injector injector = lifecycleInjectorBuilder.usingBasePackages("com.netflix.governator.autobindmultiple.basic").createInjector(); Container container = injector.getInstance(Container.class); Assert.assertEquals(container.getMocks().size(), 3); Iterable<String> transformed = Iterables.transform ( container.getMocks(), new Function<BaseForMocks, String>() { @Override public String apply(BaseForMocks mock) { return mock.getValue(); } } ); Assert.assertEquals(Sets.<String>newHashSet(transformed), Sets.newHashSet("A", "B", "C")); } @Test @UseDataProvider("builders") public void testGeneric(LifecycleInjectorBuilder lifecycleInjectorBuilder) { Injector injector = lifecycleInjectorBuilder.usingBasePackages("com.netflix.governator.autobindmultiple.generic").createInjector(); GenericContainer container = injector.getInstance(GenericContainer.class); Assert.assertEquals(container.getMocks().size(), 3); Iterable<Integer> transformed = Iterables.transform ( container.getMocks(), new Function<BaseForGenericMocks<Integer>, Integer>() { @Override public Integer apply(BaseForGenericMocks<Integer> mock) { return mock.getValue(); } } ); Assert.assertEquals(Sets.<Integer>newHashSet(transformed), Sets.newHashSet(1, 2, 3)); } }
5,632
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple/basic/MockB.java
package com.netflix.governator.autobindmultiple.basic; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(multiple = true, baseClass = BaseForMocks.class) public class MockB implements BaseForMocks { @Override public String getValue() { return "B"; } }
5,633
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple/basic/MockC.java
package com.netflix.governator.autobindmultiple.basic; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(multiple = true, baseClass = BaseForMocks.class) public class MockC implements BaseForMocks { @Override public String getValue() { return "C"; } }
5,634
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple/basic/BaseForMocks.java
package com.netflix.governator.autobindmultiple.basic; public interface BaseForMocks { public String getValue(); }
5,635
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple/basic/MockA.java
package com.netflix.governator.autobindmultiple.basic; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(multiple = true, baseClass = BaseForMocks.class) public class MockA implements BaseForMocks { @Override public String getValue() { return "A"; } }
5,636
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple/generic/MockGenericB.java
package com.netflix.governator.autobindmultiple.generic; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(multiple = true, baseClass = BaseForGenericMocks.class) public class MockGenericB implements BaseForGenericMocks<Integer> { @Override public Integer getValue() { return 2; } }
5,637
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple/generic/MockGenericC.java
package com.netflix.governator.autobindmultiple.generic; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(multiple = true, baseClass = BaseForGenericMocks.class) public class MockGenericC implements BaseForGenericMocks<Integer> { @Override public Integer getValue() { return 3; } }
5,638
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple/generic/MockGenericA.java
package com.netflix.governator.autobindmultiple.generic; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(multiple = true, baseClass = BaseForGenericMocks.class) public class MockGenericA implements BaseForGenericMocks<Integer> { @Override public Integer getValue() { return 1; } }
5,639
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmultiple/generic/BaseForGenericMocks.java
package com.netflix.governator.autobindmultiple.generic; public interface BaseForGenericMocks<T> { public T getValue(); }
5,640
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/TestTransitiveNonLazySingletons.java
package com.netflix.governator.guice; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import com.google.inject.Stage; import com.netflix.governator.guice.actions.BindingReport; import com.netflix.governator.guice.actions.CreateAllBoundSingletons; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import java.util.concurrent.atomic.AtomicLong; import javax.inject.Singleton; public class TestTransitiveNonLazySingletons { @Rule public TestName testName = new TestName(); @Singleton public static class ThisShouldBeLazy { public static final AtomicLong counter = new AtomicLong(0); public ThisShouldBeLazy() { System.out.println("ThisShouldBeLazy"); counter.incrementAndGet(); } } @Singleton public static class ThisShouldBeEager { public static final AtomicLong counter = new AtomicLong(0); @Inject public ThisShouldBeEager(Provider<ThisShouldBeLazy> provider) { System.out.println("ThisShouldBeEager"); counter.incrementAndGet(); } } @Before public void setup() { System.out.println("setup"); ThisShouldBeLazy.counter.set(0); ThisShouldBeEager.counter.set(0); } @Test public void shouldNotCreateLazyTransitiveSingleton_Production_Child() { Injector injector = LifecycleInjector.builder() .withModules(new AbstractModule() { @Override protected void configure() { bind(ThisShouldBeEager.class); } }) .withPostInjectorAction(new BindingReport(testName.getMethodName())) .build() .createInjector(); Assert.assertEquals(0, ThisShouldBeLazy.counter.get()); Assert.assertEquals(1, ThisShouldBeEager.counter.get()); } @Test public void shouldCreateAllSingletons_Production_NoChild() { Injector injector = LifecycleInjector.builder() .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .withModules(new AbstractModule() { @Override protected void configure() { bind(ThisShouldBeEager.class); } }) .withPostInjectorAction(new BindingReport(testName.getMethodName())) .build() .createInjector(); Assert.assertEquals(1, ThisShouldBeLazy.counter.get()); Assert.assertEquals(1, ThisShouldBeEager.counter.get()); } @Test public void shouldNotCreateLazyTransitiveSingleton_Development_NoChild() { Injector injector = LifecycleInjector.builder() .inStage(Stage.DEVELOPMENT) .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .withModules(new AbstractModule() { @Override protected void configure() { bind(ThisShouldBeEager.class).asEagerSingleton(); } }) .withPostInjectorAction(new BindingReport(testName.getMethodName())) .build() .createInjector(); Assert.assertEquals(0, ThisShouldBeLazy.counter.get()); Assert.assertEquals(1, ThisShouldBeEager.counter.get()); } @Test public void shouldNotCreateAnyNonEagerSingletons_Development_NoChild() { Injector injector = LifecycleInjector.builder() .inStage(Stage.DEVELOPMENT) .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .withModules(new AbstractModule() { @Override protected void configure() { bind(ThisShouldBeEager.class); } }) .withPostInjectorAction(new BindingReport(testName.getMethodName())) .build() .createInjector(); Assert.assertEquals(0, ThisShouldBeLazy.counter.get()); Assert.assertEquals(0, ThisShouldBeEager.counter.get()); } @Test public void shouldPostCreateAllBoundNonTransitiveSingletons_Development_NoChild() { Injector injector = LifecycleInjector.builder() .inStage(Stage.DEVELOPMENT) .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .withModules(new AbstractModule() { @Override protected void configure() { bind(ThisShouldBeEager.class); } }) .withPostInjectorAction(new BindingReport(testName.getMethodName())) .withPostInjectorAction(new CreateAllBoundSingletons()) .build() .createInjector(); Assert.assertEquals(0, ThisShouldBeLazy.counter.get()); Assert.assertEquals(1, ThisShouldBeEager.counter.get()); } }
5,641
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/TestModuleDependency.java
package com.netflix.governator.guice; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Module; import com.netflix.governator.annotations.Modules; import org.junit.Assert; import org.junit.Test; import java.util.List; import javax.inject.Inject; public class TestModuleDependency { public static class EmptyModule extends AbstractModule { @Override protected void configure() { } } @Modules(include = { AnnotatedModuleDependency.class }) public static class AnnotatedModule extends EmptyModule { } public static class AnnotatedModuleDependency extends EmptyModule { } public static class InjectedModule extends EmptyModule { @Inject InjectedModule(InjectedModuleDependency d) { } } public static class InjectedModuleDependency extends EmptyModule { } @Modules(include = { ReplacementAnnotatedModuleDependency.class } ) public static class ReplacementAnnotatedModule extends EmptyModule {} public static class ReplacementAnnotatedModuleDependency extends EmptyModule {} public static class ReplacementInjectedModule extends InjectedModule { @Inject ReplacementInjectedModule(ReplacementInjectedModuleDependency d) { super(d); } } public static class ReplacementInjectedModuleDependency extends InjectedModuleDependency {} @Modules(include= {AnnotatedModule.class}) public static class ParentAnnotatedModule extends EmptyModule {} @Test public void shouldImportAnnotatedDependency() throws Exception { List<Module> modules = new ModuleListBuilder() .include(AnnotatedModule.class) .build(Guice.createInjector()); assertEquals(modules, AnnotatedModuleDependency.class, AnnotatedModule.class); } @Test public void shouldImportInjectedDependency() throws Exception{ List<Module> modules = new ModuleListBuilder() .include(InjectedModule.class) .build(Guice.createInjector()); assertEquals(modules, InjectedModuleDependency.class, InjectedModule.class); } @Test public void shouldExcludeAnnotatedDependency() throws Exception{ List<Module> modules = new ModuleListBuilder() .include(AnnotatedModule.class) .exclude(AnnotatedModuleDependency.class) .build(Guice.createInjector()); assertEquals(modules, AnnotatedModule.class); } @Test public void shouldExcludeAnnotatedModule() throws Exception{ List<Module> modules = new ModuleListBuilder() .include(AnnotatedModule.class) .exclude(AnnotatedModule.class) .build(Guice.createInjector()); assertEquals(modules); } @Test public void shouldExcludeInjectedModule() throws Exception{ List<Module> modules = new ModuleListBuilder() .include(InjectedModule.class) .exclude(InjectedModule.class) .build(Guice.createInjector()); assertEquals(modules); } @Test public void shouldExcludeInjectedModuleDependency2() throws Exception{ List<Module> modules = new ModuleListBuilder() .include(InjectedModule.class) .exclude(InjectedModuleDependency.class) .build(Guice.createInjector()); assertEquals(modules, InjectedModule.class); } @Test public void shouldIncludeMultipleLevels() throws Exception{ List<Module> modules = new ModuleListBuilder() .include(ParentAnnotatedModule.class) .build(Guice.createInjector()); assertEquals(modules, AnnotatedModuleDependency.class, AnnotatedModule.class, ParentAnnotatedModule.class); } @Test public void shouldInstallAbstractModuleInstance() throws Exception { List<Module> modules = new ModuleListBuilder() .include(new AbstractModule() { @Override protected void configure() { } }) .build(Guice.createInjector()); Assert.assertEquals(1, modules.size()); } @Test public void shouldNotExcludeAbstractModuleInstance() throws Exception { List<Module> modules = new ModuleListBuilder() .include(new AbstractModule() { @Override protected void configure() { } }) .exclude(AbstractModule.class) .build(Guice.createInjector()); Assert.assertEquals(1, modules.size()); } public void assertEquals(List<Module> actual, Class<? extends Module> ... expected) { Assert.assertEquals( Lists.newArrayList(expected), ImmutableList.copyOf(Lists.transform(actual, new Function<Module, Class<? extends Module>>() { @Override public Class<? extends Module> apply(Module module) { return module.getClass(); } }))); } }
5,642
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/TestInjectedConfiguration.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import com.google.inject.Injector; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.configuration.PropertiesConfigurationProvider; import com.netflix.governator.guice.mocks.ObjectWithConfig; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Properties; @RunWith(DataProviderRunner.class) public class TestInjectedConfiguration extends LifecycleInjectorBuilderProvider { @Test @UseDataProvider("builders") public void testConfigurationProvider(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { final Properties properties = new Properties(); properties.setProperty("a", "1"); properties.setProperty("b", "2"); properties.setProperty("c", "3"); Injector injector = lifecycleInjectorBuilder .withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bindConfigurationProvider().toInstance(new PropertiesConfigurationProvider(properties)); } } ) .createInjector(); ObjectWithConfig obj = injector.getInstance(ObjectWithConfig.class); Assert.assertEquals(obj.a, 1); Assert.assertEquals(obj.b, 2); Assert.assertEquals(obj.c, 3); } }
5,643
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/TestSingletonModule.java
package com.netflix.governator.guice; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.CreationException; import com.google.inject.Guice; public class TestSingletonModule { public static interface Foo { } public static class Foo1 implements Foo { } public static class Foo2 implements Foo { } public static final class TestModule extends SingletonModule { @Override protected void configure() { Foo foo = new Foo1(); bind(Foo.class).toInstance(foo); } } public static final class NoDedupTestModule extends AbstractModule { @Override protected void configure() { Foo foo = new Foo1(); bind(Foo.class).toInstance(foo); } } @Test(expected=CreationException.class) public void confirmDupExceptionBehavior() { Guice.createInjector(new NoDedupTestModule(), new NoDedupTestModule()); } @Test public void moduleAddedToInjectorTwiceWillDedup() { Guice.createInjector(new TestModule(), new TestModule()); } @Test public void moduleInstalledTwiceWillDedup() { Guice.createInjector(new AbstractModule() { @Override protected void configure() { this.install(new TestModule()); this.install(new TestModule()); } }); } }
5,644
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/TestGovernatorGuice.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.guice.mocks.ObjectWithGenericInterface; import com.netflix.governator.guice.mocks.SimpleContainer; import com.netflix.governator.guice.mocks.SimpleEagerSingleton; import com.netflix.governator.guice.mocks.SimpleGenericInterface; import com.netflix.governator.guice.mocks.SimpleInterface; import com.netflix.governator.guice.mocks.SimplePojo; import com.netflix.governator.guice.mocks.SimplePojoAlt; import com.netflix.governator.guice.mocks.SimpleProvider; import com.netflix.governator.guice.mocks.SimpleProviderAlt; import com.netflix.governator.guice.mocks.SimpleSingleton; import com.netflix.governator.guice.mocks.UnreferencedSingleton; import com.netflix.governator.guice.modules.ObjectA; import com.netflix.governator.guice.modules.ObjectB; import com.netflix.governator.lifecycle.DefaultLifecycleListener; import com.netflix.governator.lifecycle.FilteredLifecycleListener; import com.netflix.governator.lifecycle.LifecycleListener; import com.netflix.governator.lifecycle.LifecycleManager; import com.netflix.governator.lifecycle.LifecycleState; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; @RunWith(DataProviderRunner.class) public class TestGovernatorGuice extends LifecycleInjectorBuilderProvider { private static final String PACKAGES = "com.netflix.governator.guice.mocks"; @Test @UseDataProvider("builders") public void testAutoBindSingletonToGenericInterface(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { Injector injector = lifecycleInjectorBuilder .usingBasePackages("com.netflix.governator.guice.mocks") .createInjector(); Key<SimpleGenericInterface<String>> key = Key.get(new TypeLiteral<SimpleGenericInterface<String>>(){}); SimpleGenericInterface<String> simple = injector.getInstance(key); Assert.assertEquals(simple.getValue(), "a is a"); ObjectWithGenericInterface obj = injector.getInstance(ObjectWithGenericInterface.class); Assert.assertEquals(obj.getObj().getValue(), "a is a"); } @Test @UseDataProvider("builders") public void testAutoBindSingletonToInterface(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { Injector injector = lifecycleInjectorBuilder .usingBasePackages("com.netflix.governator.guice.mocks") .createInjector(); SimpleInterface simple = injector.getInstance(SimpleInterface.class); Assert.assertEquals(simple.getValue(), 1234); } @Test @UseDataProvider("builders") public void testAutoBindModules(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { Injector injector = lifecycleInjectorBuilder .usingBasePackages("com.netflix.governator.guice.modules") .createInjector(); ObjectA objectA = injector.getInstance(ObjectA.class); ObjectB objectB = injector.getInstance(ObjectB.class); Assert.assertEquals(objectA.getColor(), "blue"); Assert.assertEquals(objectB.getSize(), "large"); } @Test @UseDataProvider("builders") public void testAutoBindSingletonVsSingleton(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { final List<Object> objects = Lists.newArrayList(); final LifecycleListener listener = new DefaultLifecycleListener() { @Override public <T> void objectInjected(TypeLiteral<T> type, T obj) { objects.add(obj); } @Override public void stateChanged(Object obj, LifecycleState newState) { } }; Injector injector = lifecycleInjectorBuilder .usingBasePackages(PACKAGES) .withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bindLifecycleListener().toInstance(new FilteredLifecycleListener(listener, PACKAGES)); } } ) .createInjector(); Assert.assertNull ( Iterables.find ( objects, new Predicate<Object>() { @Override public boolean apply(Object obj) { return obj instanceof UnreferencedSingleton; } }, null ) ); Assert.assertNotNull ( Iterables.find ( objects, new Predicate<Object>() { @Override public boolean apply(Object obj) { return obj instanceof SimpleEagerSingleton; } }, null ) ); injector.getInstance(UnreferencedSingleton.class); Assert.assertNotNull ( Iterables.find ( objects, new Predicate<Object>() { @Override public boolean apply(Object obj) { return obj instanceof UnreferencedSingleton; } }, null ) ); } @Test public void testSimpleProvider() throws Exception { Injector injector = Guice.createInjector ( new AbstractModule() { @Override protected void configure() { ProviderBinderUtil.bind(binder(), SimpleProvider.class, Scopes.SINGLETON); ProviderBinderUtil.bind(binder(), SimpleProviderAlt.class, Scopes.SINGLETON); } } ); SimplePojo pojo = injector.getInstance(SimplePojo.class); Assert.assertEquals(pojo.getI(), 1); Assert.assertEquals(pojo.getS(), "one"); SimplePojoAlt pojoAlt = injector.getInstance(SimplePojoAlt.class); Assert.assertEquals(pojoAlt.getL(), 3); Assert.assertEquals(pojoAlt.getD(), 4.5, 0); } @Test @UseDataProvider("builders") public void testSimpleSingleton(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { Injector injector = lifecycleInjectorBuilder.usingBasePackages(PACKAGES).createInjector(); LifecycleManager manager = injector.getInstance(LifecycleManager.class); manager.start(); SimpleSingleton instance = injector.getInstance(SimpleSingleton.class); Assert.assertEquals(instance.startCount.get(), 1); Assert.assertEquals(instance.finishCount.get(), 0); manager.close(); Assert.assertEquals(instance.startCount.get(), 1); Assert.assertEquals(instance.finishCount.get(), 1); } @Test @UseDataProvider("builders") public void testInjectedIntoAnother(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { Injector injector = lifecycleInjectorBuilder.usingBasePackages(PACKAGES).createInjector(); LifecycleManager manager = injector.getInstance(LifecycleManager.class); manager.start(); SimpleContainer instance = injector.getInstance(SimpleContainer.class); Assert.assertEquals(instance.simpleObject.startCount.get(), 1); Assert.assertEquals(instance.simpleObject.finishCount.get(), 0); manager.close(); Assert.assertEquals(instance.simpleObject.startCount.get(), 1); Assert.assertEquals(instance.simpleObject.finishCount.get(), 1); } }
5,645
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/TestPostInjectAction.java
package com.netflix.governator.guice; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.Stage; import com.netflix.governator.guice.actions.BindingReport; import com.netflix.governator.guice.actions.CreateAllBoundSingletons; import com.netflix.governator.guice.actions.GrapherAction; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import java.util.concurrent.atomic.AtomicInteger; import javax.inject.Inject; import javax.inject.Provider; public class TestPostInjectAction { @Test public void testPostInjectReport() { GrapherAction action = new GrapherAction(); LifecycleInjector.builder() .withPostInjectorAction(action) .build() .createInjector(); Assert.assertNotNull(action.getText()); } public static interface Foo { } @Rule public TestName testName = new TestName(); @Singleton public static class Transitive { private static AtomicInteger counter = new AtomicInteger(); public Transitive() { counter.incrementAndGet(); } } @Singleton public static class FooImpl implements Foo { private static AtomicInteger counter = new AtomicInteger(); @Inject public FooImpl(Provider<Transitive> transitive) { counter.incrementAndGet(); } } public static class FooNotAnnotated implements Foo { private static AtomicInteger counter = new AtomicInteger(); @Inject public FooNotAnnotated(Provider<Transitive> transitive) { counter.incrementAndGet(); } } @Before public void before() { FooImpl.counter.set(0); FooNotAnnotated.counter.set(0); Transitive.counter.set(0); } @Test public void testClassSingleton() { LifecycleInjector.builder() .inStage(Stage.DEVELOPMENT) .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .withPostInjectorAction(new BindingReport(testName.getMethodName())) .withPostInjectorAction(new CreateAllBoundSingletons()) .withModules(new AbstractModule() { @Override protected void configure() { bind(FooImpl.class); } }) .build() .createInjector(); Assert.assertEquals(1, FooImpl.counter.get()); Assert.assertEquals(0, Transitive.counter.get()); } @Test public void testInterfaceSingleton() { LifecycleInjector.builder() .withPostInjectorAction(new BindingReport(testName.getMethodName())) .withPostInjectorAction(new CreateAllBoundSingletons()) .inStage(Stage.DEVELOPMENT) .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .withModules(new AbstractModule() { @Override protected void configure() { bind(Foo.class).to(FooImpl.class); } }) .build() .createInjector(); Assert.assertEquals(1, FooImpl.counter.get()); Assert.assertEquals(0, Transitive.counter.get()); } @Test public void testInterfaceSingletonProductionStage() { LifecycleInjector.builder() .withPostInjectorAction(new BindingReport(testName.getMethodName())) .withPostInjectorAction(new CreateAllBoundSingletons()) .withModules(new AbstractModule() { @Override protected void configure() { bind(Foo.class).to(FooImpl.class); } }) .build() .createInjector(); Assert.assertEquals(1, FooImpl.counter.get()); Assert.assertEquals(0, Transitive.counter.get()); } @Test public void testScopedSingleton() { LifecycleInjector.builder() .withPostInjectorAction(new BindingReport(testName.getMethodName())) .withPostInjectorAction(new CreateAllBoundSingletons()) .inStage(Stage.DEVELOPMENT) .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .withModules(new AbstractModule() { @Override protected void configure() { bind(Foo.class).to(FooNotAnnotated.class).in(Scopes.SINGLETON); } }) .build() .createInjector(); Assert.assertEquals(1, FooNotAnnotated.counter.get()); Assert.assertEquals(0, Transitive.counter.get()); } }
5,646
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/TestBootstrap.java
package com.netflix.governator.guice; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.Assert; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.name.Names; import com.netflix.governator.annotations.Modules; import com.netflix.governator.guice.annotations.Bootstrap; public class TestBootstrap { private static final Logger LOG = LoggerFactory.getLogger(TestBootstrap.class); public static class TestAction implements PostInjectorAction { private boolean injected = false; private final String name; public TestAction(String name) { this.name = name; } @Override public void call(Injector injector) { LOG.info("TestAction: " + name); injected = true; } String getName() { return name; } boolean isInjected() { return injected; } } @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Bootstrap(SuiteBootstrap.class) public static @interface Suite1 { String name(); } @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Bootstrap(bootstrap=ApplicationBootstrap.class) public static @interface Application { String name(); } @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Bootstrap(bootstrap=Application2Bootstrap.class) public static @interface Application2 { String name(); } @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Bootstrap(module=Module1Bootstrap.class) public static @interface Module1 { String name(); } public static class SuiteBootstrap implements LifecycleInjectorBuilderSuite { private final Suite1 suite1; @Inject SuiteBootstrap(Suite1 suite1) { this.suite1 = suite1; } @Override public void configure(LifecycleInjectorBuilder builder) { builder.withAdditionalModules(new AbstractModule() { @Override protected void configure() { bind(String.class).annotatedWith(Names.named("suite1")).toInstance(suite1.name()); } }); } } public static class ApplicationBootstrap implements BootstrapModule { private Application application; @Inject public ApplicationBootstrap(Application application) { this.application = application; } @Override public void configure(BootstrapBinder binder) { binder.bindPostInjectorAction().toInstance(new TestAction(getClass().getSimpleName())); binder.include(new AbstractModule() { @Override protected void configure() { bind(String.class).annotatedWith(Names.named("application")).toInstance(application.name()); } }); } } public static class Application2Bootstrap implements BootstrapModule { @Override public void configure(BootstrapBinder binder) { binder.bindPostInjectorAction().toInstance(new TestAction(getClass().getSimpleName())); } } public static class Module1Bootstrap extends AbstractModule { private Module1 module1; @Inject Module1Bootstrap(Module1 module1) { this.module1 = module1; } @Override public void configure() { bind(String.class).annotatedWith(Names.named("module1")).toInstance(module1.name()); } } public static class InitModule extends AbstractModule { @Inject InitModule(Application application) { Assert.assertEquals("foo", application.name()); } @Override protected void configure() { bind(AtomicInteger.class).annotatedWith(Names.named("init")).toInstance(new AtomicInteger()); } } @Application(name="foo") @Application2(name="goo") @Suite1(name="suite1") @Module1(name="module1") @Modules(include={InitModule.class}) public static class MyApplication extends AbstractModule { @Override protected void configure() { bind(String.class).annotatedWith(Names.named("bar")).toInstance("test"); } } @Test public void testAnnotationWiringAndInjection() { Injector injector = LifecycleInjector.bootstrap(MyApplication.class); Assert.assertEquals("foo", injector.getInstance(Key.get(String.class, Names.named("application")))); Assert.assertEquals("module1", injector.getInstance(Key.get(String.class, Names.named("module1")))); Assert.assertEquals("suite1", injector.getInstance(Key.get(String.class, Names.named("suite1")))); Assert.assertEquals("test", injector.getInstance(Key.get(String.class, Names.named("bar")))); } }
5,647
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/TestStandaloneApplication.java
package com.netflix.governator.guice; import com.google.common.base.Stopwatch; import com.google.inject.AbstractModule; import com.netflix.governator.guice.runner.TerminationEvent; import com.netflix.governator.guice.runner.events.SelfDestructingTerminationEvent; import com.netflix.governator.guice.runner.standalone.StandaloneRunnerModule; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import junit.framework.Assert; public class TestStandaloneApplication { private static Logger LOG = LoggerFactory.getLogger(TestStandaloneApplication.class); private final static AtomicBoolean initCalled = new AtomicBoolean(); private final static AtomicBoolean shutdownCalled = new AtomicBoolean(); public static class SomeSingleton { @PostConstruct public void init() { LOG.info("Init SomeSingleton()"); initCalled.set(true); } @PreDestroy public void shutdown() { LOG.info("Shutdown SomeSingleton()"); shutdownCalled.set(true); } } @BeforeClass public static void before() { initCalled.set(false); shutdownCalled.set(false); } // @Ignore @Test // public void shouldCreateSingletonAndExitAfter1Second() throws Exception { // Stopwatch sw = new Stopwatch().start(); // // final TerminationEvent event = new SelfDestructingTerminationEvent(1, TimeUnit.SECONDS); // LifecycleInjector.builder() // // Example of a singleton that will be created // .withAdditionalModules(new AbstractModule() { // @Override // protected void configure() { // bind(SomeSingleton.class).asEagerSingleton(); // } // }) // .withAdditionalBootstrapModules( // StandaloneRunnerModule.builder() // .withTerminateEvent(event) // .build()) // .build() // .createInjector(); // // event.await(); // long elapsed = sw.elapsed(TimeUnit.MILLISECONDS); // LOG.info("Elapsed: " + elapsed); // Assert.assertTrue(initCalled.get()); // Assert.assertTrue(shutdownCalled.get()); // Assert.assertTrue(elapsed > 1000); // // LOG.info("Exit main"); // // } public static void main(String args[]) { final TerminationEvent event = new SelfDestructingTerminationEvent(1, TimeUnit.SECONDS); LifecycleInjector.builder() // Example of a singleton that will be created .withAdditionalModules(new AbstractModule() { @Override protected void configure() { bind(SomeSingleton.class).asEagerSingleton(); } }) .withAdditionalBootstrapModules( StandaloneRunnerModule.builder() .withTerminateEvent(event) .build()) .build() .createInjector(); } }
5,648
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/TestLifecycleInjector.java
package com.netflix.governator.guice; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.multibindings.OptionalBinder; import com.netflix.governator.lifecycle.LifecycleManager; import org.junit.Assert; import org.junit.Test; import java.util.Optional; import javax.annotation.PreDestroy; import javax.inject.Provider; public class TestLifecycleInjector { public <T extends PreDestroyOnce> void checkCleanup(Module m, Class<T> type) throws Exception { /* * If the PreDestroy method for the object is called more than once, then it * means there is a memory leak because we have registered multiple * ManagedInstanceActions in the PreDestroyMonitor */ Injector injector = LifecycleInjector.builder().withModules(m).build().createInjector(); LifecycleManager mgr = injector.getInstance(LifecycleManager.class); mgr.start(); Object[] objs = new Object[25]; for (int i = 0; i < 25; ++i) { objs[i] = injector.getInstance(type); } mgr.close(); for (Object o : objs) { T t = (T) o; Assert.assertTrue(t.isClosed()); int count = t.getPreDestroyCallCount(); Assert.assertEquals("count equals " + count, 1, count); } } /** registers ProviderInstanceBinding with Singleton scope 1 time */ @Test public void providedInstanceBindingPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { } @Singleton @Provides public PreDestroyOnce providesObj(String param1) { return new PreDestroyOnceImpl(); } }, PreDestroyOnce.class); } /** registers ProviderInstanceBinding with 'no scope' 25 times */ @Test public void providedInstanceBindingUnscopedPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { } @Provides public PreDestroyOnce providesObj(String name) { return new PreDestroyOnceImpl(); } }, PreDestroyOnce.class); } /** * registers ConstructorBindingImpl with Singleton scope 1 time */ @Test public void optionalBindingPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { OptionalBinder.newOptionalBinder(binder(), PreDestroyOnce.class).setDefault().to(PreDestroyOnceImpl.class) .in(Scopes.SINGLETON); } }, PreDestroyOnce.class); } /** * registers ConstructorBindingImpl with Singleton scope 1 time */ @Test public void optionalBindingUnscopedPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { OptionalBinder.newOptionalBinder(binder(), PreDestroyOnce.class).setDefault().to(PreDestroyOnceImpl.class); } }, PreDestroyOnce.class); } /** * registers LinkedProviderBinding in Singleton scope 1 time */ @Test public void optionalProviderBindingPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { OptionalBinder.newOptionalBinder(binder(), PreDestroyOnce.class).setDefault() .toProvider(PreDestroyOnceProvider.class).in(Scopes.SINGLETON); } }, PreDestroyOnce.class); } /** * registers InstanceBinding in Singleton scope 1 time */ @Test public void optionalProviderBindingUnscopedPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { OptionalBinder.newOptionalBinder(binder(), PreDestroyOnce.class).setDefault() .toProvider(PreDestroyOnceProvider.class); OptionalBinder.newOptionalBinder(binder(), PreDestroyOnce.class).setBinding() .toInstance(new PreDestroyOnceImpl()); } }, PreDestroyOnce.class); } /** * registers InstanceBinding in Singleton scope 1 time */ @Test public void providedInstancePreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { OptionalBinder.newOptionalBinder(binder(), PreDestroyOnce.class).setDefault() .toInstance(new PreDestroyOnceImpl()); } }, PreDestroyOnce.class); } /** * registers ConstructorBinding in Singleton scope 1 time */ @Test public void testAutomaticBindingPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { } }, PreDestroyOnceImpl.class); } /** * registers ConstructorBinding in 'No Scope' 25 times * @throws Exception */ @Test public void testAutomaticBindingUnboundPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { } }, PreDestroyOnceProtoImpl.class); } /** * registers ProviderMethodProviderInstanceBinding in Singleton scope 1 times */ @Test public void testSingletonProviderPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { } @Provides @Singleton public PreDestroyOnce providesObj(String name) { return new PreDestroyOnceImpl(); } }, JavaxSingletonConsumer.class); } /** * registers ProviderMethodProviderInstanceBinding in 'No Scope' 25 times */ @Test public void testUnscopedProviderPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { } @Provides public PreDestroyOnce providesObj(String name) { return new PreDestroyOnceImpl(); } }, JavaxSingletonConsumer.class); } /** * registers LinkedProviderBinding in 'No Scope' 25 times */ @Test public void testOptionalPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { OptionalBinder.newOptionalBinder(binder(), PreDestroyOnce.class).setDefault() .toProvider(PreDestroyOnceProvider.class); } }, JavaxOptionalConsumer.class); } /** * registers LinkedProviderBinding in Singleton scope 1 time */ @Test public void testSingletonOptionalPreDestroy() throws Exception { checkCleanup(new AbstractModule() { @Override protected void configure() { OptionalBinder.newOptionalBinder(binder(), PreDestroyOnce.class).setDefault() .toProvider(PreDestroyOnceProvider.class).asEagerSingleton(); } }, JavaxOptionalConsumer.class); } private interface PreDestroyOnce { boolean isClosed(); int getPreDestroyCallCount(); } private static class JavaxSingletonConsumer implements PreDestroyOnce { private final PreDestroyOnce delegate; @Inject JavaxSingletonConsumer(Provider<PreDestroyOnce> provider) { this.delegate = provider.get(); } public boolean isClosed() { return delegate.isClosed(); } public int getPreDestroyCallCount() { return delegate.getPreDestroyCallCount(); } } private static class JavaxOptionalConsumer implements PreDestroyOnce { private final PreDestroyOnce delegate; @Inject JavaxOptionalConsumer(Optional<PreDestroyOnce> provider) { this.delegate = provider.orElse(null); } public boolean isClosed() { return delegate.isClosed(); } public int getPreDestroyCallCount() { return delegate.getPreDestroyCallCount(); } } @Singleton private static class PreDestroyOnceImpl implements PreDestroyOnce { private boolean closed = false; private int counter = 0; @Override public boolean isClosed() { return closed; } @PreDestroy public void close() { ++counter; closed = true; } @Override public int getPreDestroyCallCount() { return counter; } } private static class PreDestroyOnceProtoImpl implements PreDestroyOnce { private boolean closed = false; private int counter = 0; @Override public boolean isClosed() { return closed; } @PreDestroy public void close() { ++counter; closed = true; } @Override public int getPreDestroyCallCount() { return counter; } } @Singleton private static class PreDestroyOnceProvider implements Provider<PreDestroyOnce> { @Override public PreDestroyOnce get() { return new PreDestroyOnceImpl(); } } }
5,649
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/SimplePojo.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.google.inject.Inject; public class SimplePojo { private final String s; private final int i; @Inject public SimplePojo(String s, int i) { this.s = s; this.i = i; } public String getS() { return s; } public int getI() { return i; } }
5,650
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/SimpleProvider.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.annotations.AutoBindSingleton; import javax.inject.Provider; @AutoBindSingleton public class SimpleProvider implements Provider<SimplePojo> { @Override public SimplePojo get() { return new SimplePojo("one", 1); } }
5,651
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/ObjectWithConfig.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.annotations.Configuration; public class ObjectWithConfig { @Configuration("a") public int a; @Configuration("b") public int b; @Configuration("c") public int c; public ObjectWithConfig() { } }
5,652
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/AnnotatedLazySingletonObject.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.guice.lazy.LazySingleton; import javax.annotation.PostConstruct; import java.util.concurrent.atomic.AtomicInteger; @LazySingleton public class AnnotatedLazySingletonObject { public static final AtomicInteger constructorCount = new AtomicInteger(0); public static final AtomicInteger postConstructCount = new AtomicInteger(0); public AnnotatedLazySingletonObject() { constructorCount.incrementAndGet(); } @PostConstruct public void postConstruct() { postConstructCount.incrementAndGet(); } }
5,653
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/LazySingletonObject.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import javax.annotation.PostConstruct; import java.util.concurrent.atomic.AtomicInteger; public class LazySingletonObject { public static final AtomicInteger constructorCount = new AtomicInteger(0); public static final AtomicInteger postConstructCount = new AtomicInteger(0); public LazySingletonObject() { constructorCount.incrementAndGet(); } @PostConstruct public void postConstruct() { postConstructCount.incrementAndGet(); } }
5,654
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/AnnotatedFineGrainedLazySingletonObject.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.guice.lazy.FineGrainedLazySingleton; import com.netflix.governator.guice.lazy.LazySingleton; import javax.annotation.PostConstruct; import java.util.concurrent.atomic.AtomicInteger; @FineGrainedLazySingleton public class AnnotatedFineGrainedLazySingletonObject { public static final AtomicInteger constructorCount = new AtomicInteger(0); public static final AtomicInteger postConstructCount = new AtomicInteger(0); public AnnotatedFineGrainedLazySingletonObject() { constructorCount.incrementAndGet(); } @PostConstruct public void postConstruct() { postConstructCount.incrementAndGet(); } }
5,655
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/SimpleGenericInterface.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; public interface SimpleGenericInterface<T> { public T getValue(); }
5,656
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/SimpleInterface.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; public interface SimpleInterface { public int getValue(); }
5,657
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/SimpleEagerSingleton.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton public class SimpleEagerSingleton { }
5,658
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/AnnotatedLazySingletonObjectAlt.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.guice.lazy.LazySingleton; import javax.annotation.PostConstruct; import java.util.concurrent.atomic.AtomicInteger; @LazySingleton public class AnnotatedLazySingletonObjectAlt { public static final AtomicInteger constructorCount = new AtomicInteger(0); public static final AtomicInteger postConstructCount = new AtomicInteger(0); public AnnotatedLazySingletonObjectAlt() { constructorCount.incrementAndGet(); } @PostConstruct public void postConstruct() { postConstructCount.incrementAndGet(); } }
5,659
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/SimpleProviderAlt.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.annotations.AutoBindSingleton; import javax.inject.Provider; @AutoBindSingleton public class SimpleProviderAlt implements Provider<SimplePojoAlt> { @Override public SimplePojoAlt get() { return new SimplePojoAlt(3, 4.5); } }
5,660
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/SimpleContainer.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.annotations.AutoBindSingleton; import org.junit.Assert; import javax.inject.Inject; @AutoBindSingleton public class SimpleContainer { public final SimpleSingleton simpleObject; @Inject public SimpleContainer(SimpleSingleton simpleObject) { this.simpleObject = simpleObject; Assert.assertEquals(simpleObject.startCount.get(), 1); Assert.assertEquals(simpleObject.finishCount.get(), 0); } }
5,661
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/AutoBindSingletonToInterface.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(SimpleInterface.class) public class AutoBindSingletonToInterface implements SimpleInterface { @Override public int getValue() { return 1234; } }
5,662
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/AutoBindSingletonToGenericInterface.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(SimpleGenericInterface.class) public class AutoBindSingletonToGenericInterface implements SimpleGenericInterface<String> { @Override public String getValue() { return "a is a"; } }
5,663
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/SimpleSingleton.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.google.inject.Inject; import com.google.inject.Singleton; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.concurrent.atomic.AtomicInteger; @Singleton public class SimpleSingleton { public final AtomicInteger startCount = new AtomicInteger(0); public final AtomicInteger finishCount = new AtomicInteger(0); @Inject public SimpleSingleton() { // NOP } @PostConstruct public void start() throws InterruptedException { startCount.incrementAndGet(); } @PreDestroy public void finish() throws InterruptedException { finishCount.incrementAndGet(); } }
5,664
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/SimplePojoAlt.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.google.inject.Inject; public class SimplePojoAlt { private final long l; private final double d; @Inject public SimplePojoAlt(long l, double d) { this.l = l; this.d = d; } public long getL() { return l; } public double getD() { return d; } }
5,665
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/ObjectWithGenericInterface.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.google.inject.Inject; public class ObjectWithGenericInterface { private final SimpleGenericInterface<String> obj; @Inject public ObjectWithGenericInterface(SimpleGenericInterface<String> obj) { this.obj = obj; } public SimpleGenericInterface<String> getObj() { return obj; } }
5,666
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/mocks/UnreferencedSingleton.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.mocks; import com.google.inject.Singleton; @Singleton public class UnreferencedSingleton { }
5,667
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/transformer/OverrideAllDuplicateBindingsTest.java
package com.netflix.governator.guice.transformer; import org.junit.Assert; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.netflix.governator.guice.LifecycleInjector; public class OverrideAllDuplicateBindingsTest { public static interface Foo { } public static class Foo1 implements Foo { } public static class Foo2 implements Foo { } public static class MyModule extends AbstractModule { @Override protected void configure() { bind(Foo.class).to(Foo1.class); } } public static class MyOverrideModule extends AbstractModule { @Override protected void configure() { bind(Foo.class).to(Foo2.class); } } @Test public void testShouldFailOnDuplicate() { try { LifecycleInjector.builder() .withModuleClasses(MyModule.class, MyOverrideModule.class) .build() .createInjector(); Assert.fail("Should have failed with duplicate binding"); } catch (Exception e) { e.printStackTrace(); } } @Test public void testShouldInstallDuplicate() { Injector injector = LifecycleInjector.builder() .withModuleTransformer(new OverrideAllDuplicateBindings()) .withModuleClasses(MyModule.class, MyOverrideModule.class) .build() .createInjector(); Foo foo = injector.getInstance(Foo.class); Assert.assertTrue(foo.getClass().equals(Foo2.class)); } }
5,668
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/concurrent/TestConcurrentSingleton.java
package com.netflix.governator.guice.concurrent; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import junit.framework.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.Test; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.AbstractModule; import com.google.inject.ImplementedBy; import com.google.inject.Injector; import com.netflix.governator.annotations.NonConcurrent; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.guice.LifecycleInjectorMode; import com.netflix.governator.guice.actions.BindingReport; import com.netflix.governator.guice.lazy.FineGrainedLazySingleton; import com.netflix.governator.lifecycle.LoggingLifecycleListener; public class TestConcurrentSingleton { private static Logger LOG = LoggerFactory.getLogger(TestConcurrentSingleton.class); public static interface IParent { } @FineGrainedLazySingleton public static class Parent implements IParent { @Inject Parent(@NonConcurrent NonConcurrentSingleton nonConcurrent, SlowChild1 child1, SlowChild2 child2, Provider<SlowChild3> child3, NonSingletonChild child4, NonSingletonChild child5) { LOG.info("Parent start"); LOG.info("Parent end"); } @PostConstruct public void init() { LOG.info("PostConstruct"); } } @Singleton public static class NonConcurrentSingleton { @Inject public NonConcurrentSingleton(Recorder recorder) throws InterruptedException { recorder.record(getClass()); LOG.info("NonConcurrentSingleton start"); TimeUnit.SECONDS.sleep(1); LOG.info("NonConcurrentSingleton end"); } } @FineGrainedLazySingleton public static class SlowChild1 { @Inject public SlowChild1(Recorder recorder) throws InterruptedException { recorder.record(getClass()); LOG.info("Child1 start"); TimeUnit.SECONDS.sleep(1); LOG.info("Child1 end"); } } @FineGrainedLazySingleton public static class SlowChild2 { @Inject public SlowChild2(Recorder recorder) throws InterruptedException { recorder.record(getClass()); LOG.info("Child2 start"); TimeUnit.SECONDS.sleep(1); LOG.info("Child2 end"); } } @ImplementedBy(SlowChild3Impl.class) public static interface SlowChild3 { } @FineGrainedLazySingleton public static class SlowChild3Impl implements SlowChild3 { @Inject public SlowChild3Impl(Recorder recorder) throws InterruptedException { recorder.record(getClass()); LOG.info("Child3 start"); TimeUnit.SECONDS.sleep(1); LOG.info("Child3 end"); } } public static class NonSingletonChild { private static AtomicInteger counter = new AtomicInteger(); @Inject public NonSingletonChild(Recorder recorder) throws InterruptedException { recorder.record(getClass()); int count = counter.incrementAndGet(); LOG.info("NonSingletonChild start " + count); TimeUnit.SECONDS.sleep(1); LOG.info("NonSingletonChild end " + count); } } @FineGrainedLazySingleton public static class Recorder { Map<Class<?>, Integer> counts = Maps.newHashMap(); Map<Class<?>, Long> threadIds = Maps.newHashMap(); Set<Long> uniqueThreadIds = Sets.newHashSet(); public synchronized void record(Class<?> type) { threadIds.put(type, Thread.currentThread().getId()); uniqueThreadIds.add(Thread.currentThread().getId()); if (!counts.containsKey(type)) { counts.put(type, 1); } else { counts.put(type, counts.get(type)+1); } } public int getUniqueThreadCount() { return uniqueThreadIds.size(); } public int getTypeCount(Class<?> type) { Integer count = counts.get(type); return count == null ? 0 : count; } public long getThreadId(Class<?> type) { return threadIds.get(type); } } @Test public void shouldInitInterfaceInParallel() { Injector injector = LifecycleInjector.builder() .withPostInjectorAction(new BindingReport("Report")) .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .withAdditionalBootstrapModules(new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bindLifecycleListener().to(LoggingLifecycleListener.class); } }) .withModules(new AbstractModule() { @Override protected void configure() { bind(IParent.class).to(Parent.class); bind(Parent.class).toProvider(ConcurrentProviders.of(Parent.class)); } }) .build().createInjector(); // This confirms that the Provider is called via the interface binding injector.getInstance(IParent.class); Recorder recorder = injector.getInstance(Recorder.class); long getMainThreadId = Thread.currentThread().getId(); Assert.assertEquals(5, recorder.getUniqueThreadCount()); Assert.assertEquals(1, recorder.getTypeCount(SlowChild1.class)); Assert.assertEquals(1, recorder.getTypeCount(SlowChild2.class)); Assert.assertEquals(0, recorder.getTypeCount(SlowChild3.class)); // Only the provider was injected Assert.assertEquals(2, recorder.getTypeCount(NonSingletonChild.class)); Assert.assertEquals(getMainThreadId, recorder.getThreadId(NonConcurrentSingleton.class)); } }
5,669
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/lazy/TestLazySingleton.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.lazy; import com.google.inject.Binder; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Provider; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.governator.guice.mocks.AnnotatedLazySingletonObject; import com.netflix.governator.guice.mocks.LazySingletonObject; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(DataProviderRunner.class) public class TestLazySingleton extends LifecycleInjectorBuilderProvider { public static class InjectedProvider { public final Provider<LazySingletonObject> provider; @Inject public InjectedProvider(Provider<LazySingletonObject> provider) { this.provider = provider; } } public static class InjectedAnnotatedProvider { public final Provider<AnnotatedLazySingletonObject> provider; @Inject public InjectedAnnotatedProvider(Provider<AnnotatedLazySingletonObject> provider) { this.provider = provider; } } @Before public void setup() { AnnotatedLazySingletonObject.constructorCount.set(0); AnnotatedLazySingletonObject.postConstructCount.set(0); LazySingletonObject.constructorCount.set(0); LazySingletonObject.postConstructCount.set(0); } @Test @UseDataProvider("builders") public void testUsingAnnotation(LifecycleInjectorBuilder lifecycleInjectorBuilder) { Injector injector = lifecycleInjectorBuilder.createInjector(); Assert.assertEquals(AnnotatedLazySingletonObject.constructorCount.get(), 0); Assert.assertEquals(AnnotatedLazySingletonObject.postConstructCount.get(), 0); AnnotatedLazySingletonObject instance = injector.getInstance(AnnotatedLazySingletonObject.class); Assert.assertEquals(AnnotatedLazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(AnnotatedLazySingletonObject.postConstructCount.get(), 1); AnnotatedLazySingletonObject instance2 = injector.getInstance(AnnotatedLazySingletonObject.class); Assert.assertEquals(AnnotatedLazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(AnnotatedLazySingletonObject.postConstructCount.get(), 1); Assert.assertSame(instance, instance2); } @Test @UseDataProvider("builders") public void testUsingInWithProviderAndAnnotation(LifecycleInjectorBuilder lifecycleInjectorBuilder) { Injector injector = lifecycleInjectorBuilder.createInjector(); Assert.assertEquals(AnnotatedLazySingletonObject.constructorCount.get(), 0); Assert.assertEquals(AnnotatedLazySingletonObject.postConstructCount.get(), 0); InjectedAnnotatedProvider injectedProvider = injector.getInstance(InjectedAnnotatedProvider.class); Assert.assertEquals(AnnotatedLazySingletonObject.constructorCount.get(), 0); Assert.assertEquals(AnnotatedLazySingletonObject.postConstructCount.get(), 0); AnnotatedLazySingletonObject instance = injectedProvider.provider.get(); Assert.assertEquals(AnnotatedLazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(AnnotatedLazySingletonObject.postConstructCount.get(), 1); AnnotatedLazySingletonObject instance2 = injectedProvider.provider.get(); Assert.assertEquals(AnnotatedLazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(AnnotatedLazySingletonObject.postConstructCount.get(), 1); Assert.assertSame(instance, instance2); } @Test @UseDataProvider("builders") public void testUsingIn(LifecycleInjectorBuilder lifecycleInjectorBuilder) { Injector injector = lifecycleInjectorBuilder .withModules ( new Module() { @Override public void configure(Binder binder) { binder.bind(LazySingletonObject.class).in(LazySingletonScope.get()); } } ) .createInjector(); Assert.assertEquals(LazySingletonObject.constructorCount.get(), 0); Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 0); LazySingletonObject instance = injector.getInstance(LazySingletonObject.class); Assert.assertEquals(LazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 1); LazySingletonObject instance2 = injector.getInstance(LazySingletonObject.class); Assert.assertEquals(LazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 1); Assert.assertSame(instance, instance2); } @Test @UseDataProvider("builders") public void testUsingInWithProvider(LifecycleInjectorBuilder lifecycleInjectorBuilder) { Injector injector = lifecycleInjectorBuilder .withModules ( new Module() { @Override public void configure(Binder binder) { binder.bind(LazySingletonObject.class).in(LazySingletonScope.get()); } } ) .createInjector(); Assert.assertEquals(LazySingletonObject.constructorCount.get(), 0); Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 0); InjectedProvider injectedProvider = injector.getInstance(InjectedProvider.class); Assert.assertEquals(LazySingletonObject.constructorCount.get(), 0); Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 0); LazySingletonObject instance = injectedProvider.provider.get(); Assert.assertEquals(LazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 1); LazySingletonObject instance2 = injectedProvider.provider.get(); Assert.assertEquals(LazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(LazySingletonObject.postConstructCount.get(), 1); Assert.assertSame(instance, instance2); } }
5,670
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/lazy/TestFineGrainedLazySingleton.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.lazy; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.governator.guice.mocks.AnnotatedFineGrainedLazySingletonObject; import com.netflix.governator.guice.mocks.LazySingletonObject; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; @RunWith(DataProviderRunner.class) public class TestFineGrainedLazySingleton extends LifecycleInjectorBuilderProvider { public static class InjectedAnnotatedProvider { public final Provider<AnnotatedFineGrainedLazySingletonObject> provider; @Inject public InjectedAnnotatedProvider(Provider<AnnotatedFineGrainedLazySingletonObject> provider) { this.provider = provider; } } @Before public void setup() { AnnotatedFineGrainedLazySingletonObject.constructorCount.set(0); AnnotatedFineGrainedLazySingletonObject.postConstructCount.set(0); LazySingletonObject.constructorCount.set(0); LazySingletonObject.postConstructCount.set(0); } @FineGrainedLazySingleton public static class DeadLockTester { @Inject public DeadLockTester(final Injector injector) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); Executors.newSingleThreadExecutor().submit ( new Callable<Object>() { @Override public Object call() throws Exception { injector.getInstance(AnnotatedFineGrainedLazySingletonObject.class); latch.countDown(); return null; } } ); latch.await(); } } @Test public void testDeadLock() throws InterruptedException { AbstractModule module = new AbstractModule() { @Override protected void configure() { binder().bindScope(LazySingleton.class, LazySingletonScope.get()); binder().bindScope(FineGrainedLazySingleton.class, FineGrainedLazySingletonScope.get()); } }; Injector injector = Guice.createInjector(module); injector.getInstance(DeadLockTester.class); // if FineGrainedLazySingleton is not used, this line will deadlock Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.constructorCount.get(), 1); } @Test @UseDataProvider("builders") public void testUsingAnnotation(LifecycleInjectorBuilder lifecycleInjectorBuilder) { Injector injector = lifecycleInjectorBuilder.createInjector(); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.constructorCount.get(), 0); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.postConstructCount.get(), 0); AnnotatedFineGrainedLazySingletonObject instance = injector.getInstance(AnnotatedFineGrainedLazySingletonObject.class); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.postConstructCount.get(), 1); AnnotatedFineGrainedLazySingletonObject instance2 = injector.getInstance(AnnotatedFineGrainedLazySingletonObject.class); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.postConstructCount.get(), 1); Assert.assertSame(instance, instance2); } @Test @UseDataProvider("builders") public void testUsingInWithProviderAndAnnotation(LifecycleInjectorBuilder lifecycleInjectorBuilder) { Injector injector = lifecycleInjectorBuilder.createInjector(); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.constructorCount.get(), 0); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.postConstructCount.get(), 0); InjectedAnnotatedProvider injectedProvider = injector.getInstance(InjectedAnnotatedProvider.class); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.constructorCount.get(), 0); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.postConstructCount.get(), 0); AnnotatedFineGrainedLazySingletonObject instance = injectedProvider.provider.get(); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.postConstructCount.get(), 1); AnnotatedFineGrainedLazySingletonObject instance2 = injectedProvider.provider.get(); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.constructorCount.get(), 1); Assert.assertEquals(AnnotatedFineGrainedLazySingletonObject.postConstructCount.get(), 1); Assert.assertSame(instance, instance2); } }
5,671
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/modules/ObjectA.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.modules; import com.google.inject.Inject; import com.netflix.governator.annotations.binding.Color; public class ObjectA { private final String color; @Inject public ObjectA(@Color String color) { this.color = color; } public String getColor() { return color; } }
5,672
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/modules/AutoBindModule1.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.modules; import com.google.inject.Binder; import com.google.inject.Module; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.annotations.binding.Size; @AutoBindSingleton public class AutoBindModule1 implements Module { @Override public void configure(Binder binder) { binder.bind(String.class).annotatedWith(Size.class).toInstance("large"); } }
5,673
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/modules/AutoBindModule2.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.modules; import com.google.inject.AbstractModule; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.annotations.binding.Color; @AutoBindSingleton public class AutoBindModule2 extends AbstractModule { @Override protected void configure() { binder().bind(String.class).annotatedWith(Color.class).toInstance("blue"); } }
5,674
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/modules/ObjectB.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice.modules; import com.google.inject.Inject; import com.netflix.governator.annotations.binding.Size; public class ObjectB { private final String size; @Inject public ObjectB(@Size String size) { this.size = size; } public String getSize() { return size; } }
5,675
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/serviceloader/ServiceLoaderTest.java
package com.netflix.governator.guice.serviceloader; import java.util.Set; import javax.inject.Inject; import junit.framework.Assert; import org.junit.Test; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Names; import com.google.inject.util.Types; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.guice.LifecycleInjectorBuilder; public class ServiceLoaderTest { public static class BoundServiceImpl implements TestService { private Boolean injected; @Inject public BoundServiceImpl(Boolean injected) { this.injected = injected; } @Override public boolean isInjected() { return injected; } } @Test public void testMultibindings() { Injector injector = Guice.createInjector(new ServiceLoaderModule() { @Override protected void configureServices() { bind(Boolean.class).toInstance(true); Multibinder .newSetBinder(binder(), TestService.class) .addBinding() .to(BoundServiceImpl.class); bindServices(TestService.class) .usingMultibinding(true); } }); Set<TestService> services = (Set<TestService>) injector.getInstance(Key.get(Types.setOf(TestService.class))); Assert.assertEquals(2, services.size()); for (TestService service : services) { Assert.assertTrue(service.isInjected()); System.out.println(" " + service.getClass().getName()); } } @Test public void testNoMultibindings() { Injector injector = Guice.createInjector(new ServiceLoaderModule() { @Override protected void configureServices() { bind(Boolean.class).toInstance(true); bindServices(TestService.class); } }); Set<TestService> services = (Set<TestService>) injector.getInstance(Key.get(Types.setOf(TestService.class))); Assert.assertEquals(1, services.size()); for (TestService service : services) { Assert.assertTrue(service.isInjected()); System.out.println(" " + service.getClass().getName()); } } @Test public void testServiceLoadedModules() { LifecycleInjectorBuilder builder = LifecycleInjector.builder(); builder.withAdditionalBootstrapModules(new ServiceLoaderBootstrapModule()); Injector injector = builder.build().createInjector(); Assert.assertEquals("loaded", injector.getInstance(Key.get(String.class, Names.named(MyServiceLoadedModule.class.getSimpleName())))); } }
5,676
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/serviceloader/TestServiceImpl.java
package com.netflix.governator.guice.serviceloader; import javax.inject.Inject; public class TestServiceImpl implements TestService { private Boolean injected = false; public TestServiceImpl() { System.out.println("TestServiceImpl"); } @Inject public void setInjected(Boolean injected) { this.injected = injected; } @Override public boolean isInjected() { return injected; } }
5,677
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/serviceloader/TestService.java
package com.netflix.governator.guice.serviceloader; public interface TestService { public boolean isInjected(); }
5,678
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/guice/serviceloader/MyServiceLoadedModule.java
package com.netflix.governator.guice.serviceloader; import com.google.inject.AbstractModule; import com.google.inject.name.Names; public class MyServiceLoadedModule extends AbstractModule { @Override protected void configure() { bind(String.class).annotatedWith(Names.named("MyServiceLoadedModule")).toInstance("loaded"); } }
5,679
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/JavaClasspath.java
package com.netflix.governator.lifecycle; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; import javax.tools.*; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URL; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JavaClasspath { Map<String, byte[]> classpath = new HashMap<>(); Map<String, File> jarByClass = new HashMap<>(); Path temp; ClassLoader classLoader = byteClassLoader(); public JavaClasspath() { try { temp = Files.createTempDirectory("classes"); } catch (IOException e) { throw new IllegalStateException(e); } } public void cleanup() { temp.toFile().delete(); } private ClassLoader byteClassLoader() { return new ClassLoader() { @Override protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] b = classpath.get(name); if(b == null) throw new ClassNotFoundException(name); return defineClass(name, b, 0, b.length); } @Override protected Enumeration<URL> findResources(String name) throws IOException { Set<URL> matchingJars = new HashSet<>(); for (Map.Entry<String, File> classToJar : jarByClass.entrySet()) { if(classToJar.getKey().startsWith(name)) matchingJars.add(classToJar.getValue().toURI().toURL()); } return Collections.enumeration(matchingJars); } }; } private static String classNameFromSource(CharSequence source) { Matcher m = Pattern.compile("(class|interface)\\s+(\\w+)").matcher(source); return m.find() ? m.group(2) : null; } public <T> Class<T> loadClass(String className) { try { return (Class<T>) classLoader.loadClass(className); } catch(ClassNotFoundException e) { throw new IllegalStateException(e); } } @SuppressWarnings("unchecked") public <T> T newInstance(String className, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException { Class<T> clazz = (Class<T>) loadClass(className); nextConstructor: for (Constructor<?> constructor : clazz.getDeclaredConstructors()) { if(args.length != constructor.getParameterTypes().length) continue; int i = 0; for (Class type : constructor.getParameterTypes()) if(!type.isAssignableFrom(args[i++].getClass())) continue nextConstructor; constructor.setAccessible(true); try { return (T) constructor.newInstance(args); } catch (IllegalAccessException e) { throw new RuntimeException(e); // should never happen } } throw new IllegalArgumentException("No matching constructor for class " + className + " found for provided args"); } private static class InMemoryJavaFileObject extends SimpleJavaFileObject { private String contents = null; public InMemoryJavaFileObject(String contents) { super(URI.create("string:///" + classNameFromSource(contents) + ".java"), Kind.SOURCE); this.contents = contents; } public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return contents; } } private static DiagnosticListener<JavaFileObject> diagnosticListener = new DiagnosticListener<JavaFileObject>() { @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { System.out.println("ERROR compiling " + diagnostic.getSource().getName()); System.out.println("Line " + diagnostic.getLineNumber() + ": " + diagnostic.getMessage(Locale.ENGLISH)); } }; /** * Compiles all java sources and adds them to the rule's classpath * @param javaSources * @return the set of fully qualified class names compiled just in this invocation */ public Collection<String> compile(String... javaSources) { return compile(Arrays.asList(javaSources)); } /** * Compiles all java sources and adds them to the rule's classpath * @param javaSources * @return the set of fully qualified class names compiled just in this invocation */ public Collection<String> compile(Collection<String> javaSources) { Collection<InMemoryJavaFileObject> files = new ArrayList<>(); for (String javaSource : javaSources) files.add(new InMemoryJavaFileObject(javaSource)); return compileInternal(files); } private Collection<String> compileInternal(Collection<InMemoryJavaFileObject> files) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticListener, Locale.ENGLISH, null); try { JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnosticListener, Arrays.asList("-d", temp.toFile().getAbsolutePath(), "-cp", temp.toFile().getAbsolutePath(), "-g"), null, files); task.call(); Map<String, byte[]> classes = new HashMap<>(); for (Path p : recurseListFiles(temp)) { try { byte[] bytes = Files.readAllBytes(p); classes.put(fullyQualifiedName(bytes), bytes); } catch (IOException e) { throw new IllegalStateException(e); } } classpath.putAll(classes); Set<String> classNames = new HashSet<>(); classIter: for (String c : classes.keySet()) { String[] classNameParts = c.split("\\."); for (InMemoryJavaFileObject file : files) { if(classNameFromSource(file.contents).equals(classNameParts[classNameParts.length - 1])) { classNames.add(c); continue classIter; } } } return classNames; } catch (IOException e) { throw new RuntimeException(e); } } private List<Path> recurseListFiles(Path path) throws IOException { List<Path> files = new ArrayList<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { for (Path entry : stream) { if (Files.isDirectory(entry)) files.addAll(recurseListFiles(entry)); else files.add(entry); } } return files; } public String fullyQualifiedName(byte[] classBytes) { final StringBuffer className = new StringBuffer(); ClassReader cr = new ClassReader(classBytes); cr.accept(new ClassVisitor(Opcodes.ASM7) { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { className.append(name); } }, 0); return className.toString().replace("/", "."); } public File jar(File f, String... classSources) { f.getParentFile().mkdirs(); try { FileOutputStream fos = new FileOutputStream(f); JarOutputStream jos = new JarOutputStream(fos); for (String clazz : compile(classSources)) { jos.putNextEntry(new JarEntry(clazz.replace(".", "/") + ".class")); jos.write(classpath.get(clazz)); jarByClass.put(clazz.replace('.', '/'), f); } jos.close(); fos.close(); return f; } catch (IOException e) { throw new RuntimeException(e); } } public byte[] classBytes(String className) { return classpath.get(className); } public ClassLoader getClassLoader() { return classLoader; } }
5,680
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/LocalScoped.java
package com.netflix.governator.lifecycle; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.google.inject.ScopeAnnotation; @Target({ TYPE, METHOD }) @Retention(RetentionPolicy.RUNTIME) @ScopeAnnotation public @interface LocalScoped { }
5,681
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/PreDestroyStressTest.java
package com.netflix.governator.lifecycle; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Named; import org.apache.log4j.Level; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.name.Names; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.governator.guice.LifecycleInjectorMode; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; @RunWith(DataProviderRunner.class) public class PreDestroyStressTest { static final Key<LifecycleSubject> LIFECYCLE_SUBJECT_KEY = Key.get(LifecycleSubject.class); private static final int TEST_TIME_IN_SECONDS = 10; // run the stress test for this many seconds private static final int CONCURRENCY_LEVEL = 20; // run the stress test with this many threads private final class ScopingModule extends AbstractModule { LocalScope localScope = new LocalScope(); @Override protected void configure() { bindScope(LocalScoped.class, localScope); bind(LifecycleSubject.class).in(localScope); } @Provides @Singleton @Named("thing1") public LifecycleSubject thing1() { return new LifecycleSubject("thing1"); } } static class LifecycleSubject { private static AtomicInteger instanceCounter = new AtomicInteger(0); private static AtomicInteger preDestroyCounter = new AtomicInteger(0); private static AtomicInteger postConstructCounter = new AtomicInteger(0); private static Logger logger = LoggerFactory.getLogger(LifecycleSubject.class); private static byte[] bulkTemplate; static { bulkTemplate = new byte[1024*100]; Arrays.fill(bulkTemplate, (byte)0); } private String name; private volatile boolean postConstructed = false; private volatile boolean preDestroyed = false; private byte[] bulk; private final String toString; public LifecycleSubject() { this("anonymous"); } public LifecycleSubject(String name) { this.name = name; this.bulk = bulkTemplate.clone(); int instanceId = instanceCounter.incrementAndGet(); this.toString = "LifecycleSubject@" + instanceId + '[' + name + ']'; logger.info("created instance {} {}", toString, instanceId); } public static void clear() { instanceCounter.set(0); postConstructCounter.set(0); preDestroyCounter.set(0); } @PostConstruct public void init() { logger.info("@PostConstruct called {} {}", toString, postConstructCounter.incrementAndGet()); this.postConstructed = true; } @PreDestroy public void destroy() { logger.info("@PreDestroy called {} {}", toString, preDestroyCounter.incrementAndGet()); this.preDestroyed = true; } public boolean isPostConstructed() { return postConstructed; } public boolean isPreDestroyed() { return preDestroyed; } public String getName() { return name; } public String toString() { return toString; } } @Test @UseDataProvider("builders") public void testInParallel(String name, LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { LifecycleSubject.clear(); ScopingModule scopingModule = new ScopingModule(); final LocalScope localScope = scopingModule.localScope; LifecycleInjector lifecycleInjector = LifecycleInjector.builder() .withAdditionalModules(scopingModule).build(); SecureRandom random = new SecureRandom(); LifecycleSubject thing1 = null; try (com.netflix.governator.lifecycle.LifecycleManager legacyLifecycleManager = lifecycleInjector.getLifecycleManager()) { org.apache.log4j.Logger.getLogger("com.netflix.governator").setLevel(Level.WARN); final Injector injector = lifecycleInjector.createInjector(); legacyLifecycleManager.start(); thing1 = injector.getInstance(Key.get(LifecycleSubject.class, Names.named("thing1"))); Assert.assertEquals("singleton instance not postConstructed", LifecycleSubject.postConstructCounter.get(), LifecycleSubject.instanceCounter.get()); Assert.assertEquals("singleton instance predestroyed too soon", LifecycleSubject.preDestroyCounter.get(), LifecycleSubject.instanceCounter.get()-1); Callable<Void> scopingTask = allocateScopedInstance(injector, localScope, random); runInParallel(CONCURRENCY_LEVEL, scopingTask, TEST_TIME_IN_SECONDS, TimeUnit.SECONDS); System.gc(); Thread.sleep(1000); System.out.println("instances count: " + LifecycleSubject.instanceCounter.get()); System.out.flush(); Assert.assertEquals("instances not postConstructed", LifecycleSubject.postConstructCounter.get(), LifecycleSubject.instanceCounter.get()); Assert.assertEquals("scoped instances not predestroyed", LifecycleSubject.preDestroyCounter.get(), LifecycleSubject.instanceCounter.get()-1); Assert.assertFalse("singleton instance was predestroyed too soon", thing1.isPreDestroyed()); } finally { org.apache.log4j.Logger.getLogger("com.netflix.governator").setLevel(Level.DEBUG); } Assert.assertTrue("singleton instance was not predestroyed", thing1.isPreDestroyed()); Thread.yield(); } void runInParallel(int concurrency, final Callable<Void> task, int duration, TimeUnit timeUnits) throws InterruptedException { ExecutorService es = Executors.newFixedThreadPool(concurrency, new ThreadFactoryBuilder().setNameFormat("predestroy-stress-test-%d").build()); final AtomicBoolean running = new AtomicBoolean(true); try { List<Callable<Void>> tasks = new ArrayList<>(); for (int i=0; i < concurrency; i++) { tasks.add(new Callable<Void>() { @Override public Void call() { while (running.get()) { try { task.call(); } catch (Exception e) { e.printStackTrace(); } } return null; } }); } es.invokeAll(tasks, duration, timeUnits); } finally { running.set(false); es.shutdown(); es.awaitTermination(10, TimeUnit.SECONDS); } es = null; } Callable<Void> allocateScopedInstance(final Injector injector, final LocalScope localScope, final SecureRandom random) { return new Callable<Void>() { public Void call() throws InterruptedException { localScope.enter(); try { LifecycleSubject anonymous = injector.getInstance(LIFECYCLE_SUBJECT_KEY); Thread.sleep(random.nextInt(500)); Assert.assertTrue(anonymous.isPostConstructed()); Assert.assertFalse(anonymous.isPreDestroyed()); } catch(InterruptedException e) { } finally { localScope.exit(); } return null; } }; } @DataProvider public static Object[][] builders() { return new Object[][] { new Object[] { "simulatedChildInjector", LifecycleInjector.builder().withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) }, new Object[] { "childInjector", LifecycleInjector.builder() } }; } }
5,682
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/TestAnnotationFinder.java
package com.netflix.governator.lifecycle; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.is; import static org.objectweb.asm.ClassReader.SKIP_CODE; import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.objectweb.asm.ClassReader; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.TreeSet; public class TestAnnotationFinder { JavaClasspath cp; String a = "governator.test.A"; String b = "governator.test.B"; @Before public void before() { cp = new JavaClasspath(); cp.compile( "package governator.test;" + "public @interface A {}", "package governator.test;" + "public @interface B {}"); } @After public void after() { cp.cleanup(); } @Test public void testFindAnnotationsOnClasses() { cp.compile( "package governator.test;" + "@A public class Foo {}" ); assertThat(scan("governator.test.Foo", a).getAnnotatedClasses(), is(Matchers.<Class<?>>iterableWithSize(1))); assertThat(scan("governator.test.Foo", b).getAnnotatedClasses(), is(emptyIterable())); } @Test public void testFindAnnotationsOnFields() { cp.compile( "package governator.test;" + "public class Foo {" + " @A private String f1;" + " @A transient String f2;" + " @A static String f3;" + " @A static int f4;" + "}" ); AnnotationFinder finder = scan("governator.test.Foo", a); Set<String> matchingFields = new TreeSet<>(); for (Field field : finder.getAnnotatedFields()) matchingFields.add(field.getName()); assertThat(matchingFields, containsInAnyOrder("f1", "f2", "f3", "f4")); } @Test public void testFindAnnotationsOnMethods() { cp.compile( "package governator.test;" + "import java.util.Collection;" + "public class Foo {" + " @A private void m1() {}" + " @A void m2(String p) {}" + " @A void m3(String[] p) {}" + " @A void m4(Collection<String> p) {}" + " @A void m5(int p) {}" + "}" ); AnnotationFinder finder = scan("governator.test.Foo", a); Set<String> matchingMethods = new TreeSet<>(); for (Method method : finder.getAnnotatedMethods()) matchingMethods.add(method.getName()); assertThat(matchingMethods, containsInAnyOrder("m1", "m2", "m3", "m4", "m5")); } @Test public void testFindAnnotationsOnConstructors() { cp.compile( "package governator.test;" + "import java.util.Collection;" + "public class Foo {" + " @A private Foo() {}" + " @A Foo(String p) {}" + " @A Foo(String[] p) {}" + " @A Foo(Collection<String> p) {}" + " @A Foo(byte p) {}" + "}" ); assertThat(scan("governator.test.Foo", a).getAnnotatedConstructors(), is(Matchers.<Constructor>iterableWithSize(5))); } @Test public void testInnerClasses() { Collection<String> compile = cp.compile( "package governator.test;" + "public class Foo {" + " @A class Inner {}" + " @A static class StaticInner {}" + "}" ); assertThat(scan("governator.test.Foo$Inner", a).getAnnotatedClasses(), is(Matchers.<Class<?>>iterableWithSize(1))); assertThat(scan("governator.test.Foo$StaticInner", a).getAnnotatedClasses(), is(Matchers.<Class<?>>iterableWithSize(1))); } private AnnotationFinder scan(String clazz, String annotation) { Class<? extends Annotation> aClass = cp.loadClass(annotation); AnnotationFinder finder = new AnnotationFinder(cp.getClassLoader(), Collections.<Class<? extends Annotation>>singletonList(aClass)); new ClassReader(cp.classBytes(clazz)).accept(finder, SKIP_CODE); return finder; } }
5,683
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/TestInjectedLifecycleListener.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.TypeLiteral; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Collection; @RunWith(DataProviderRunner.class) public class TestInjectedLifecycleListener extends LifecycleInjectorBuilderProvider { public interface TestInterface { public String getValue(); } public static class MyListener extends DefaultLifecycleListener { private final TestInterface testInterface; @Inject public MyListener(TestInterface testInterface) { this.testInterface = testInterface; } public TestInterface getTestInterface() { return testInterface; } @Override public <T> void objectInjected(TypeLiteral<T> type, T obj) { } @Override public void stateChanged(Object obj, LifecycleState newState) { } } @Test @UseDataProvider("builders") public void testInjectedLifecycleListener(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { Injector injector = lifecycleInjectorBuilder .withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { TestInterface instance = new TestInterface() { @Override public String getValue() { return "a is a"; } }; binder.bind(TestInterface.class).toInstance(instance); binder.bindLifecycleListener().to(MyListener.class); } } ) .createInjector(); LifecycleManager manager = injector.getInstance(LifecycleManager.class); Collection<LifecycleListener> listeners = manager.getListeners(); Assert.assertEquals(listeners.size(), 1); Assert.assertTrue(listeners.iterator().next() instanceof MyListener); Assert.assertEquals(((MyListener)listeners.iterator().next()).getTestInterface().getValue(), "a is a"); } }
5,684
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/LifeCycleFeaturesOnLegacyBuilderTest.java
package com.netflix.governator.lifecycle; import static org.junit.Assert.assertNotNull; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Named; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.name.Names; import com.google.inject.util.Providers; import com.netflix.governator.LifecycleManager; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.governator.guice.LifecycleInjectorMode; import com.netflix.governator.spi.LifecycleListener; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; @RunWith(DataProviderRunner.class) public class LifeCycleFeaturesOnLegacyBuilderTest { static class LifecycleSubject { private Logger logger = LoggerFactory.getLogger(LifecycleSubject.class); private String name; private volatile boolean postConstructed = false; private volatile boolean preDestroyed = false; private static AtomicInteger instanceCounter = new AtomicInteger(0); public LifecycleSubject(String name) { this.name = name; instanceCounter.incrementAndGet(); logger.info("created instance " + this); } @PostConstruct public void init() { logger.info("@PostConstruct called " + this); this.postConstructed = true; } @PreDestroy public void destroy() { logger.info("@PreDestroy called " + this); this.preDestroyed = true; } public boolean isPostConstructed() { return postConstructed; } public boolean isPreDestroyed() { return preDestroyed; } public String getName() { return name; } public static int getInstanceCount() { return instanceCounter.get(); } public String toString() { return "LifecycleSubject@" + System.identityHashCode(this) + '[' + name + ']'; } } @Singleton static class UsesNullable { private AtomicBoolean preDestroyed = new AtomicBoolean(false); private LifecycleSubject subject; @Inject public void UsesNullable(@Nullable @Named("missing") LifecycleSubject subject) { this.subject = subject; } @PreDestroy public void destroy() { this.preDestroyed.set(true); } } static interface LifecycleInterface { @PostConstruct public default void init() { System.out.println("init() called"); } @PreDestroy public default void destroy() { System.out.println("destroy() called"); } } @Mock private TestListener listener; private Injector injector; private LocalScope localScope; private static class TestListener implements LifecycleListener { @PostConstruct public void init() { } @PreDestroy public void shutdown() { } public void onStopped(Throwable error) { } public void onStarted() { } } public com.netflix.governator.lifecycle.LifecycleManager init(LifecycleInjectorBuilder builder) throws Exception { LifecycleSubject.instanceCounter.set(0); localScope = new LocalScope(); listener = Mockito.mock(TestListener.class); LifecycleInjector lifecycleInjector = builder .withAdditionalModules(new AbstractModule() { @Override protected void configure() { bind(TestListener.class).toInstance(listener); bindScope(LocalScoped.class, localScope); bind(UsesNullable.class); bind(Key.get(LifecycleSubject.class, Names.named("missing"))).toProvider(Providers.of((LifecycleSubject)null)); } @Provides @LocalScoped @Named("thing1") public LifecycleSubject thing1() { return new LifecycleSubject("thing1"); } @Provides @Singleton @Named("thing2") public LifecycleSubject thing2() { return new LifecycleSubject("thing2"); } }) .requiringExplicitBindings() .build(); injector = lifecycleInjector.createInjector(); com.netflix.governator.lifecycle.LifecycleManager lifecycleManager = lifecycleInjector.getLifecycleManager(); lifecycleManager.start(); return lifecycleManager; } @UseDataProvider("builders") @Test public void testPostActionsAndLifecycleListenersInvoked(LifecycleInjectorBuilder builder) throws Exception { try (com.netflix.governator.lifecycle.LifecycleManager lm = init(builder)) { assertNotNull(injector); assertNotNull(injector.getInstance(LifecycleManager.class)); Mockito.verify(listener, Mockito.times(1)).onStarted(); Mockito.verify(listener, Mockito.times(1)).init(); Mockito.verify(listener, Mockito.times(0)).onStopped(Mockito.any(Throwable.class)); Mockito.verify(listener, Mockito.times(0)).shutdown(); } Mockito.verify(listener, Mockito.times(1)).onStopped(Mockito.any(Throwable.class)); Mockito.verify(listener, Mockito.times(1)).onStopped(Mockito.any(Throwable.class)); } @UseDataProvider("builders") @Test public void testScopeManagement(LifecycleInjectorBuilder builder) throws Exception { LifecycleSubject thing2 = null; try (com.netflix.governator.lifecycle.LifecycleManager lm = init(builder)) { thing2 = injector.getInstance(Key.get(LifecycleSubject.class, Names.named("thing2"))); localScope.enter(); injector.getInstance(Key.get(LifecycleSubject.class, Names.named("thing1"))); LifecycleSubject thing1 = injector.getInstance(Key.get(LifecycleSubject.class, Names.named("thing1"))); Assert.assertTrue(thing1.isPostConstructed()); Assert.assertFalse(thing1.isPreDestroyed()); Assert.assertTrue(thing2.isPostConstructed()); Assert.assertFalse(thing2.isPreDestroyed()); Assert.assertEquals(2, LifecycleSubject.getInstanceCount()); // thing1 and // thing2 Assert.assertFalse(thing2.isPreDestroyed()); localScope.exit(); System.gc(); Thread.sleep(500); Assert.assertTrue(thing1.isPreDestroyed()); } System.gc(); Thread.sleep(500); Assert.assertTrue(thing2.isPreDestroyed()); } @UseDataProvider("builders") @Test public void testSingletonScopeManagement(LifecycleInjectorBuilder builder) throws Exception { LifecycleSubject thing2 = null; try (com.netflix.governator.lifecycle.LifecycleManager lm = init(builder)) { thing2 = injector.getInstance(Key.get(LifecycleSubject.class, Names.named("thing2"))); Assert.assertTrue(thing2.isPostConstructed()); Assert.assertFalse(thing2.isPreDestroyed()); injector.getInstance(Key.get(LifecycleSubject.class, Names.named("thing2"))); injector.getInstance(Key.get(LifecycleSubject.class, Names.named("thing2"))); injector.getInstance(Key.get(LifecycleSubject.class, Names.named("thing2"))); Assert.assertEquals(1, LifecycleSubject.getInstanceCount()); } System.gc(); Thread.sleep(500); Assert.assertTrue(thing2.isPreDestroyed()); } @UseDataProvider("builders") @Test public void testNullableInjection(LifecycleInjectorBuilder builder) throws Exception { AtomicBoolean nullableConsumerDestroyed = null; try (com.netflix.governator.lifecycle.LifecycleManager lm = init(builder)) { UsesNullable nullableConsumer = injector.getInstance(UsesNullable.class); nullableConsumerDestroyed = nullableConsumer.preDestroyed; Assert.assertNull(nullableConsumer.subject); } System.gc(); Thread.sleep(500); Assert.assertTrue(nullableConsumerDestroyed.get()); } @Test public void testLifecycleMethods() throws Exception { LifecycleInterface instance = new LifecycleInterface() {}; Class<?> defaultMethodsClass = instance.getClass(); LifecycleMethods methods = new LifecycleMethods(defaultMethodsClass); methods.methodInvoke(defaultMethodsClass.getMethod("init", (Class[])null), instance); methods.methodInvoke(defaultMethodsClass.getMethod("destroy", (Class[])null), instance); } @DataProvider public static Object[][] builders() { return new Object[][] { new Object[] { "simulatedChildInjector", LifecycleInjector.builder().withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) }, new Object[] { "childInjector", LifecycleInjector.builder() }, new Object[] { "simulatedChildInjectorExplicitBindings", LifecycleInjector.builder().withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS).requiringExplicitBindings() }, new Object[] { "childInjectorExplicitBindings", LifecycleInjector.builder().requiringExplicitBindings() } }; } }
5,685
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/LocalScope.java
package com.netflix.governator.lifecycle; import static com.google.common.base.Preconditions.checkState; import java.util.Map; import com.google.common.collect.Maps; import com.google.inject.Key; import com.google.inject.OutOfScopeException; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.Scopes; public class LocalScope implements Scope { final ThreadLocal<Map<Key<?>, Object>> content = new ThreadLocal<Map<Key<?>, Object>>(); public void enter() { checkState(content.get() == null, "LocalScope already exists in thread %s", Thread.currentThread()); content.set(Maps.<Key<?>, Object> newHashMap()); } public void exit() { Map<Key<?>, Object> scopeContents = content.get(); checkState(scopeContents != null, "No LocalScope found in thread %s", Thread.currentThread()); scopeContents.clear(); content.remove(); } public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) { return new Provider<T>() { public T get() { Map<Key<?>, Object> scopedObjects = content.get(); if (scopedObjects == null) { throw new OutOfScopeException("No LocalScope found in thread " + Thread.currentThread()); } @SuppressWarnings("unchecked") T current = (T) scopedObjects.get(key); if (current == null) { current = unscoped.get(); // don't remember proxies; these exist only to serve // circular dependencies if (Scopes.isCircularProxy(current)) { return current; } scopedObjects.put(key, current); } return current; } }; } }
5,686
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/TestLifecycleManager.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import org.junit.Assert; import org.junit.Test; @SuppressWarnings("UnusedDeclaration") public class TestLifecycleManager { @Test public void testValidation() throws Exception { Object goodObj = new Object() { private int a = 10; }; Object badObj = new Object() { private int a = 0; }; LifecycleManager manager = new LifecycleManager(); manager.add(goodObj); manager.start(); manager = new LifecycleManager(); manager.add(badObj); try { manager.start(); } catch ( ValidationException e ) { Assert.fail(); //should no longer throw a validation exception as this feature was removed in 1.17.0 } } }
5,687
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/CircularDAG.java
package com.netflix.governator.lifecycle; import com.google.inject.Injector; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.annotations.WarmUp; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; /** * There is a infinite recursion in InternalLifecycleModule.warmUpIsInDag(InternalLifecycleModule.java:150) * and InternalLifecycleModule.warmUpIsInDag(InternalLifecycleModule.java:171) that will ultimately lead to * an StackOverflowError. */ @RunWith(DataProviderRunner.class) public class CircularDAG extends LifecycleInjectorBuilderProvider { @Singleton public static class A { @Inject private B b; } @Singleton public static class B { @Inject private A a; } @Singleton public static class Service { private final Logger log = LoggerFactory.getLogger(getClass()); @Inject private A a; @WarmUp public void connect() { log.info("connect"); } @PreDestroy public void disconnect() { log.info("disconnect"); } } @Test @UseDataProvider("builders") public void circle(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { Injector injector = lifecycleInjectorBuilder.createInjector(); injector.getInstance(Service.class); LifecycleManager manager = injector.getInstance(LifecycleManager.class); manager.start(); } }
5,688
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/mocks/SubclassedObjectWithConfig.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.mocks; import com.netflix.governator.annotations.Configuration; public class SubclassedObjectWithConfig extends ObjectWithConfig { @Configuration(value = "test.main", documentation = "This is the mainInt") public int mainInt; }
5,689
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/mocks/ObjectWithConfigVariable.java
package com.netflix.governator.lifecycle.mocks; import com.netflix.governator.annotations.Configuration; import com.netflix.governator.annotations.ConfigurationVariable; import java.util.Arrays; import java.util.Date; import java.util.List; public class ObjectWithConfigVariable { @ConfigurationVariable(name="name") private final String name; @Configuration(value = "${name}.b", documentation = "this is a boolean") public boolean aBool = false; @Configuration("${name}.i") public int anInt = 1; @Configuration("${name}.l") public long aLong = 2; @Configuration("${name}.d") public double aDouble = 3.4; @Configuration("${name}.s") public String aString = "test"; @Configuration("${name}.dt") public Date aDate = null; @Configuration(value = "${name}.obj") public List<Integer> ints = Arrays.asList(5, 6, 7); public ObjectWithConfigVariable(String name) { this.name = name; } }
5,690
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/mocks/ObjectWithConfig.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.mocks; import com.netflix.governator.annotations.Configuration; import java.util.*; public class ObjectWithConfig { @Configuration(value = "test.b", documentation = "this is a boolean") public boolean aBool = false; @Configuration("test.i") public int anInt = 1; @Configuration("test.l") public long aLong = 2; @Configuration("test.d") public double aDouble = 3.4; @Configuration("test.s") public String aString = "test"; @Configuration("test.dt") public Date aDate = null; @Configuration(value = "test.obj") public List<Integer> ints = Arrays.asList(5,6,7); @Configuration(value = "test.mapOfMaps") public Map<String, Map<String, String>> mapOfMaps = new HashMap<String, Map<String, String>>(); }
5,691
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/mocks/PreConfigurationChange.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.mocks; import com.netflix.governator.annotations.Configuration; import com.netflix.governator.annotations.PreConfiguration; import com.netflix.governator.configuration.CompositeConfigurationProvider; import com.netflix.governator.configuration.PropertiesConfigurationProvider; import org.junit.Assert; import javax.annotation.PostConstruct; import javax.inject.Inject; import java.util.Properties; public class PreConfigurationChange { private final CompositeConfigurationProvider configurationProvider; @Configuration("pre-config-test") private String value = "default"; @Inject public PreConfigurationChange(CompositeConfigurationProvider configurationProvider) { this.configurationProvider = configurationProvider; } @PreConfiguration public void preConfiguration() { Assert.assertEquals(value, "default"); Properties override = new Properties(); override.setProperty("pre-config-test", "override"); configurationProvider.add(new PropertiesConfigurationProvider(override)); } @PostConstruct public void postConstruct() { Assert.assertEquals(value, "override"); } }
5,692
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/mocks/SimpleObject.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.mocks; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.concurrent.atomic.AtomicInteger; public class SimpleObject { public final AtomicInteger startCount = new AtomicInteger(0); public final AtomicInteger finishCount = new AtomicInteger(0); @PostConstruct public void start() throws InterruptedException { startCount.incrementAndGet(); } @PreDestroy public void finish() throws InterruptedException { finishCount.incrementAndGet(); } }
5,693
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/mocks/SimpleContainer.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.mocks; import com.netflix.governator.lifecycle.LifecycleManager; import com.netflix.governator.lifecycle.LifecycleState; import org.junit.Assert; public class SimpleContainer extends SimpleObject { public final SimpleObject simpleObject; public SimpleContainer(LifecycleManager manager, SimpleObject simpleObject) { Assert.assertEquals(manager.getState(simpleObject), LifecycleState.ACTIVE); this.simpleObject = simpleObject; } }
5,694
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/mocks/ObjectWithDynamicConfig.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.mocks; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.netflix.governator.annotations.Configuration; import com.netflix.governator.configuration.Property; import java.util.*; public class ObjectWithDynamicConfig { @Configuration(value = "test.dynamic.b", documentation = "this is a boolean") public Supplier<Boolean> aDynamicBool = Suppliers.ofInstance(true); @Configuration(value = "test.dynamic.i") public Supplier<Integer> anDynamicInt = Suppliers.ofInstance(1); @Configuration(value = "test.dynamic.i") public Property<Integer> anDynamicInt2 = Property.from(1); @Configuration(value = "test.dynamic.l") public Supplier<Long> aDynamicLong = Suppliers.ofInstance(2L); @Configuration(value = "test.dynamic.d") public Supplier<Double> aDynamicDouble = Suppliers.ofInstance(3.4); @Configuration(value = "test.dynamic.s") public Supplier<String> aDynamicString = Suppliers.ofInstance("a is a"); @Configuration(value = "test.dynamic.s") public Property<String> aDynamicString2 = Property.from("a is a"); @Configuration(value = "test.dynamic.dt") public Supplier<Date> aDynamicDate = Suppliers.ofInstance(null); @Configuration(value = "test.dynamic.obj") public Supplier<List<Integer>> aDynamicObj = Suppliers.ofInstance(Arrays.asList(5, 6, 7)); @Configuration(value = "test.dynamic.mapOfMaps") public Supplier<Map<String, Map<String, String>>> aDynamicMapOfMaps = Suppliers.ofInstance(Collections.<String, Map<String, String>>emptyMap()); }
5,695
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/mocks/ObjectWithIgnoreTypeMismatchConfig.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.mocks; import com.netflix.governator.annotations.Configuration; import java.util.Date; public class ObjectWithIgnoreTypeMismatchConfig { @Configuration(value = "test.b", documentation = "this is a boolean", ignoreTypeMismatch = true) public boolean aBool = false; @Configuration(value = "test.i", ignoreTypeMismatch = true) public int anInt = 1; @Configuration(value = "test.l", ignoreTypeMismatch = true) public long aLong = 2; @Configuration(value = "test.d", ignoreTypeMismatch = true) public double aDouble = 3.4; @Configuration(value = "test.dt", ignoreTypeMismatch = true) public Date aDate = new Date(); }
5,696
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/resources/Jsr250SupportTest.java
package com.netflix.governator.lifecycle.resources; import com.google.inject.Injector; import com.google.inject.Scopes; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.governator.lifecycle.LifecycleManager; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Alexey Krylov (lexx) * @since 19.02.13 */ @RunWith(DataProviderRunner.class) public class Jsr250SupportTest extends LifecycleInjectorBuilderProvider { @Test @UseDataProvider("builders") public void testJsr250EnabledService(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { Injector injector = lifecycleInjectorBuilder.createInjector(); Jsr250EnabledService jsr250EnabledService = injector.getInstance(Jsr250EnabledService.class); injector.getInstance(LifecycleManager.class).start(); Assert.assertTrue(Scopes.isSingleton(injector.getBinding(jsr250EnabledService.getClass()))); Assert.assertTrue(jsr250EnabledService.isPostConstuctInvoked()); Assert.assertTrue(jsr250EnabledService.isResourceSet()); Jsr250EnabledService service = injector.getInstance(Jsr250EnabledService.class); Assert.assertEquals(jsr250EnabledService.getResource(), service.getResource()); injector.getInstance(LifecycleManager.class).close(); Assert.assertTrue(jsr250EnabledService.isPreDestroyInvoked()); } }
5,697
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/resources/TestResources.java
package com.netflix.governator.lifecycle.resources; import com.google.inject.Injector; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.governator.lifecycle.ResourceLocator; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.awt.Point; import java.awt.Rectangle; import java.math.BigInteger; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Resource; @RunWith(DataProviderRunner.class) public class TestResources extends LifecycleInjectorBuilderProvider { @Test @UseDataProvider("builders") public void basicTest(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { final AtomicInteger classResourceCount = new AtomicInteger(0); final ResourceLocator resourceLocator = new ResourceLocator() { @Override public Object locate(Resource resource, ResourceLocator nextInChain) throws Exception { if ( resource.name().equals(ObjectWithResources.class.getName() + "/myResource") ) { return "a"; } if ( resource.name().equals("overrideInt") ) { return BigInteger.valueOf(2); } if ( resource.name().equals(ObjectWithResources.class.getName() + "/p") ) { return new Point(3, 4); } if ( resource.name().equals("overrideRect") ) { return new Rectangle(5, 6); } if ( resource.name().equals("classResource") ) { classResourceCount.incrementAndGet(); return 7.8; } return null; } }; Injector injector = lifecycleInjectorBuilder.withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bindResourceLocator().toInstance(resourceLocator); } } ) .createInjector(); ObjectWithResources obj = injector.getInstance(ObjectWithResources.class); Assert.assertEquals(obj.getMyResource(), "a"); Assert.assertEquals(obj.getMyOverrideResource(), BigInteger.valueOf(2)); Assert.assertEquals(obj.getP(), new Point(3, 4)); Assert.assertEquals(obj.getR(), new Rectangle(5, 6)); Assert.assertEquals(classResourceCount.get(), 1); } @Test @UseDataProvider("builders") public void testChained(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { final AtomicInteger resourceLocator1Count = new AtomicInteger(0); final AtomicInteger resourceLocator2Count = new AtomicInteger(0); final ResourceLocator resourceLocator1 = new ResourceLocator() { @Override public Object locate(Resource resource, ResourceLocator nextInChain) throws Exception { resourceLocator1Count.incrementAndGet(); return nextInChain.locate(resource, nextInChain); } }; final ResourceLocator resourceLocator2 = new ResourceLocator() { @Override public Object locate(Resource resource, ResourceLocator nextInChain) throws Exception { resourceLocator2Count.incrementAndGet(); return nextInChain.locate(resource, nextInChain); } }; Injector injector = lifecycleInjectorBuilder.withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bindResourceLocator().toInstance(resourceLocator1); binder.bindResourceLocator().toInstance(resourceLocator2); binder.bind(BigInteger.class).toInstance(BigInteger.valueOf(1)); binder.bind(Double.class).toInstance(1.1); } } ) .createInjector(); injector.getInstance(ObjectWithResources.class); Assert.assertEquals(resourceLocator1Count.get(), 5); // 1 for each @Resource Assert.assertEquals(resourceLocator2Count.get(), 5); // " " } }
5,698
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/resources/Jsr250Resource.java
package com.netflix.governator.lifecycle.resources; import com.google.inject.Singleton; @Singleton public class Jsr250Resource { }
5,699