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-core/src/test/java/com/netflix
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/TestSupport.java
package com.netflix.governator; import java.util.ArrayList; import java.util.Arrays; import java.util.IdentityHashMap; import java.util.List; import com.google.inject.AbstractModule; import com.google.inject.Module; import com.google.inject.Stage; public class TestSupport { private static final class InstancesModule extends AbstractModule { final List<Object> instances; public InstancesModule(Object... instances) { this.instances = new ArrayList<>(Arrays.asList(instances)); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected void configure() { for (Object o : instances) { Class clz = (Class) o.getClass(); bind(clz).toInstance(o); } } } private InstancesModule module = new InstancesModule(); private IdentityHashMap<GovernatorFeature<?>, Object> features = new IdentityHashMap<>(); public static Module asModule(final Object o) { return asModule(o); } public static Module asModule(final Object... instances) { return new InstancesModule(instances); } public static LifecycleInjector inject(final Object... instances) { return InjectorBuilder.fromModule(new InstancesModule(instances)).createInjector(); } public <T> TestSupport withFeature(GovernatorFeature<T> feature, T value) { this.features.put(feature, value); return this; } public TestSupport withSingleton(final Object... instances) { module.instances.addAll(Arrays.asList(instances)); return this; } public LifecycleInjector inject() { return new LifecycleInjectorCreator().withFeatures(features).createInjector(Stage.PRODUCTION, module); } }
5,500
0
Create_ds/governator/governator-core/src/test/java/com/netflix
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/PostConstructTest.java
package com.netflix.governator; import javax.annotation.PostConstruct; import javax.inject.Singleton; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.mockito.InOrder; import org.mockito.Mockito; import com.google.inject.AbstractModule; import com.google.inject.Provides; import junit.framework.Assert; public class PostConstructTest { private static class SimplePostConstruct { @PostConstruct public void init() { } } private static class InvalidPostConstructs { @PostConstruct public String initWithReturnValue() { return "invalid return type"; } @PostConstruct public static void initStatic() { // can't use static method type throw new RuntimeException("boom"); } @PostConstruct public void initWithParameters(String invalidArg) { // can't use method parameters } } private static class PostConstructParent1 { @PostConstruct public void init() { System.out.println("parent.init"); } } private static class PostConstructChild1 extends PostConstructParent1 { @PostConstruct public void init() { System.out.println("child.init"); } } private static class PostConstructParent2 { @PostConstruct public void anotherInit() { System.out.println("parent.anotherInit"); } } private static class PostConstructChild2 extends PostConstructParent2 { @PostConstruct public void init() { System.out.println("child.init"); } } private static class PostConstructParent3 { @PostConstruct public void init() { } } static class PostConstructChild3 extends PostConstructParent3 { public void init() { System.out.println("init invoked"); } } static class MultiplePostConstructs { @PostConstruct public void init1() { System.out.println("init1"); } @PostConstruct public void init2() { System.out.println("init2"); } } @Test public void testLifecycleInitInheritance1() { final PostConstructChild1 postConstructChild = Mockito.mock(PostConstructChild1.class); InOrder inOrder = Mockito.inOrder(postConstructChild); try (LifecycleInjector injector = TestSupport.inject(postConstructChild)) { Assert.assertNotNull(injector.getInstance(postConstructChild.getClass())); // not twice inOrder.verify(postConstructChild, Mockito.times(1)).init(); } } @Test public void testLifecycleInitInheritance2() { final PostConstructChild2 postConstructChild = Mockito.mock(PostConstructChild2.class); InOrder inOrder = Mockito.inOrder(postConstructChild); try (LifecycleInjector injector = TestSupport.inject(postConstructChild)) { Assert.assertNotNull(injector.getInstance(postConstructChild.getClass())); // parent postConstruct before child postConstruct inOrder.verify(postConstructChild, Mockito.times(1)).anotherInit(); // not twice inOrder.verify(postConstructChild, Mockito.times(1)).init(); } } @Test public void testLifecycleShutdownInheritance3() { final PostConstructChild3 postConstructChild = Mockito.spy(new PostConstructChild3()); InOrder inOrder = Mockito.inOrder(postConstructChild); try (LifecycleInjector injector = TestSupport.inject(postConstructChild)) { Assert.assertNotNull(injector.getInstance(postConstructChild.getClass())); Mockito.verify(postConstructChild, Mockito.never()).init(); } // never, child class overrides method without annotation inOrder.verify(postConstructChild, Mockito.never()).init(); } @Test public void testLifecycleMultipleAnnotations() { final MultiplePostConstructs multiplePostConstructs = Mockito.spy(new MultiplePostConstructs()); try (LifecycleInjector injector = new TestSupport() .withFeature(GovernatorFeatures.STRICT_JSR250_VALIDATION, true) .withSingleton(multiplePostConstructs) .inject()) { Assert.assertNotNull(injector.getInstance(multiplePostConstructs.getClass())); Mockito.verify(multiplePostConstructs, Mockito.never()).init1(); Mockito.verify(multiplePostConstructs, Mockito.never()).init2(); } // never, multiple annotations should be ignored Mockito.verify(multiplePostConstructs, Mockito.never()).init1(); Mockito.verify(multiplePostConstructs, Mockito.never()).init2(); } @Test public void testLifecycleInitWithInvalidPostConstructs() { InvalidPostConstructs mockInstance = Mockito.mock(InvalidPostConstructs.class); try (LifecycleInjector injector = new TestSupport() .withFeature(GovernatorFeatures.STRICT_JSR250_VALIDATION, true) .withSingleton(mockInstance) .inject()) { Assert.assertNotNull(injector.getInstance(InvalidPostConstructs.class)); Mockito.verify(mockInstance, Mockito.never()).initWithParameters(Mockito.anyString()); Mockito.verify(mockInstance, Mockito.never()).initWithReturnValue(); } } @Test public void testLifecycleInitWithPostConstructException() { InvalidPostConstructs mockInstance = Mockito.mock(InvalidPostConstructs.class); try (LifecycleInjector injector = new TestSupport() .withFeature(GovernatorFeatures.STRICT_JSR250_VALIDATION, true) .withSingleton(mockInstance) .inject()) { Assert.assertNotNull(injector.getInstance(InvalidPostConstructs.class)); Mockito.verify(mockInstance, Mockito.never()).initWithParameters(Mockito.anyString()); Mockito.verify(mockInstance, Mockito.never()).initWithReturnValue(); } } @Test public void testLifecycleInit() { SimplePostConstruct mockInstance = Mockito.mock(SimplePostConstruct.class); try (LifecycleInjector injector = TestSupport.inject(mockInstance)) { Assert.assertNotNull(injector.getInstance(SimplePostConstruct.class)); Mockito.verify(mockInstance, Mockito.times(1)).init(); } } @Test public void testLifecycleInitWithAtProvides() { final SimplePostConstruct simplePostConstruct = Mockito.mock(SimplePostConstruct.class); InjectorBuilder builder = InjectorBuilder.fromModule(new AbstractModule() { @Override protected void configure() { } @Provides @Singleton SimplePostConstruct getSimplePostConstruct() { return simplePostConstruct; } }); try (LifecycleInjector injector = builder.createInjector()) { Mockito.verify(injector.getInstance(SimplePostConstruct.class), Mockito.times(1)).init(); } } @Before public void printTestHeader() { System.out.println("\n======================================================="); System.out.println(" Running Test : " + name.getMethodName()); System.out.println("=======================================================\n"); } @Rule public TestName name = new TestName(); }
5,501
0
Create_ds/governator/governator-core/src/test/java/com/netflix
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/LifecycleModuleTest.java
package com.netflix.governator; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Provider; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.CreationException; import com.google.inject.Injector; import com.google.inject.Scopes; import com.netflix.governator.spi.LifecycleListener; public class LifecycleModuleTest { private static final Logger logger = LoggerFactory.getLogger(LifecycleModuleTest.class); static class TestRuntimeException extends RuntimeException { private static final long serialVersionUID = 1L; public TestRuntimeException() { super(); } public TestRuntimeException(String message) { super(message); } } private static enum Events { Injected, Initialized, Destroyed, Started, Stopped, Error } @Rule public final TestName name = new TestName(); static class TrackingLifecycleListener implements LifecycleListener { final List<Events> events = new ArrayList<>(); private String name; public TrackingLifecycleListener(String name) { this.name = name; } @Inject public void injected(Injector injector) { events.add(Events.Injected); } @PostConstruct public void initialized() { events.add(Events.Initialized); } @Override public void onStarted() { events.add(Events.Started); } @Override public void onStopped(Throwable t) { events.add(Events.Stopped); if (t != null) { events.add(Events.Error); } } @PreDestroy public void destroyed() { events.add(Events.Destroyed); } @Override public String toString() { return "TrackingLifecycleListener@" + name; } } @Test public void confirmLifecycleListenerEventsForSuccessfulStart() { final TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()); TestSupport.inject(listener).close(); assertThat(listener.events, equalTo( Arrays.asList(Events.Injected, Events.Initialized, Events.Started, Events.Stopped, Events.Destroyed))); } @Test public void confirmLifecycleListenerEventsForRTExceptionInjected() { final TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @Override @Inject public void injected(Injector injector) { super.injected(injector); throw new TestRuntimeException("injected failed"); } }; try (LifecycleInjector injector = TestSupport.inject(listener)) { fail("expected exception injecting instance"); } catch (CreationException e) { // expected } catch (Exception e) { fail("expected CreationException injecting instance but got " + e); } finally { assertThat(listener.events, equalTo(Arrays.asList(Events.Injected))); } } @Test public void confirmLifecycleListenerEventsForRTExceptionPostConstruct() { final TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @Override @PostConstruct public void initialized() { super.initialized(); throw new TestRuntimeException("postconstruct rt exception"); } }; try (LifecycleInjector injector = TestSupport.inject(listener)) { fail("expected rt exception starting injector"); } catch (CreationException e) { // expected } catch (Exception e) { fail("expected CreationException starting injector but got " + e); } finally { assertThat(listener.events, equalTo(Arrays.asList(Events.Injected, Events.Initialized, Events.Stopped, Events.Error))); } } @Test public void confirmLifecycleListenerEventsForRTExceptionOnStarted() { final TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @Override public void onStarted() { super.onStarted(); throw new TestRuntimeException("onStarted rt exception"); } }; try (LifecycleInjector injector = TestSupport.inject(listener)) { fail("expected rt exception starting injector"); } catch (TestRuntimeException e) { // expected } catch (Exception e) { fail("expected TestRuntimeException starting injector but got " + e); } finally { assertThat(listener.events, equalTo(Arrays.asList(Events.Injected, Events.Initialized, Events.Started, Events.Stopped, Events.Error, Events.Destroyed))); } } @Test public void confirmLifecycleListenerEventsForRTExceptionOnStopped() { final TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @Override public void onStopped(Throwable t) { super.onStopped(t); throw new TestRuntimeException("onStopped rt exception"); } }; try (LifecycleInjector injector = TestSupport.inject(listener)) { } finally { assertThat(listener.events, equalTo(Arrays.asList(Events.Injected, Events.Initialized, Events.Started, Events.Stopped, Events.Destroyed))); } } @Test public void confirmLifecycleListenerEventsForRTExceptionPreDestroy() { final TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @PreDestroy @Override public void destroyed() { super.destroyed(); throw new TestRuntimeException("destroyed rt exception"); } }; try (LifecycleInjector injector = TestSupport.inject(listener)) { } finally { assertThat(listener.events, equalTo(Arrays.asList(Events.Injected, Events.Initialized, Events.Started, Events.Stopped, Events.Destroyed))); } } @Test(expected=AssertionError.class) public void assertionErrorInInject() { TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @Inject @Override public void injected(Injector injector) { super.injected(injector); fail("injected exception"); } }; try (LifecycleInjector injector = TestSupport.inject(listener)) { fail("expected error provisioning injector"); } catch (Exception e) { fail("expected AssertionError provisioning injector but got " + e); } finally { assertThat(listener.events, equalTo( Arrays.asList(Events.Injected, Events.Initialized, Events.Stopped, Events.Error))); } } @Test(expected=AssertionError.class) public void assertionErrorInPostConstruct() { TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @PostConstruct @Override public void initialized() { super.initialized(); fail("postconstruct exception"); } }; try (LifecycleInjector injector = TestSupport.inject(listener)) { fail("expected error creating injector"); } catch (Exception e) { fail("expected AssertionError destroying injector but got " + e); } finally { assertThat(listener.events, equalTo( Arrays.asList(Events.Injected, Events.Initialized, Events.Stopped, Events.Error))); } } @Test(expected=AssertionError.class) public void assertionErrorInOnStarted() { TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @Override public void onStarted() { super.onStarted(); fail("onStarted exception"); } }; try (LifecycleInjector injector = TestSupport.inject(listener)) { fail("expected AssertionError starting injector"); } catch (Exception e) { fail("expected AssertionError starting injector but got " + e); } finally { assertThat(listener.events, equalTo( Arrays.asList(Events.Injected, Events.Initialized, Events.Started, Events.Stopped, Events.Error))); } } @Test(expected=AssertionError.class) public void assertionErrorInOnStopped() { TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @Override public void onStopped(Throwable t) { super.onStopped(t); fail("onstopped exception"); } }; try (LifecycleInjector injector = TestSupport.inject(listener)) { fail("expected AssertionError stopping injector"); } catch (Exception e) { fail("expected AssertionError stopping injector but got " + e); } finally { assertThat(listener.events, equalTo( Arrays.asList(Events.Injected, Events.Initialized, Events.Stopped, Events.Error))); } } @Test(expected=AssertionError.class) public void assertionErrorInPreDestroy() { TrackingLifecycleListener listener = new TrackingLifecycleListener(name.getMethodName()) { @PreDestroy @Override public void destroyed() { super.destroyed(); fail("expected exception from predestroy"); } }; try { TestSupport.inject(listener).close(); } catch (Exception e) { e.printStackTrace(); fail("expected no exceptions for failed destroy method but got " + e); } finally { assertThat(listener.events, equalTo( Arrays.asList(Events.Injected, Events.Initialized, Events.Started, Events.Stopped, Events.Destroyed))); } } public static class Listener1 implements LifecycleListener { boolean wasStarted; boolean wasStopped; @Inject Provider<Listener2> nestedListener; @Override public void onStarted() { logger.info("starting listener1"); wasStarted = true; nestedListener.get(); } @Override public void onStopped(Throwable error) { logger.info("stopped listener1"); wasStopped = true; Assert.assertTrue(nestedListener.get().wasStopped); } } public static class Listener2 implements LifecycleListener { boolean wasStarted; boolean wasStopped; @Override public void onStarted() { logger.info("starting listener2"); wasStarted = true; } @Override public void onStopped(Throwable error) { logger.info("stopped listener2"); wasStopped = true; } } @Test public void testNestedLifecycleListeners() { Listener1 listener1; Listener2 listener2; try (LifecycleInjector injector = InjectorBuilder.fromModule(new AbstractModule() { @Override protected void configure() { bind(Listener1.class).asEagerSingleton(); bind(Listener2.class).in(Scopes.SINGLETON); } }).createInjector()) { listener1 = injector.getInstance(Listener1.class); listener2 = listener1.nestedListener.get(); Assert.assertNotNull(listener2); Assert.assertTrue(listener1.wasStarted); Assert.assertTrue(listener2.wasStarted); } Assert.assertTrue(listener1.wasStopped); Assert.assertTrue(listener2.wasStopped); } }
5,502
0
Create_ds/governator/governator-core/src/test/java/com/netflix
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/PreDestroyTest.java
package com.netflix.governator; import java.io.Closeable; import java.io.IOException; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.mockito.InOrder; import org.mockito.Mockito; import com.google.inject.AbstractModule; import com.google.inject.Key; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.name.Named; import com.google.inject.name.Names; public class PreDestroyTest { private static final int GC_SLEEP_TIME = 100; private static class Foo { private volatile boolean shutdown = false; Foo() { System.out.println("Foo constructed: " + this); } @PreDestroy protected void shutdown() { shutdown = true; } public boolean isShutdown() { return shutdown; } @Override public String toString() { return "Foo@" + System.identityHashCode(this); } } @ThreadLocalScoped private static class AnnotatedFoo { private volatile boolean shutdown = false; @SuppressWarnings("unused") AnnotatedFoo() { System.out.println("AnnotatedFoo constructed: " + this); } @PreDestroy public void shutdown() { this.shutdown = true; } public boolean isShutdown() { return shutdown; } @Override public String toString() { return "AnnotatedFoo@" + System.identityHashCode(this); } } private static class InvalidPreDestroys { @PreDestroy public String shutdownWithReturnValue() { return "invalid return type"; } @PreDestroy public static void shutdownStatic() { // can't use static method type throw new RuntimeException("boom"); } @PreDestroy public void shutdownWithParameters(String invalidArg) { // can't use method parameters } } private interface PreDestroyInterface { @PreDestroy public void destroy(); } private static class PreDestroyImpl implements PreDestroyInterface { @Override public void destroy() { // should not be called } } private static class RunnableType implements Runnable { @Override @PreDestroy public void run() { // method from interface; will it be called? } } private static class CloseableType implements Closeable { @Override public void close() throws IOException { } @PreDestroy public void shutdown() { } } private static class PreDestroyParent1 { @PreDestroy public void shutdown() { } } private static class PreDestroyChild1 extends PreDestroyParent1 { @PreDestroy public void shutdown() { System.out.println("shutdown invoked"); } } private static class PreDestroyParent2 { @PreDestroy public void anotherShutdown() { } } private static class PreDestroyChild2 extends PreDestroyParent2 { @PreDestroy public void shutdown() { System.out.println("shutdown invoked"); } } private static class PreDestroyParent3 { @PreDestroy public void shutdown() { } } private static class PreDestroyChild3 extends PreDestroyParent3 { public void shutdown() { System.out.println("shutdown invoked"); } } private static class MultipleDestroys { @PreDestroy public void shutdown1() { System.out.println("shutdown1 invoked"); } @PreDestroy public void shutdown2() { System.out.println("shutdown2 invoked"); } } private static class EagerBean { volatile boolean shutdown = false; SingletonBean singletonInstance; @Inject public EagerBean(SingletonBean singletonInstance) { this.singletonInstance = singletonInstance; } @PreDestroy public void shutdown() { System.out.println("eager bean shutdown invoked"); shutdown = true; this.singletonInstance.eagerShutdown = true; } } @Singleton private static class SingletonBean { volatile boolean eagerShutdown = false; boolean shutdown = false; @PreDestroy public void shutdown() { System.out.println("singleton bean shutdown invoked"); shutdown = true; Assert.assertTrue(eagerShutdown); } } @Test public void testEagerSingletonShutdown() { EagerBean eagerBean; SingletonBean singletonBean; try (LifecycleInjector injector = InjectorBuilder.fromModule(new AbstractModule() { @Override protected void configure() { bind(EagerBean.class).asEagerSingleton(); bind(SingletonBean.class).in(Scopes.SINGLETON); }}).createInjector()) { eagerBean = injector.getInstance(EagerBean.class); singletonBean = injector.getInstance(SingletonBean.class); Assert.assertFalse(eagerBean.shutdown); Assert.assertFalse(singletonBean.shutdown); } Assert.assertTrue(eagerBean.shutdown); Assert.assertTrue(singletonBean.shutdown); } @Test public void testLifecycleShutdownInheritance1() { final PreDestroyChild1 preDestroyChild = Mockito.spy(new PreDestroyChild1()); InOrder inOrder = Mockito.inOrder(preDestroyChild); try (LifecycleInjector injector = TestSupport.inject(preDestroyChild)) { Assert.assertNotNull(injector.getInstance(preDestroyChild.getClass())); Mockito.verify(preDestroyChild, Mockito.never()).shutdown(); } // once not twice inOrder.verify(preDestroyChild, Mockito.times(1)).shutdown(); } @Test public void testLifecycleShutdownInheritance2() { final PreDestroyChild2 preDestroyChild = Mockito.spy(new PreDestroyChild2()); InOrder inOrder = Mockito.inOrder(preDestroyChild); try (LifecycleInjector injector = TestSupport.inject(preDestroyChild)) { Assert.assertNotNull(injector.getInstance(preDestroyChild.getClass())); Mockito.verify(preDestroyChild, Mockito.never()).shutdown(); } // once not twice inOrder.verify(preDestroyChild, Mockito.times(1)).shutdown(); inOrder.verify(preDestroyChild, Mockito.times(1)).anotherShutdown(); } @Test public void testLifecycleShutdownInheritance3() { final PreDestroyChild3 preDestroyChild = Mockito.spy(new PreDestroyChild3()); InOrder inOrder = Mockito.inOrder(preDestroyChild); try (LifecycleInjector injector = TestSupport.inject(preDestroyChild)) { Assert.assertNotNull(injector.getInstance(preDestroyChild.getClass())); Mockito.verify(preDestroyChild, Mockito.never()).shutdown(); } // never, child class overrides method without annotation inOrder.verify(preDestroyChild, Mockito.never()).shutdown(); } @Test public void testLifecycleMultipleAnnotations() { final MultipleDestroys multipleDestroys = Mockito.spy(new MultipleDestroys()); try (LifecycleInjector injector = new TestSupport() .withFeature(GovernatorFeatures.STRICT_JSR250_VALIDATION, true) .withSingleton(multipleDestroys) .inject()) { Assert.assertNotNull(injector.getInstance(multipleDestroys.getClass())); Mockito.verify(multipleDestroys, Mockito.never()).shutdown1(); Mockito.verify(multipleDestroys, Mockito.never()).shutdown2(); } // never, multiple annotations should be ignored Mockito.verify(multipleDestroys, Mockito.never()).shutdown1(); Mockito.verify(multipleDestroys, Mockito.never()).shutdown2(); } @Test public void testLifecycleDeclaredInterfaceMethod() { final RunnableType runnableInstance = Mockito.mock(RunnableType.class); InOrder inOrder = Mockito.inOrder(runnableInstance); try (LifecycleInjector injector = TestSupport.inject(runnableInstance)) { Assert.assertNotNull(injector.getInstance(RunnableType.class)); Mockito.verify(runnableInstance, Mockito.never()).run(); } inOrder.verify(runnableInstance, Mockito.times(1)).run(); } @Test public void testLifecycleAnnotatedInterfaceMethod() { final PreDestroyImpl impl = Mockito.mock(PreDestroyImpl.class); InOrder inOrder = Mockito.inOrder(impl); try (LifecycleInjector injector = TestSupport.inject(impl)) { Assert.assertNotNull(injector.getInstance(RunnableType.class)); Mockito.verify(impl, Mockito.never()).destroy(); } inOrder.verify(impl, Mockito.never()).destroy(); } @Test public void testLifecycleShutdownWithInvalidPreDestroys() { final InvalidPreDestroys ipd = Mockito.mock(InvalidPreDestroys.class); try (LifecycleInjector injector = new TestSupport() .withFeature(GovernatorFeatures.STRICT_JSR250_VALIDATION, true) .withSingleton(ipd) .inject()) { Assert.assertNotNull(injector.getInstance(InvalidPreDestroys.class)); Mockito.verify(ipd, Mockito.never()).shutdownWithParameters(Mockito.anyString()); Mockito.verify(ipd, Mockito.never()).shutdownWithReturnValue(); } Mockito.verify(ipd, Mockito.never()).shutdownWithParameters(Mockito.anyString()); Mockito.verify(ipd, Mockito.never()).shutdownWithReturnValue(); } @Test public void testLifecycleCloseable() { final CloseableType closeableType = Mockito.mock(CloseableType.class); try { Mockito.doThrow(new IOException("boom")).when(closeableType).close(); } catch (IOException e1) { // ignore, mock only } try (LifecycleInjector injector = TestSupport.inject(closeableType)) { Assert.assertNotNull(injector.getInstance(closeableType.getClass())); try { Mockito.verify(closeableType, Mockito.never()).close(); } catch (IOException e) { // close() called before shutdown and failed Assert.fail("close() called before shutdown and failed"); } } try { Mockito.verify(closeableType, Mockito.times(1)).close(); Mockito.verify(closeableType, Mockito.never()).shutdown(); } catch (IOException e) { // close() called before shutdown and failed Assert.fail("close() called after shutdown and failed"); } } @Test public void testLifecycleShutdown() { final Foo foo = Mockito.mock(Foo.class); try (LifecycleInjector injector = TestSupport.inject(foo)) { Assert.assertNotNull(injector.getInstance(foo.getClass())); Mockito.verify(foo, Mockito.never()).shutdown(); } Mockito.verify(foo, Mockito.times(1)).shutdown(); } @Test public void testLifecycleShutdownWithAtProvides() { InjectorBuilder builder = InjectorBuilder.fromModule(new AbstractModule() { @Override protected void configure() { } @Provides @Singleton Foo getFoo() { return new Foo(); } }); Foo managedFoo = null; try (LifecycleInjector injector = builder.createInjector()) { managedFoo = injector.getInstance(Foo.class); Assert.assertNotNull(managedFoo); Assert.assertFalse(managedFoo.isShutdown()); } managedFoo = null; builder = null; } @Test public void testLifecycleShutdownWithExplicitScope() throws Exception { final ThreadLocalScope threadLocalScope = new ThreadLocalScope(); InjectorBuilder builder = InjectorBuilder.fromModule(new AbstractModule() { @Override protected void configure() { binder().bind(Foo.class).in(threadLocalScope); } }); Foo managedFoo = null; try (LifecycleInjector injector = builder.createInjector()) { threadLocalScope.enter(); managedFoo = injector.getInstance(Foo.class); Assert.assertNotNull(managedFoo); Assert.assertFalse(managedFoo.isShutdown()); threadLocalScope.exit(); System.gc(); Thread.sleep(GC_SLEEP_TIME); Assert.assertTrue(managedFoo.isShutdown()); } } @Test public void testLifecycleShutdownWithAnnotatedExplicitScope() throws Exception { final ThreadLocalScope threadLocalScope = new ThreadLocalScope(); InjectorBuilder builder = InjectorBuilder.fromModules(new AbstractModule() { @Override protected void configure() { binder().bind(Key.get(AnnotatedFoo.class)); } }, new AbstractModule() { @Override protected void configure() { binder().bindScope(ThreadLocalScoped.class, threadLocalScope); } }); AnnotatedFoo managedFoo = null; try (LifecycleInjector injector = builder.createInjector()) { threadLocalScope.enter(); managedFoo = injector.getInstance(AnnotatedFoo.class); Assert.assertNotNull(managedFoo); Assert.assertFalse(managedFoo.shutdown); threadLocalScope.exit(); System.gc(); Thread.sleep(GC_SLEEP_TIME); synchronized(managedFoo) { Assert.assertTrue(managedFoo.shutdown); } } } @Test public void testLifecycleShutdownWithMultipleInScope() throws Exception { final ThreadLocalScope scope = new ThreadLocalScope(); InjectorBuilder builder = InjectorBuilder.fromModule(new AbstractModule() { @Override protected void configure() { binder().bindScope(ThreadLocalScoped.class, scope); } @Provides @ThreadLocalScoped @Named("afoo1") protected AnnotatedFoo afoo1() { return new AnnotatedFoo(); } @Provides @ThreadLocalScoped @Named("afoo2") protected AnnotatedFoo afoo2() { return new AnnotatedFoo(); } }); AnnotatedFoo managedFoo1 = null; AnnotatedFoo managedFoo2 = null; try (LifecycleInjector injector = builder.createInjector()) { scope.enter(); managedFoo1 = injector.getInstance(Key.get(AnnotatedFoo.class, Names.named("afoo1"))); Assert.assertNotNull(managedFoo1); Assert.assertFalse(managedFoo1.isShutdown()); managedFoo2 = injector.getInstance(Key.get(AnnotatedFoo.class, Names.named("afoo2"))); Assert.assertNotNull(managedFoo2); Assert.assertFalse(managedFoo2.isShutdown()); scope.exit(); System.gc(); Thread.sleep(GC_SLEEP_TIME); Assert.assertTrue(managedFoo1.isShutdown()); Assert.assertTrue(managedFoo2.isShutdown()); } } @Test public void testLifecycleShutdownWithSingletonScope() throws Exception { InjectorBuilder builder = InjectorBuilder.fromModule(new AbstractModule() { @Override protected void configure() { binder().bind(Foo.class).in(Scopes.SINGLETON); } }); Foo managedFoo = null; try (LifecycleInjector injector = builder.createInjector()) { managedFoo = injector.getInstance(Foo.class); Assert.assertNotNull(managedFoo); Assert.assertFalse(managedFoo.isShutdown()); } System.gc(); Thread.sleep(GC_SLEEP_TIME); Assert.assertTrue(managedFoo.isShutdown()); } @Before public void printTestHeader() { System.out.println("\n======================================================="); System.out.println(" Running Test : " + name.getMethodName()); System.out.println("=======================================================\n"); } @Rule public TestName name = new TestName(); }
5,503
0
Create_ds/governator/governator-core/src/test/java/com/netflix
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/ThreadLocalScope.java
package com.netflix.governator; import static com.google.common.base.Preconditions.checkState; 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; import java.util.Map; public class ThreadLocalScope implements Scope { private final ThreadLocal<Map<Key<?>, Object>> content = new ThreadLocal<Map<Key<?>, Object>>(); public void enter() { checkState(content.get() == null, "ThreadLocalScope already exists in thread " + Thread.currentThread().getId()); content.set(Maps.<Key<?>, Object> newHashMap()); } public void exit() { checkState(content.get() != null, "No ThreadLocalScope found in thread " + Thread.currentThread().getId()); 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 ThreadLocalScope found in thread " + Thread.currentThread().getId()); } @SuppressWarnings("unchecked") T current = (T) scopedObjects.get(key); if (current == null && !scopedObjects.containsKey(key)) { 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,504
0
Create_ds/governator/governator-core/src/test/java/com/netflix
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/NullableBindingTest.java
package com.netflix.governator; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import org.junit.Before; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.util.Providers; import com.netflix.governator.event.guava.GuavaApplicationEventModule; public class NullableBindingTest { private Injector injector; @Before public void setup() { injector = InjectorBuilder.fromModules(new GuavaApplicationEventModule(), new AbstractModule() { @Override protected void configure() { bind(InnerDependency.class).toProvider(Providers.<InnerDependency>of(null)); } }).createInjector(); } @Test public void test() { OuterDependency instance = injector.getInstance(OuterDependency.class); assertNotNull(instance); assertNull(instance.innerDependency); } private static class OuterDependency { InnerDependency innerDependency; @Inject public OuterDependency(@Nullable InnerDependency innerDependency) { this.innerDependency = innerDependency; } } @Singleton private static class InnerDependency { } }
5,505
0
Create_ds/governator/governator-core/src/test/java/com/netflix
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/ProvisionMetricsModuleTest.java
package com.netflix.governator; import com.google.inject.AbstractModule; import com.google.inject.Key; import com.netflix.governator.ProvisionMetrics.Element; import com.netflix.governator.ProvisionMetrics.Visitor; import com.netflix.governator.visitors.ProvisionListenerTracingVisitor; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.inject.Singleton; public class ProvisionMetricsModuleTest { @Test public void disableMetrics() { try (LifecycleInjector injector = InjectorBuilder.fromModule( new AbstractModule() { @Override protected void configure() { bind(ProvisionMetrics.class).to(NullProvisionMetrics.class); } }) .createInjector()) { ProvisionMetrics metrics = injector.getInstance(ProvisionMetrics.class); LoggingProvisionMetricsVisitor visitor = new LoggingProvisionMetricsVisitor(); metrics.accept(visitor); Assert.assertTrue(visitor.getElementCount() == 0); } } @Test public void confirmDedupWorksWithOverride() { try (LifecycleInjector injector = InjectorBuilder.fromModule( new AbstractModule() { @Override protected void configure() { install(new ProvisionMetricsModule()); } }) // Confirm that installing ProvisionMetricsModule twice isn't broken with overrides .overrideWith(new AbstractModule() { @Override protected void configure() { } }) .createInjector()) { ProvisionMetrics metrics = injector.getInstance(ProvisionMetrics.class); LoggingProvisionMetricsVisitor visitor = new LoggingProvisionMetricsVisitor(); metrics.accept(visitor); Assert.assertTrue(visitor.getElementCount() != 0); } } @Singleton public static class Foo { public Foo() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(200); } @PostConstruct public void init() throws InterruptedException { TimeUnit.MILLISECONDS.sleep(200); } } public class KeyTrackingVisitor implements Visitor { private Element element; private Key key; KeyTrackingVisitor(Key key) { this.key = key; } @Override public void visit(Element element) { if (element.getKey().equals(key)) { this.element = element; } } Element getElement() { return element; } } @Test public void confirmMetricsIncludePostConstruct() { try (LifecycleInjector injector = InjectorBuilder.fromModules( new ProvisionDebugModule(), new AbstractModule() { @Override protected void configure() { bind(Foo.class).asEagerSingleton(); } }) .traceEachElement(new ProvisionListenerTracingVisitor()) .createInjector()) { ProvisionMetrics metrics = injector.getInstance(ProvisionMetrics.class); KeyTrackingVisitor keyTracker = new KeyTrackingVisitor(Key.get(Foo.class)); metrics.accept(keyTracker); Assert.assertNotNull(keyTracker.getElement()); Assert.assertTrue(keyTracker.getElement().getTotalDuration(TimeUnit.MILLISECONDS) > 300); } } }
5,506
0
Create_ds/governator/governator-core/src/test/java/com/netflix
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/ThreadLocalScoped.java
package com.netflix.governator; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; import com.google.inject.ScopeAnnotation; /** * annotation for binding instances bound to ThreadLocalScope * */ @Target({ TYPE, METHOD }) @Retention(RUNTIME) @ScopeAnnotation public @interface ThreadLocalScoped {}
5,507
0
Create_ds/governator/governator-core/src/test/java/com/netflix
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/GovernatorTest.java
package com.netflix.governator; import java.util.concurrent.atomic.AtomicBoolean; import junit.framework.Assert; import org.junit.Test; import com.google.inject.AbstractModule; import com.netflix.governator.spi.LifecycleListener; public class GovernatorTest { @Test public void testSimpleExecution() { final AtomicBoolean isStopped = new AtomicBoolean(); final AtomicBoolean isStarted = new AtomicBoolean(); LifecycleInjector injector = new Governator() .addModules(new AbstractModule() { @Override protected void configure() { bind(String.class).toInstance("foo"); } }) .run(new LifecycleListener() { @Override public void onStarted() { isStarted.set(true); } @Override public void onStopped(Throwable error) { isStopped.set(true); } @Override public String toString() { return "UnitTest[]"; } }); try { Assert.assertTrue(isStarted.get()); Assert.assertFalse(isStopped.get()); Assert.assertEquals("foo", injector.getInstance(String.class)); } finally { injector.shutdown(); } Assert.assertTrue(isStopped.get()); } }
5,508
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/providers/TestSingletonProvider.java
package com.netflix.governator.providers; import org.junit.Assert; import org.junit.Test; public class TestSingletonProvider { public static class Foo { } public static class StringProvider extends SingletonProvider<Foo> { @Override protected Foo create() { return new Foo(); } } @Test public void testSingletonBehavior() { StringProvider provider = new StringProvider(); Foo foo1 = provider.get(); Foo foo2 = provider.get(); Assert.assertSame(foo1, foo2); } }
5,509
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/package1/AutoBindSingletonMultiBinding.java
package com.netflix.governator.package1; import com.netflix.governator.annotations.AutoBindSingleton; import javax.inject.Singleton; @AutoBindSingleton(multiple=true, value=AutoBindSingletonInterface.class) @Singleton public class AutoBindSingletonMultiBinding implements AutoBindSingletonInterface { }
5,510
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/package1/AutoBindLazySingleton.java
package com.netflix.governator.package1; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(eager=false) public class AutoBindLazySingleton { }
5,511
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/package1/AutoBindModule.java
package com.netflix.governator.package1; import com.google.inject.AbstractModule; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton public class AutoBindModule extends AbstractModule { @Override protected void configure() { bind(String.class).toInstance("AutoBound"); } }
5,512
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/package1/Foo.java
package com.netflix.governator.package1; import com.google.inject.AbstractModule; import com.google.inject.Provides; import javax.inject.Singleton; public class Foo extends AbstractModule { @Provides @Singleton Foo getFoo() { return new Foo(); } @Override protected void configure() { } }
5,513
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/package1/FooModule.java
package com.netflix.governator.package1; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.netflix.governator.annotations.AutoBindSingleton; import javax.inject.Singleton; @AutoBindSingleton public class FooModule extends AbstractModule { @Provides @Singleton Foo getFoo() { return new Foo(); } @Override protected void configure() { } @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object obj) { return getClass().equals(obj.getClass()); } }
5,514
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/package1/AutoBindSingletonConcrete.java
package com.netflix.governator.package1; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton public class AutoBindSingletonConcrete { }
5,515
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/package1/AutoBindSingletonWithInterface.java
package com.netflix.governator.package1; import com.netflix.governator.annotations.AutoBindSingleton; @AutoBindSingleton(AutoBindSingletonInterface.class) public class AutoBindSingletonWithInterface implements AutoBindSingletonInterface { }
5,516
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/package1/AutoBindSingletonInterface.java
package com.netflix.governator.package1; public interface AutoBindSingletonInterface { }
5,517
0
Create_ds/governator/governator-core/src/test/java/com/netflix/governator
Create_ds/governator/governator-core/src/test/java/com/netflix/governator/event/ApplicationEventModuleTest.java
package com.netflix.governator.event; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; import org.junit.Test; import com.google.inject.AbstractModule; import com.google.inject.CreationException; import com.google.inject.Injector; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.event.guava.GuavaApplicationEventModule; public class ApplicationEventModuleTest { private Injector injector; @Before public void setup() { injector = InjectorBuilder.fromModules(new GuavaApplicationEventModule(), new AbstractModule() { @Override protected void configure() { bind(TestAnnotatedListener.class).toInstance(new TestAnnotatedListener()); bind(TestListenerInterface.class).toInstance(new TestListenerInterface()); } }).createInjector(); } @Test public void testProvidedComponentsPresent() { ApplicationEventDispatcher dispatcher = injector.getInstance(ApplicationEventDispatcher.class); TestAnnotatedListener listener = injector.getInstance(TestAnnotatedListener.class); TestListenerInterface listenerInterface = injector.getInstance(TestListenerInterface.class); assertNotNull(dispatcher); assertNotNull(listener); assertNotNull(listenerInterface); } @Test public void testAnnotatedListener() throws Exception { ApplicationEventDispatcher dispatcher = injector.getInstance(ApplicationEventDispatcher.class); TestAnnotatedListener listener = injector.getInstance(TestAnnotatedListener.class); assertEquals(0, listener.invocationCount.get()); dispatcher.publishEvent(new TestEvent()); assertEquals(1, listener.invocationCount.get()); dispatcher.publishEvent(new NotTestEvent()); assertEquals(1, listener.invocationCount.get()); } @Test public void testManuallyRegisteredApplicationEventListeners() throws Exception { ApplicationEventDispatcher dispatcher = injector.getInstance(ApplicationEventDispatcher.class); final AtomicInteger testEventCounter = new AtomicInteger(); final AtomicInteger notTestEventCounter = new AtomicInteger(); final AtomicInteger allEventCounter = new AtomicInteger(); dispatcher.registerListener(TestEvent.class, new ApplicationEventListener<TestEvent>() { public void onEvent(TestEvent event) { testEventCounter.incrementAndGet(); } }); dispatcher.registerListener(NotTestEvent.class, new ApplicationEventListener<NotTestEvent>() { public void onEvent(NotTestEvent event) { notTestEventCounter.incrementAndGet(); } }); dispatcher.registerListener(ApplicationEvent.class, new ApplicationEventListener<ApplicationEvent>() { public void onEvent(ApplicationEvent event) { allEventCounter.incrementAndGet(); } }); dispatcher.publishEvent(new TestEvent()); assertEquals(1, testEventCounter.get()); assertEquals(0, notTestEventCounter.get()); assertEquals(1, allEventCounter.get()); } @Test public void testManuallyRegisteredApplicationEventListenersWithoutClassArgument() throws Exception { ApplicationEventDispatcher dispatcher = injector.getInstance(ApplicationEventDispatcher.class); final AtomicInteger testEventCounter = new AtomicInteger(); final AtomicInteger notTestEventCounter = new AtomicInteger(); final AtomicInteger allEventCounter = new AtomicInteger(); dispatcher.registerListener(new ApplicationEventListener<TestEvent>() { public void onEvent(TestEvent event) { testEventCounter.incrementAndGet(); } }); dispatcher.registerListener(new ApplicationEventListener<NotTestEvent>() { public void onEvent(NotTestEvent event) { notTestEventCounter.incrementAndGet(); } }); dispatcher.registerListener(new ApplicationEventListener<ApplicationEvent>() { public void onEvent(ApplicationEvent event) { allEventCounter.incrementAndGet(); } }); dispatcher.publishEvent(new TestEvent()); assertEquals(1, testEventCounter.get()); assertEquals(0, notTestEventCounter.get()); assertEquals(1, allEventCounter.get()); } @Test public void testInjectorDiscoveredApplicationEventListeners() throws Exception { ApplicationEventDispatcher dispatcher = injector.getInstance(ApplicationEventDispatcher.class); TestListenerInterface listener = injector.getInstance(TestListenerInterface.class); assertEquals(0, listener.invocationCount.get()); dispatcher.publishEvent(new TestEvent()); assertEquals(1, listener.invocationCount.get()); dispatcher.publishEvent(new NotTestEvent()); assertEquals(1, listener.invocationCount.get()); } @Test public void testUnregisterApplicationEventListener() throws Exception { ApplicationEventDispatcher dispatcher = injector.getInstance(ApplicationEventDispatcher.class); final AtomicInteger testEventCounter = new AtomicInteger(); ApplicationEventRegistration registration = dispatcher.registerListener(new ApplicationEventListener<TestEvent>() { public void onEvent(TestEvent event) { testEventCounter.incrementAndGet(); } }); dispatcher.publishEvent(new TestEvent()); assertEquals(1, testEventCounter.get()); registration.unregister(); assertEquals(1, testEventCounter.get()); } @Test(expected=CreationException.class) public void testEventListenerWithInvalidArgumentsFailsFast() { injector = InjectorBuilder.fromModules(new GuavaApplicationEventModule(), new AbstractModule() { @Override protected void configure() { bind(TestFailFastEventListener.class).toInstance(new TestFailFastEventListener()); } }).createInjector(); } private class TestAnnotatedListener { AtomicInteger invocationCount = new AtomicInteger(); @EventListener public void doThing(TestEvent event) { invocationCount.incrementAndGet(); } } private class TestFailFastEventListener { @EventListener public void doNothing(String invalidArgumentType) { fail("This should never be called"); } } private class TestListenerInterface implements ApplicationEventListener<TestEvent> { AtomicInteger invocationCount = new AtomicInteger(); @Override public void onEvent(TestEvent event) { invocationCount.incrementAndGet(); } } private class TestEvent implements ApplicationEvent { } private class NotTestEvent implements ApplicationEvent { } }
5,518
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LifecycleInjectorCreator.java
package com.netflix.governator; import java.util.Arrays; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; 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.Stage; import com.google.inject.multibindings.Multibinder; import com.netflix.governator.annotations.SuppressLifecycleUninitialized; import com.netflix.governator.annotations.binding.Arguments; import com.netflix.governator.annotations.binding.Profiles; import com.netflix.governator.internal.DefaultPropertySource; import com.netflix.governator.internal.GovernatorFeatureSet; import com.netflix.governator.spi.InjectorCreator; import com.netflix.governator.spi.LifecycleListener; import com.netflix.governator.spi.PropertySource; /** * Custom strategy for creating a Guice Injector that enables support for lifecycle annotations such * as {@link @PreDestroy} and {@link @PostConstruct} as well as injector lifecycle hooks via the * {@link LifecycleListener} API. * * The LifecycleInjectorCreator may be overridden to handle pre-create and post-create notification. */ public class LifecycleInjectorCreator implements InjectorCreator<LifecycleInjector> { private static final Logger LOG = LoggerFactory.getLogger(LifecycleInjectorCreator.class); private String[] args = new String[]{}; private LinkedHashSet<String> profiles = new LinkedHashSet<>(); private IdentityHashMap<GovernatorFeature<?>, Object> features = new IdentityHashMap<>(); public LifecycleInjectorCreator withArguments(String[] args) { Preconditions.checkArgument(args != null, "Arg may not be null"); this.args = args; return this; } public LifecycleInjectorCreator withProfiles(String... profiles) { Preconditions.checkArgument(profiles != null, "Arg may not be null"); this.profiles = new LinkedHashSet<>(Arrays.asList(profiles)); return this; } public LifecycleInjectorCreator withProfiles(Set<String> profiles) { Preconditions.checkArgument(profiles != null, "profiles may not be null"); this.profiles = new LinkedHashSet<>(profiles); return this; } public LifecycleInjectorCreator withFeatures(IdentityHashMap<GovernatorFeature<?>, Object> features) { Preconditions.checkArgument(features != null, "features may not be null"); this.features = features; return this; } @Singleton @SuppressLifecycleUninitialized class GovernatorFeatureSetImpl implements GovernatorFeatureSet { private final IdentityHashMap<GovernatorFeature<?>, Object> featureOverrides; @Inject private PropertySource properties = new DefaultPropertySource(); @Inject public GovernatorFeatureSetImpl(IdentityHashMap<GovernatorFeature<?>, Object> featureOverrides) { this.featureOverrides = featureOverrides; } @SuppressWarnings("unchecked") @Override public <T> T get(GovernatorFeature<T> feature) { return featureOverrides.containsKey(feature) ? (T) featureOverrides.get(feature) : (T) properties.get(feature.getKey(), feature.getType(), feature.getDefaultValue()); } } @Override public LifecycleInjector createInjector(Stage stage, Module module) { final GovernatorFeatureSetImpl featureSet = new GovernatorFeatureSetImpl(features); final LifecycleManager manager = new LifecycleManager(); // Construct the injector using our override structure try { onBeforeInjectorCreate(); Injector injector = Guice.createInjector( stage, // This has to be first to make sure @PostConstruct support is added as early // as possible new ProvisionMetricsModule(), new LifecycleModule(), new LifecycleListenerModule(), new LegacyScopesModule(), new AbstractModule() { @Override protected void configure() { bind(GovernatorFeatureSet.class).toInstance(featureSet); bind(LifecycleManager.class).toInstance(manager); Multibinder<String> profilesBinder = Multibinder.newSetBinder(binder(), Key.get(String.class, Profiles.class)).permitDuplicates(); profiles.forEach(profile -> profilesBinder.addBinding().toInstance(profile)); bind(String[].class).annotatedWith(Arguments.class).toInstance(args); requestInjection(LifecycleInjectorCreator.this); } }, module ); manager.notifyStarted(); LifecycleInjector lifecycleInjector = LifecycleInjector.wrapInjector(injector, manager); onSuccessfulInjectorCreate(); LOG.info("Injector created successfully "); return lifecycleInjector; } catch (Exception e) { LOG.error("Failed to create injector - {}@{}", e.getClass().getSimpleName(), System.identityHashCode(e), e); onFailedInjectorCreate(e); try { manager.notifyStartFailed(e); } catch (Exception e2) { LOG.error("Failed to notify injector creation failure", e2 ); } if (!featureSet.get(GovernatorFeatures.SHUTDOWN_ON_ERROR)) { return LifecycleInjector.createFailedInjector(manager); } else { throw e; } } finally { onCompletedInjectorCreate(); } } /** * Template method invoked immediately before the injector is created */ protected void onBeforeInjectorCreate() { } /** * Template method invoked immediately after the injector is created */ protected void onSuccessfulInjectorCreate() { } /** * Template method invoked immediately after any failure to create the injector * @param error Cause of the failure */ protected void onFailedInjectorCreate(Throwable error) { } /** * Template method invoked at the end of createInjector() regardless of whether * the injector was created successful or not. */ protected void onCompletedInjectorCreate() { } @Override public String toString() { return "LifecycleInjectorCreator[]"; } }
5,519
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/InjectorBuilder.java
package com.netflix.governator; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.google.inject.spi.Element; import com.google.inject.spi.ElementVisitor; import com.google.inject.spi.Elements; import com.google.inject.util.Modules; import com.netflix.governator.spi.InjectorCreator; import com.netflix.governator.spi.ModuleTransformer; import com.netflix.governator.visitors.IsNotStaticInjectionVisitor; import com.netflix.governator.visitors.KeyTracingVisitor; import com.netflix.governator.visitors.WarnOfStaticInjectionVisitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.function.Consumer; /** * Simple DSL on top of Guice through which an injector may be created using a series * of operations and transformations of Guice modules. Operations are tracked using a * single module and are additive such that each operation executes on top of the entire * current binding state. Once all bindings have been defined the injector can be created * using an {@link InjectorCreator} strategy. * * <code> * InjectorBuilder * .fromModule(new MyApplicationModule()) * .overrideWith(new OverridesForTesting()) * .traceEachElement(new BindingTracingVisitor()) * .createInjector(); * </code> */ public final class InjectorBuilder { private static final Logger LOG = LoggerFactory.getLogger(InjectorBuilder.class); private static final Stage LAZY_SINGLETONS_STAGE = Stage.DEVELOPMENT; private Module module; /** * Start the builder using the specified module. * * @param module * @return */ public static InjectorBuilder fromModule(Module module) { return new InjectorBuilder(module); } public static InjectorBuilder fromModules(Module ... additionalModules) { return new InjectorBuilder(Modules.combine(additionalModules)); } public static InjectorBuilder fromModules(List<Module> modules) { return new InjectorBuilder(Modules.combine(modules)); } private InjectorBuilder(Module module) { this.module = module; } /** * Override all existing bindings with bindings in the provided modules. * This method uses Guice's build in {@link Modules#override} and is preferable * to using {@link Modules#override}. The approach here is to attempt to promote * the use of {@link Modules#override} as a single top level override. Using * {@link Modules#override} inside Guice modules can result in duplicate bindings * when the same module is installed in multiple placed. * @param modules */ public InjectorBuilder overrideWith(Module ... modules) { return overrideWith(Arrays.asList(modules)); } /** * @see InjectorBuilder#overrideWith(Module...) */ public InjectorBuilder overrideWith(Collection<Module> modules) { this.module = Modules.override(module).with(modules); return this; } /** * Add additional bindings to the module tracked by the DSL * @param modules */ public InjectorBuilder combineWith(Module ... modules) { List<Module> m = new ArrayList<>(); m.add(module); m.addAll(Arrays.asList(modules)); this.module = Modules.combine(m); return this; } /** * Iterator through all elements of the current module and write the output of the * ElementVisitor to the logger at debug level. 'null' responses are ignored * @param visitor * * @deprecated Use forEachElement(visitor, message -&gt; LOG.debug(message)); instead */ @Deprecated public InjectorBuilder traceEachElement(ElementVisitor<String> visitor) { return forEachElement(visitor, message -> LOG.debug(message)); } /** * Iterate through all elements of the current module and pass the output of the * ElementVisitor to the provided consumer. 'null' responses from the visitor are ignored. * * This call will not modify any bindings * @param visitor */ public <T> InjectorBuilder forEachElement(ElementVisitor<T> visitor, Consumer<T> consumer) { Elements .getElements(module) .forEach(element -> Optional.ofNullable(element.acceptVisitor(visitor)).ifPresent(consumer)); return this; } /** * Call the provided visitor for all elements of the current module. * * This call will not modify any bindings * @param visitor */ public <T> InjectorBuilder forEachElement(ElementVisitor<T> visitor) { Elements .getElements(module) .forEach(element -> element.acceptVisitor(visitor)); return this; } /** * Log the current binding state. traceEachKey() is useful for debugging a sequence of * operation where the binding snapshot can be dumped to the log after an operation. */ public InjectorBuilder traceEachKey() { return forEachElement(new KeyTracingVisitor(), message -> LOG.debug(message)); } /** * Log a warning that static injection is being used. Static injection is considered a 'hack' * to alllow for backwards compatibility with non DI'd static code. */ public InjectorBuilder warnOfStaticInjections() { return forEachElement(new WarnOfStaticInjectionVisitor(), message -> LOG.debug(message)); } /** * Extend the core DSL by providing a custom ModuleTransformer. The output module * replaces the current module. * @param transformer */ public InjectorBuilder map(ModuleTransformer transformer) { this.module = transformer.transform(module); return this; } /** * Filter out elements for which the provided visitor returns true. * @param predicate */ public InjectorBuilder filter(ElementVisitor<Boolean> predicate) { List<Element> elements = new ArrayList<Element>(); for (Element element : Elements.getElements(Stage.TOOL, module)) { if (element.acceptVisitor(predicate)) { elements.add(element); } } this.module = Elements.getModule(elements); return this; } /** * Filter out all bindings using requestStaticInjection */ public InjectorBuilder stripStaticInjections() { return filter(new IsNotStaticInjectionVisitor()); } /** * @return Return all elements in the managed module */ public List<Element> getElements() { return Elements.getElements(Stage.TOOL, module); } /** * Create the injector in the specified stage using the specified InjectorCreator * strategy. The InjectorCreator will most likely perform additional error handling on top * of the call to {@link Guice#createInjector}. * * @param stage Stage in which the injector is running. It is recommended to run in Stage.DEVELOPEMENT * since it treats all singletons as lazy as opposed to defaulting to eager instantiation which * could result in instantiating unwanted classes. * @param creator */ public <I extends Injector> I createInjector(Stage stage, InjectorCreator<I> creator) { return creator.createInjector(stage, module); } /** * @see {@link InjectorBuilder#createInjector(Stage, InjectorCreator)} */ public <I extends Injector> I createInjector(InjectorCreator<I> creator) { return creator.createInjector(LAZY_SINGLETONS_STAGE, module); } /** * @see {@link InjectorBuilder#createInjector(Stage, InjectorCreator)} */ public LifecycleInjector createInjector(Stage stage) { return createInjector(stage, new LifecycleInjectorCreator()); } /** * @see {@link InjectorBuilder#createInjector(Stage, InjectorCreator)} */ public LifecycleInjector createInjector() { return createInjector(LAZY_SINGLETONS_STAGE, new LifecycleInjectorCreator()); } }
5,520
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LegacyScopesModule.java
package com.netflix.governator; import com.google.inject.AbstractModule; import com.netflix.governator.guice.lazy.FineGrainedLazySingleton; import com.netflix.governator.guice.lazy.FineGrainedLazySingletonScope; import com.netflix.governator.guice.lazy.LazySingleton; import com.netflix.governator.guice.lazy.LazySingletonScope; public class LegacyScopesModule extends AbstractModule { @Override protected void configure() { bindScope(FineGrainedLazySingleton.class, FineGrainedLazySingletonScope.get()); bindScope(LazySingleton.class, LazySingletonScope.get()); } }
5,521
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LifecycleShutdownSignal.java
package com.netflix.governator; import com.google.inject.ImplementedBy; /** * Shutdown signal for the lifecycle manager. Code can either block on the signal * being fired or trigger it from a shutdown mechanism, such as a shutdown PID or * shutdown socket. Each container is likely to have it's own implementation of * shutdown signal. * * @author elandau * */ @ImplementedBy(DefaultLifecycleShutdownSignal.class) public interface LifecycleShutdownSignal { /** * Signal shutdown */ void signal(); /** * Wait for shutdown to be signalled. This could be either the result of * calling signal() or an internal shutdown mechanism for the container. * * @throws InterruptedException */ void await() throws InterruptedException; }
5,522
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/AutoBindSingletonAnnotatedClassScanner.java
package com.netflix.governator; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.ScopeAnnotation; import com.google.inject.TypeLiteral; import com.google.inject.binder.ScopedBindingBuilder; import com.google.inject.internal.MoreTypes; import com.google.inject.multibindings.Multibinder; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.guice.lazy.LazySingletonScope; import com.netflix.governator.spi.AnnotatedClassScanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Set; import javax.inject.Scope; import javax.inject.Singleton; public class AutoBindSingletonAnnotatedClassScanner implements AnnotatedClassScanner { private static final Logger LOG = LoggerFactory.getLogger(AutoBindSingletonAnnotatedClassScanner.class); @Override public Class<? extends Annotation> annotationClass() { return AutoBindSingleton.class; } @Override public <T> void applyTo(Binder binder, Annotation annotation, Key<T> key) { AutoBindSingleton abs = (AutoBindSingleton)annotation; Class clazz = key.getTypeLiteral().getRawType(); if ( Module.class.isAssignableFrom(clazz) ) { try { binder.install((Module)clazz.newInstance()); } catch (Exception e) { binder.addError("Failed to install @AutoBindSingleton module " + clazz.getName()); binder.addError(e); } } else { bindAutoBindSingleton(binder, abs, clazz); } } private void bindAutoBindSingleton(Binder binder, AutoBindSingleton annotation, Class<?> clazz) { LOG.info("Installing @AutoBindSingleton '{}'", clazz.getName()); LOG.info("***** @AutoBindSingleton for '{}' is deprecated as of 2015-10-10.\nPlease use a Guice module with bind({}.class).asEagerSingleton() instead.\nSee https://github.com/Netflix/governator/wiki/Auto-Binding", clazz.getName(), clazz.getSimpleName() ); Singleton singletonAnnotation = clazz.getAnnotation(Singleton.class); if (singletonAnnotation == null) { LOG.info("***** {} should also be annotated with @Singleton to ensure singleton behavior", clazz.getName()); } Class<?> annotationBaseClass = getAnnotationBaseClass(annotation); // Void.class is used as a marker to mean "default" because annotation defaults cannot be null if ( annotationBaseClass != Void.class ) { Object foundBindingClass = searchForBaseClass(clazz, annotationBaseClass, Sets.newHashSet()); Preconditions.checkArgument(foundBindingClass != null, String.format("AutoBindSingleton class %s does not implement or extend %s", clazz.getName(), annotationBaseClass.getName())); if ( foundBindingClass instanceof Class ) { if ( annotation.multiple() ) { Multibinder<?> multibinder = Multibinder.newSetBinder(binder, (Class)foundBindingClass); //noinspection unchecked applyScope(multibinder .addBinding() .to((Class)clazz), clazz, annotation); } else { //noinspection unchecked applyScope(binder .withSource(getCurrentStackElement()) .bind((Class)foundBindingClass) .to(clazz), clazz, annotation); } } else if ( foundBindingClass instanceof Type ) { TypeLiteral typeLiteral = TypeLiteral.get((Type)foundBindingClass); if ( annotation.multiple() ) { //noinspection unchecked applyScope(Multibinder.newSetBinder(binder, typeLiteral) .addBinding() .to((Class)clazz), clazz, annotation); } else { //noinspection unchecked applyScope(binder .withSource(getCurrentStackElement()) .bind(typeLiteral).to(clazz), clazz, annotation); } } else { binder.addError("Unexpected binding class: " + foundBindingClass); } } else { Preconditions.checkState(!annotation.multiple(), "@AutoBindSingleton(multiple=true) must have either value or baseClass set"); applyScope(binder .withSource(getCurrentStackElement()) .bind(clazz), clazz, annotation); } } private StackTraceElement getCurrentStackElement() { return Thread.currentThread().getStackTrace()[1]; } private void applyScope(ScopedBindingBuilder builder, Class<?> clazz, AutoBindSingleton annotation) { if (hasScopeAnnotation(clazz)) { // Honor scoped annotations first } else if (annotation.eager()) { builder.asEagerSingleton(); } else { builder.in(LazySingletonScope.get()); } } private boolean hasScopeAnnotation(Class<?> clazz) { Annotation scopeAnnotation = null; for (Annotation annot : clazz.getAnnotations()) { if (annot.annotationType().isAnnotationPresent(ScopeAnnotation.class) || annot.annotationType().isAnnotationPresent(Scope.class)) { Preconditions.checkState(scopeAnnotation == null, "Multiple scopes not allowed"); scopeAnnotation = annot; } } return scopeAnnotation != null; } private Class<?> getAnnotationBaseClass(AutoBindSingleton annotation) { Class<?> annotationValue = annotation.value(); Class<?> annotationBaseClass = annotation.baseClass(); Preconditions.checkState((annotationValue == Void.class) || (annotationBaseClass == Void.class), "@AutoBindSingleton cannot have both value and baseClass set"); return (annotationBaseClass != Void.class) ? annotationBaseClass : annotationValue; } private Object searchForBaseClass(Class<?> clazz, Class<?> annotationBaseClass, Set<Object> usedSet) { if (clazz == null) { return null; } if (clazz.equals(annotationBaseClass)) { return clazz; } if (!usedSet.add(clazz)) { return null; } for (Type type : clazz.getGenericInterfaces()) { if (MoreTypes.getRawType(type).equals(annotationBaseClass)) { return type; } } if (clazz.getGenericSuperclass() != null) { if (MoreTypes.getRawType(clazz.getGenericSuperclass()).equals(annotationBaseClass)) { return clazz.getGenericSuperclass(); } } for (Class<?> interfaceClass : clazz.getInterfaces()) { Object foundBindingClass = searchForBaseClass(interfaceClass, annotationBaseClass, usedSet); if (foundBindingClass != null) { return foundBindingClass; } } return searchForBaseClass(clazz.getSuperclass(), annotationBaseClass, usedSet); } }
5,523
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LifecycleListener.java
package com.netflix.governator; /** * @deprecated 2015-12-15 Use com.netflix.governator.api.LifecycleListener instead */ @Deprecated public interface LifecycleListener extends com.netflix.governator.spi.LifecycleListener { }
5,524
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/ProvisionDebugModule.java
package com.netflix.governator; import javax.inject.Inject; /** * Install this module to log a Provision report after the Injector is created. */ public final class ProvisionDebugModule extends SingletonModule { @Inject private static void initialize(LoggingProvisionMetricsLifecycleListener listener) { } @Override protected void configure() { // We do a static injection here to make sure the listener gets registered early. Otherwise, // if the injector fails before it's instantiated no logging will be done binder().requestStaticInjection(ProvisionDebugModule.class); } @Override public boolean equals(Object obj) { return getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } @Override public String toString() { return "ProvisionDebugModule[]"; } }
5,525
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/ManagedInstanceAction.java
package com.netflix.governator; import java.lang.ref.Reference; import java.util.concurrent.Callable; /** * Runnable that applies one or more LifecycleActions to a managed instance T or Reference<T>. * For Reference<T> the action is invoked on a best-effort basis, if the referent is non-null * at time run() is invoked */ public final class ManagedInstanceAction implements Callable<Void> { private final Object target; // the managed instance private final Reference<?> targetReference; // reference to the managed instance private final Iterable<LifecycleAction> actions; // set of actions that will // be applied to target public ManagedInstanceAction(Object target, Iterable<LifecycleAction> actions) { this.target = target; // keep hard reference to target this.targetReference = null; this.actions = actions; } public ManagedInstanceAction(Reference<?> target, Object context, Iterable<LifecycleAction> actions) { this.target = null; this.targetReference = target; // keep hard reference to target this.actions = actions; } @Override public Void call() throws Exception { Object target = (targetReference == null) ? this.target : targetReference.get(); if (target != null) { for (LifecycleAction m : actions) { m.call(target); } } return null; } }
5,526
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/DelegatingInjector.java
package com.netflix.governator; import java.lang.annotation.Annotation; import java.util.List; import java.util.Map; import java.util.Set; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.MembersInjector; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.TypeLiteral; import com.google.inject.spi.TypeConverterBinding; public abstract class DelegatingInjector implements Injector { private final Injector injector; public DelegatingInjector(Injector injector) { this.injector = injector; } @Override public void injectMembers(Object instance) { injector.injectMembers(instance); } @Override public <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral) { return injector.getMembersInjector(typeLiteral); } @Override public <T> MembersInjector<T> getMembersInjector(Class<T> type) { return injector.getMembersInjector(type); } @Override public Map<Key<?>, Binding<?>> getBindings() { return injector.getBindings(); } @Override public Map<Key<?>, Binding<?>> getAllBindings() { return injector.getAllBindings(); } @Override public <T> Binding<T> getBinding(Key<T> key) { return injector.getBinding(key); } @Override public <T> Binding<T> getBinding(Class<T> type) { return injector.getBinding(type); } @Override public <T> Binding<T> getExistingBinding(Key<T> key) { return injector.getExistingBinding(key); } @Override public <T> List<Binding<T>> findBindingsByType(TypeLiteral<T> type) { return injector.findBindingsByType(type); } @Override public <T> Provider<T> getProvider(Key<T> key) { return injector.getProvider(key); } @Override public <T> Provider<T> getProvider(Class<T> type) { return injector.getProvider(type); } @Override public <T> T getInstance(Key<T> key) { return injector.getInstance(key); } @Override public <T> T getInstance(Class<T> type) { return injector.getInstance(type); } @Override public Injector getParent() { return injector.getParent(); } @Override public Injector createChildInjector(Iterable<? extends Module> modules) { return injector.createChildInjector(modules); } @Override public Injector createChildInjector(Module... modules) { return injector.createChildInjector(modules); } @Override public Map<Class<? extends Annotation>, Scope> getScopeBindings() { return injector.getScopeBindings(); } @Override public Set<TypeConverterBinding> getTypeConverterBindings() { return injector.getTypeConverterBindings(); } }
5,527
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/Governator.java
package com.netflix.governator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import com.google.inject.Module; import com.google.inject.util.Modules; import com.netflix.governator.annotations.SuppressLifecycleUninitialized; import com.netflix.governator.internal.DefaultPropertySource; import com.netflix.governator.internal.GovernatorFeatureSet; import com.netflix.governator.internal.ModulesEx; import com.netflix.governator.spi.ModuleListTransformer; import com.netflix.governator.spi.ModuleTransformer; import com.netflix.governator.spi.PropertySource; import com.netflix.governator.spi.LifecycleListener; /** * Main entry point for creating a LifecycleInjector with guice extensions such as * support for @PostConstruct, @PreDestroy annotations and LifecycleListener. * * Example: * <code> new Governator() .addModules( new ArchaiusGovernatorModule(), new JettyModule(), new JerseyServletModule() { {@literal @}@Override protected void configureServlets() { serve("/*").with(GuiceContainer.class); bind(GuiceContainer.class).asEagerSingleton(); bind(HelloWorldApp.class).asEagerSingleton(); } } ) .run() .awaitTermination(); * </code> * * @deprecated 2015-12-13 Use {@link InjectorBuilder} instead */ @Deprecated public class Governator { protected Set<String> profiles = new LinkedHashSet<>(); protected List<Module> modules = new ArrayList<>(); protected List<ModuleListTransformer> transformers = new ArrayList<>(); protected List<Module> overrideModules = new ArrayList<>(); protected IdentityHashMap<GovernatorFeature<?>, Object> featureOverrides = new IdentityHashMap<>(); // This is a hack to make sure that if archaius is used at some point we make use // of the bridge so any access to the legacy Archaius1 API is actually backed by // the Archaius2 implementation static { System.setProperty("archaius.default.configuration.class", "com.netflix.archaius.bridge.StaticAbstractConfiguration"); System.setProperty("archaius.default.deploymentContext.class", "com.netflix.archaius.bridge.StaticDeploymentContext"); } @Singleton @SuppressLifecycleUninitialized class GovernatorFeatureSetImpl implements GovernatorFeatureSet { private final IdentityHashMap<GovernatorFeature<?>, Object> featureOverrides; @Inject private PropertySource properties = new DefaultPropertySource(); @Inject public GovernatorFeatureSetImpl(IdentityHashMap<GovernatorFeature<?>, Object> featureOverrides) { this.featureOverrides = featureOverrides; } @SuppressWarnings("unchecked") @Override public <T> T get(GovernatorFeature<T> feature) { return featureOverrides.containsKey(feature) ? (T) featureOverrides.get(feature) : (T) properties.get(feature.getKey(), feature.getType(), feature.getDefaultValue()); } } /** * Add Guice modules to Governator. * * @param modules Guice modules to add. * @return this */ public Governator addModules(Module ... modules) { if (modules != null) { this.modules.addAll(Arrays.asList(modules)); } return this; } /** * Add Guice modules to Governator. * * @param modules Guice modules to add. * @return this */ public Governator addModules(List<Module> modules) { if (modules != null) { this.modules.addAll(modules); } return this; } /** * Add a runtime profile. Profiles are processed by the conditional binding {@literal @}ConditionalOnProfile and * are injectable as {@literal @}Profiles Set{@literal <}String{@literal >}. * * @param profile A profile * @return this */ public Governator addProfile(String profile) { if (profile != null) { this.profiles.add(profile); } return this; } /** * Add a runtime profiles. Profiles are processed by the conditional binding {@literal @}ConditionalOnProfile and * are injectable as {@literal @}Profiles Set{@literal <}String{@literal >}. * * @param profiles Set of profiles * @return this */ public Governator addProfiles(String... profiles) { if (profiles != null) { this.profiles.addAll(Arrays.asList(profiles)); } return this; } /** * Add a runtime profiles. Profiles are processed by the conditional binding {@literal @}ConditionalOnProfile and * are injectable as {@literal @}Profiles Set{@literal <}String{@literal >}. * * @param profiles Set of profiles * @return this */ public Governator addProfiles(Collection<String> profiles) { if (profiles != null) { this.profiles.addAll(profiles); } return this; } /** * Enable the specified feature * @param feature Boolean feature to enable * @return this */ public Governator enableFeature(GovernatorFeature<Boolean> feature) { return setFeature(feature, true); } /** * Enable or disable the specified feature * @param feature Boolean feature to disable * @return this */ public Governator enableFeature(GovernatorFeature<Boolean> feature, boolean enabled) { return setFeature(feature, enabled); } /** * Disable the specified feature * @param feature Boolean feature to enable/disable * @return this */ public Governator disableFeature(GovernatorFeature<Boolean> feature) { return setFeature(feature, false); } /** * Set a feature * @param feature Feature to set * @return this */ public <T> Governator setFeature(GovernatorFeature<T> feature, T value) { this.featureOverrides.put(feature, value); return this; } /** * Add a ModuleListTransformer that will be invoked on the final list of modules * prior to creating the injectors. Multiple transformers may be added with each * transforming the result of the previous one. * * @param transformer A transformer * @return this */ public Governator addModuleListTransformer(ModuleListTransformer transformer) { if (transformer != null) { this.transformers.add(transformer); } return this; } /** * Add override modules for any modules add via addModules or that are * conditionally loaded. This is useful for testing or when an application * absolutely needs to override a binding to fix a binding problem in the * code modules * @param modules Modules that will be applied as overrides to modules * @return this */ public Governator addOverrideModules(Module ... modules) { if (modules != null) { this.overrideModules.addAll(Arrays.asList(modules)); } return this; } /** * Add override modules for any modules add via addModules or that are * conditionally loaded. This is useful for testing or when an application * absolutely needs to override a binding to fix a binding problem in the * code modules * @param modules Modules that will be applied as overrides to modules * @return this */ public Governator addOverrideModules(List<Module> modules) { if (modules != null) { this.overrideModules.addAll(modules); } return this; } /** * @deprecated Call new Governator().addModules(modules).run() instead. */ @Deprecated public LifecycleInjector createInjector(Module ... modules) { return new Governator().addModules(modules).run(); } /** * @deprecated Call new Governator().addModules(modules).run() instead. */ public LifecycleInjector createInjector(Collection<Module> modules) { return new Governator().addModules(new ArrayList<Module>(modules)).run(); } /** * Create the injector and call any LifecycleListeners * @return the LifecycleInjector for this run */ public LifecycleInjector run() { return run(ModulesEx.emptyModule(), new String[]{}); } public LifecycleInjector run(final String[] args) { return run(ModulesEx.emptyModule(), args); } public LifecycleInjector run(final Class<? extends LifecycleListener> mainClass) { return run(mainClass, new String[]{}); } public LifecycleInjector run(LifecycleListener mainClass) { return run(ModulesEx.fromInstance(mainClass), new String[]{}); } public LifecycleInjector run(LifecycleListener mainClass, final String[] args) { return run(ModulesEx.fromInstance(mainClass), args); } public LifecycleInjector run(final Class<? extends LifecycleListener> mainClass, final String[] args) { return run(ModulesEx.fromEagerSingleton(mainClass), args); } /** * Create the injector and call any LifecycleListeners * @param args - Runtime parameter (from main) injectable as {@literal @}Arguments String[] * @return the LifecycleInjector for this run */ private LifecycleInjector run(Module externalModule, final String[] args) { return InjectorBuilder .fromModules(modules) .combineWith(externalModule) .map(new ModuleTransformer() { @Override public Module transform(Module module) { List<Module> modulesToTransform = Collections.singletonList(module); for (ModuleListTransformer transformer : transformers) { modulesToTransform = transformer.transform(Collections.unmodifiableList(modulesToTransform)); } return Modules.combine(modulesToTransform); } }) .overrideWith(overrideModules) .createInjector(new LifecycleInjectorCreator() .withArguments(args) .withFeatures(featureOverrides) .withProfiles(profiles)); } }
5,528
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LifecycleManager.java
package com.netflix.governator; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.netflix.governator.annotations.SuppressLifecycleUninitialized; import com.netflix.governator.spi.LifecycleListener; /** * Manage state for lifecycle listeners * * @author elandau */ @Singleton @SuppressLifecycleUninitialized public final class LifecycleManager { private static final Logger LOG = LoggerFactory.getLogger(LifecycleManager.class); /** * Processes unreferenced LifecycleListeners from the referenceQueue, until * the 'running' flag is false or interrupted * */ private final class ListenerCleanupWorker implements Runnable { public void run() { try { while (running.get()) { Reference<? extends LifecycleListener> ref = unreferencedListenersQueue.remove(1000); if (ref != null && ref instanceof SafeLifecycleListener) { removeListener((SafeLifecycleListener)ref); } } LOG.info("LifecycleManager.ListenerCleanupWorker is exiting"); } catch (InterruptedException e) { LOG.info("LifecycleManager.ListenerCleanupWorker is exiting due to thread interrupt"); } } } private final Set<SafeLifecycleListener> listeners = new LinkedHashSet<>(); private final AtomicReference<State> state; private final ReferenceQueue<LifecycleListener> unreferencedListenersQueue = new ReferenceQueue<>(); private volatile Throwable failureReason; private final ExecutorService reqQueueExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("lifecycle-listener-monitor-%d").build()); private final AtomicBoolean running= new AtomicBoolean(true); public enum State { Starting, Started, Stopped, Done } public LifecycleManager() { LOG.info("Starting '{}'", this); state = new AtomicReference<>(State.Starting); reqQueueExecutor.submit(new ListenerCleanupWorker()); } private synchronized void removeListener(SafeLifecycleListener listenerRef) { listeners.remove(listenerRef); } public synchronized void addListener(LifecycleListener listener) { SafeLifecycleListener safeListener = SafeLifecycleListener.wrap(listener, unreferencedListenersQueue); if (!listeners.contains(safeListener) && listeners.add(safeListener)) { LOG.info("Adding listener '{}'", safeListener); switch (state.get()) { case Started: safeListener.onStarted(); break; case Stopped: safeListener.onStopped(failureReason); break; default: // ignore } } } public synchronized void notifyStarted() { if (state.compareAndSet(State.Starting, State.Started)) { LOG.info("Started '{}'", this); for (LifecycleListener listener : new ArrayList<>(listeners)) { listener.onStarted(); } } } public synchronized void notifyStartFailed(final Throwable t) { // State.Started added here to allow for failure when LifecycleListener.onStarted() is called, post-injector creation if (state.compareAndSet(State.Starting, State.Stopped) || state.compareAndSet(State.Started, State.Stopped)) { LOG.info("Failed start of '{}'", this); if (running.compareAndSet(true, false)) { reqQueueExecutor.shutdown(); } this.failureReason = t; Iterator<SafeLifecycleListener> shutdownIter = new LinkedList<>(listeners).descendingIterator(); while (shutdownIter.hasNext()) { shutdownIter.next().onStopped(t); } listeners.clear(); } state.set(State.Done); } public synchronized void notifyShutdown() { if (running.compareAndSet(true, false)) { reqQueueExecutor.shutdown(); } if (state.compareAndSet(State.Started, State.Stopped)) { LOG.info("Stopping '{}'", this); Iterator<SafeLifecycleListener> shutdownIter = new LinkedList<>(listeners).descendingIterator(); while (shutdownIter.hasNext()) { shutdownIter.next().onStopped(null); } listeners.clear(); } state.set(State.Done); } public State getState() { return state.get(); } public Throwable getFailureReason() { return failureReason; } @Override public String toString() { return "LifecycleManager@" + System.identityHashCode(this); } }
5,529
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/SafeLifecycleListener.java
package com.netflix.governator; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.netflix.governator.spi.LifecycleListener; /** * Wrapper for any LifecycleListener to provide this following functionality * 1. Logging of events as INFO * 2. Swallow any event handler exceptions during shutdown */ final class SafeLifecycleListener extends WeakReference<LifecycleListener> implements LifecycleListener { private static final Logger LOG = LoggerFactory.getLogger(SafeLifecycleListener.class); private final int delegateHash; private final String asString; public static SafeLifecycleListener wrap(LifecycleListener listener) { Preconditions.checkNotNull(listener, "listener argument must be non-null"); return new SafeLifecycleListener(listener, null); } public static SafeLifecycleListener wrap(LifecycleListener listener, ReferenceQueue<LifecycleListener> refQueue) { Preconditions.checkNotNull(listener, "listener argument must be non-null"); return new SafeLifecycleListener(listener, refQueue); } private SafeLifecycleListener(LifecycleListener delegate, ReferenceQueue<LifecycleListener> refQueue) { super(delegate, refQueue); this.delegateHash = delegate.hashCode(); this.asString = "SafeLifecycleListener@" + System.identityHashCode(this) + " [" + delegate.toString() + "]"; } @Override public void onStarted() { LifecycleListener delegate = get(); if (delegate != null) { LOG.info("Starting '{}'", delegate); delegate.onStarted(); } } @Override public void onStopped(Throwable t) { LifecycleListener delegate = get(); if (delegate != null) { if (t != null) { LOG.info("Stopping '{}' due to '{}@{}'", delegate, t.getClass().getSimpleName(), System.identityHashCode(t)); } else { LOG.info("Stopping '{}'", delegate); } try { delegate.onStopped(t); } catch (Exception e) { LOG.info("onStopped failed for {}", delegate, e); } } } @Override public String toString() { return asString; } @Override public int hashCode() { return delegateHash; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LifecycleListener delegate = get(); if (delegate != null) { LifecycleListener otherDelegate = ((SafeLifecycleListener)obj).get(); return delegate == otherDelegate || delegate.equals(otherDelegate); } else { return false; } } }
5,530
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LifecycleAction.java
package com.netflix.governator; /** * Generic interface for actions to be invoked as part of lifecycle * management. This includes actions such as PostConstruct, PreDestroy * and configuration related mapping. * * @see LifecycleFeature * * @author elandau * */ public interface LifecycleAction { /** * Invoke the action on an object. * * @param obj * @throws Exception */ public void call(Object obj) throws Exception; }
5,531
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/NullProvisionMetrics.java
package com.netflix.governator; import com.google.inject.Key; /** * Default NoOp implementation of ProvisionMetrics. * * @author elandau * */ public class NullProvisionMetrics implements ProvisionMetrics { @Override public void push(Key<?> key) { } @Override public void pop() { } @Override public void accept(Visitor visitor) { } }
5,532
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LoggingProvisionMetricsLifecycleListener.java
package com.netflix.governator; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class LoggingProvisionMetricsLifecycleListener extends AbstractLifecycleListener { private static final Logger LOG = LoggerFactory.getLogger(LoggingProvisionMetricsLifecycleListener.class); private final ProvisionMetrics metrics; @Inject LoggingProvisionMetricsLifecycleListener(LifecycleManager manager, ProvisionMetrics metrics) { this.metrics = metrics; manager.addListener(this); } @Override public void onStarted() { LOG.info("Injection provision report : \n" ); metrics.accept(new LoggingProvisionMetricsVisitor()); } @Override public void onStopped(Throwable t) { if (t != null) { LOG.info("Injection provision report for failed start : \n" ); metrics.accept(new LoggingProvisionMetricsVisitor()); } } }
5,533
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/ScanningModuleBuilder.java
package com.netflix.governator; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.Module; import com.netflix.governator.internal.scanner.ClasspathUrlDecoder; import com.netflix.governator.spi.AnnotatedClassScanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * When installed this module will scan for annotated classes and creating appropriate bindings. * The specific annotation to scan and binding semantics are captured in a {@link AnnotatedClassScanner}. * * The following example shows how to install a module that creates bindings for classes containing * the AutoBindSingleton annotation. * * <pre> * {@code * install(new ScanningModuleBuilder(). * .forPackages("org.example") * .addScanner(new AutoBindSingletonAnnotatedClassScanner()) * .build() * } * </pre> */ public class ScanningModuleBuilder { private static final Logger LOG = LoggerFactory.getLogger(ScanningModuleBuilder.class); private Set<String> packages = new HashSet<>(); private List<AnnotatedClassScanner> scanners = new ArrayList<>(); private ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); private Predicate<Class<?>> excludeRule = (cls) -> false; /** * Specify a custom class loader to use. If not specified Thread.currentThread().getContextClassLoader() * will be used. * * @param classLoader * @return Builder for chaining */ public ScanningModuleBuilder usingClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; } /** * Set of packages to scan. * * @param packages * @return Builder for chaining */ public ScanningModuleBuilder forPackages(String... packages) { return forPackages(Arrays.asList(packages)); } /** * Set of packages to scan. * * @param packages * @return Builder for chaining */ public ScanningModuleBuilder forPackages(Collection<String> packages) { this.packages = new HashSet<>(packages); return this; } /** * Specify an {@link AnnotatedClassScanner} to process classes from the set of specified packages. * * @param packages * @return Builder for chaining */ public ScanningModuleBuilder addScanner(AnnotatedClassScanner scanner) { scanners.add(scanner); return this; } /** * Exclude bindings for any class matching the specified predicate. Use this when implementing * custom exclude logic such as a regex match. * @param predicate Predicate that gets the fully qualified classname. * @return Builder for chaining */ // TODO: Make this public when switching to Java8 and use the JDK's predicate private ScanningModuleBuilder excludeClassesWhen(Predicate<Class<?>> predicate) { excludeRule = excludeRule.or(predicate); return this; } /** * Exclude specific classes from the classpath scanning. * @param classes Classes to exclude * @return Builder for chaining */ public ScanningModuleBuilder excludeClasses(Class<?>... classes) { return excludeClasses(new HashSet<>(Arrays.asList(classes))); } /** * Exclude specific classes from the classpath scanning. * @param packages Top packages to exclude * @return Builder for chaining */ public ScanningModuleBuilder excludePackages(String... packages) { return excludeClassesWhen(cls -> { for (String pkg : packages) { if (cls.getPackage().getName().startsWith(pkg)) { return true; }; } return false; }); } /** * Exclude specific classes from the classpath scanning. * @param classes Fully qualified classname to exclude * @return Builder for chaining */ public ScanningModuleBuilder excludeClasses(Set<Class<?>> classes) { final Set<Class<?>> toTest = new HashSet<>(classes); return excludeClassesWhen(cls -> toTest.contains(cls)); } public Module build() { final Predicate<Class<?>> includeRule = excludeRule.negate(); List<Consumer<Binder>> consumers = new ArrayList<>(); ScannerContext scanner = new ScannerContext(); for ( String basePackage : packages ) { scanner.doScan(basePackage, new Consumer<String>() { @Override public void accept(String className) { try { Class<?> cls = Class.forName(className, false, classLoader); if (includeRule.test(cls)) { for (AnnotatedClassScanner scanner : scanners) { if (cls.isAnnotationPresent(scanner.annotationClass())) { consumers.add(binder -> scanner.applyTo(binder, cls.getAnnotation(scanner.annotationClass()), Key.get(cls))); } } } } catch (ClassNotFoundException|NoClassDefFoundError e) { LOG.debug("Error scanning class {}", className, e); } catch (Error e) { throw new RuntimeException("Error scanning class " + className, e); } } }); } // Generate the list of elements here and immediately create a module from them. This ensures // that the class path is canned only once as a Module's configure method may be called multiple // times by Guice. return binder -> consumers.forEach(consumer -> consumer.accept(binder)); } private class ScannerContext { // Used to dedup packages that were already scanned private final Set<URL> foundUrls = new HashSet<>(); /** * Scan the specified packages and it's subpackages notifying the consumer for any new * class that's seen * @param basePackage * @param consumer * @throws Exception */ void doScan(String basePackage, Consumer<String> consumer) { LOG.debug("Scanning package {}", basePackage); try { String basePackageWithSlashes = basePackage.replace(".", "/"); for (URL url : Collections.list(classLoader.getResources(basePackageWithSlashes))) { LOG.debug("Scanning url {}", url); if (foundUrls.contains(url)) { continue; } foundUrls.add(url); try { if ( isJarURL(url)) { String jarPath = url.getFile(); if ( jarPath.contains("!") ) { jarPath = jarPath.substring(0, jarPath.indexOf("!")); url = new URL(jarPath); } File file = ClasspathUrlDecoder.toFile(url); try (JarFile jar = new JarFile(file)) { for (JarEntry entry : Collections.list(jar.entries())) { try { int pos = entry.getName().indexOf(".class"); if (pos != -1) { consumer.accept(entry.getName().substring(0, pos).replace('/', '.')); } } catch (Exception e) { throw new Exception( String.format("Unable to scan JarEntry '%s' in '%s'. %s", entry.getName(), file.getCanonicalPath(), e.getMessage())); } } } catch (Exception e ) { throw new Exception(String.format("Unable to scan '%s'. %s", file.getCanonicalPath(), e.getMessage())); } } else { scanPackage(url, basePackage, consumer); } } catch (Exception e) { throw new Exception(String.format("Unable to scan jar '%s'. %s ", url, e.getMessage())); } } } catch ( Exception e ) { LOG.error("Classpath scanning failed for package '{}'", basePackage, e); } } private boolean isJarURL(URL url) { String protocol = url.getProtocol(); return "zip".equals(protocol) || "jar".equals(protocol) || ("file".equals(protocol) && url.getPath().endsWith(".jar")); } private void scanPackage(URL url, String basePackage, Consumer<String> consumer) { File dir = ClasspathUrlDecoder.toFile(url); if (dir.isDirectory()) { scanDir(dir, (basePackage.length() > 0) ? (basePackage + ".") : "", consumer); } } private void scanDir(File dir, String packageName, Consumer<String> consumer) { LOG.debug("Scanning dir {}", packageName); File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { scanDir(file, packageName + file.getName() + ".", consumer); } else if (file.getName().endsWith(".class")) { String name = file.getName(); name = name.replaceFirst(".class$", ""); if (name.contains(".")) { continue; } consumer.accept(packageName + name); } } } } }
5,534
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/ServiceLoaderModuleBuilder.java
package com.netflix.governator; import java.util.ServiceLoader; import java.util.concurrent.Callable; import com.google.inject.AbstractModule; import com.google.inject.Module; import com.google.inject.ProvisionException; import com.google.inject.multibindings.Multibinder; /** * Builder for creating a Guice module that either installs modules loaded from the * service loader or creates multibindings for a service type. Method and field @Inject * methods of the services will also be invoked. * * @author elandau * * TODO: Lazy member injection */ public class ServiceLoaderModuleBuilder { private ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); private Boolean installed = false; public ServiceLoaderModuleBuilder usingClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; } public ServiceLoaderModuleBuilder forInstalledServices(Boolean installed) { this.installed = installed; return this; } private abstract class BaseModule<S> extends AbstractModule { private final Class<S> type; public BaseModule(Class<S> type) { this.type = type; } @Override protected final void configure() { Callable<ServiceLoader<S>> loader; if (installed) { if (classLoader != null) { throw new RuntimeException("Class loader may not be combined with loading installed services"); } loader = new Callable<ServiceLoader<S>>() { @Override public ServiceLoader<S> call() throws Exception { return ServiceLoader.loadInstalled(type); } }; } else if (classLoader != null) { loader = new Callable<ServiceLoader<S>>() { @Override public ServiceLoader<S> call() throws Exception { return ServiceLoader.load(type, classLoader); } }; } else { loader = new Callable<ServiceLoader<S>>() { @Override public ServiceLoader<S> call() throws Exception { return ServiceLoader.load(type); } }; } try { for (S service : loader.call()) { onService(service); } } catch (Exception e) { throw new ProvisionException("Failed to load services for '" + type + "'", e); } } protected abstract void onService(S service); } public <S extends Module> Module loadModules(final Class<S> type) { return new BaseModule<S>(type) { @Override protected void onService(S service) { install((Module)service); } }; } public <S> Module loadServices(final Class<S> type) { return new BaseModule<S>(type) { @Override protected void onService(S service) { requestInjection(service); Multibinder.newSetBinder(binder(), type).addBinding().toInstance(service); } }; } }
5,535
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/GovernatorFeature.java
package com.netflix.governator; public class GovernatorFeature<T> { private final String key; private final T defaultValue; public static <T> GovernatorFeature<T> create(String key, T defaultValue) { return new GovernatorFeature<T>(key, defaultValue); } public GovernatorFeature(String key, T defaultValue) { this.key = key; this.defaultValue = defaultValue; } public String getKey() { return key; } @SuppressWarnings("unchecked") public Class<T> getType() { return (Class<T>) defaultValue.getClass(); } public T getDefaultValue() { return defaultValue; } }
5,536
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LifecycleFeature.java
package com.netflix.governator; import java.util.List; /** * Each LifecycleFeature provides support for specific post constructor * pre-@PostConstruct processing of an injected object. For example, * {@link ConfigurationLifecycleFeature} enables configuration mapping * prior to @PostConstruct being called. * * {@link LifecycleFeature}s are added via a multibinding. For example, * * <pre> * {@code * Multibinder.newSetBinder(binder(), LifecycleFeature.class).addBinding().to(ConfigurationLifecycleFeature.class); * } * </pre> * * @author elandau */ public interface LifecycleFeature { /** * Return a list of actions to perform on object of this type as part of * lifecycle processing. Each LifecycleAction will likely be tied to processing * of a specific field or method. * * @param type * @return */ List<LifecycleAction> getActionsForType(Class<?> type); }
5,537
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/BindingLoggingModuleTransformer.java
package com.netflix.governator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Module; import com.google.inject.Stage; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; import com.netflix.governator.spi.ModuleListTransformer; public class BindingLoggingModuleTransformer implements ModuleListTransformer { private static final Logger LOG = LoggerFactory.getLogger(BindingLoggingModuleTransformer.class); @Override public List<Module> transform(List<Module> modules) { for (Element binding : Elements.getElements(Stage.TOOL, modules)) { LOG.debug("Binding : {}", binding); } return modules; } }
5,538
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/SimpleInjectorCreator.java
package com.netflix.governator; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.netflix.governator.spi.InjectorCreator; public class SimpleInjectorCreator implements InjectorCreator<Injector> { @Override public Injector createInjector(Stage stage, Module module) { return Guice.createInjector(stage, module); } }
5,539
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LifecycleInjector.java
package com.netflix.governator; import com.google.inject.Injector; import com.netflix.governator.spi.LifecycleListener; /** * Wrapper for Guice's Injector with added shutdown methods. * * <b>Invoking shutdown from outside the injector</b> * <pre> * <code> * LifecycleInjector injector = new Governator().run(); * // ... * injector.shutdown(); * </code> * </pre> * * <b>Blocking on the injector terminating</b> * <pre> * <code> * LifecycleInjector injector = new Governator().run(; * // ... * injector.awaitTermination(); * </code> * </pre> * * <b>Triggering shutdown from a DI'd class</b> * <pre> * <code> * {@literal @}Singleton * public class SomeShutdownService { * {@literal @}Inject * SomeShutdownService(LifecycleManager lifecycleManager) { * this.lifecycleManager = lifecycleManager; * } * * void someMethodInvokedForShutdown() { * this.lifecycleManager.shutdown(); * } * } * } * </code> * </pre> * * <b>Triggering an external event from shutdown without blocking</b> * <pre> * <code> * LifecycleInjector injector = new Governator().run(; * injector.addListener(new LifecycleListener() { * public void onShutdown() { * // Do your shutdown handling here * } * }); * } * </code> * </pre> */ final public class LifecycleInjector extends DelegatingInjector implements AutoCloseable { private final LifecycleManager manager; private final LifecycleShutdownSignal signal; public static LifecycleInjector createFailedInjector(LifecycleManager manager) { return new LifecycleInjector(null, manager); } public static LifecycleInjector wrapInjector(Injector injector, LifecycleManager manager) { return new LifecycleInjector(injector, manager); } private LifecycleInjector(Injector injector, LifecycleManager manager) { super(injector); this.manager = manager; if (injector != null) { this.signal = injector.getInstance(LifecycleShutdownSignal.class); } else { this.signal = new DefaultLifecycleShutdownSignal(manager); } } /** * Block until LifecycleManager terminates * @throws InterruptedException */ public void awaitTermination() throws InterruptedException { signal.await(); } /** * Shutdown LifecycleManager on this Injector which will invoke all registered * {@link LifecycleListener}s and unblock awaitTermination. * * @deprecated use LifecycleInjector.close() instead */ @Deprecated public void shutdown() { signal.signal(); } /** * Register a single shutdown listener for async notification of the LifecycleManager * terminating. * @param listener */ public void addListener(LifecycleListener listener) { manager.addListener(listener); } @Override public void close() { shutdown(); } }
5,540
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LoggingProvisionMetricsVisitor.java
package com.netflix.governator; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.governator.ProvisionMetrics.Element; import com.netflix.governator.ProvisionMetrics.Visitor; public class LoggingProvisionMetricsVisitor implements Visitor { private static final Logger LOG = LoggerFactory.getLogger(LoggingProvisionMetricsVisitor.class); int level = 1; int elementCount = 0; @Override public void visit(Element entry) { elementCount++; LOG.info(String.format("%" + (level * 3 - 2) + "s%s%s : %d ms (%d ms)", "", entry.getKey().getTypeLiteral().toString(), entry.getKey().getAnnotation() == null ? "" : " [" + entry.getKey().getAnnotation() + "]", entry.getTotalDuration(TimeUnit.MILLISECONDS), entry.getDuration(TimeUnit.MILLISECONDS) )); level++; entry.accept(this); level--; } int getElementCount() { return elementCount; } }
5,541
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/AbstractPropertySource.java
package com.netflix.governator; import java.lang.reflect.Method; import com.netflix.governator.spi.PropertySource; public abstract class AbstractPropertySource implements PropertySource { @Override public <T> T get(String key, Class<T> type) { return get(key, type, null); } @SuppressWarnings("unchecked") @Override public <T> T get(String key, Class<T> type, T defaultValue) { String value = get(key); if (value == null) { return defaultValue; } Method method; try { method = type.getDeclaredMethod("valueOf", String.class); } catch (Exception e) { throw new RuntimeException("Unable to find method 'valueOf' of type '" + type.getName() + "'"); } try { return (T) method.invoke(null, value); } catch (Exception e) { throw new RuntimeException("Unable to invoke method 'valueOf' of type '" + type.getName() + "'"); } } }
5,542
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/ShutdownHookModule.java
package com.netflix.governator; import javax.inject.Inject; import javax.inject.Singleton; import com.google.inject.AbstractModule; /** * When installed ShutdownHookModule will link a JVM shutdown hook to * LifecycleManager so that calling System.exit() will shutdown * it down. * * <pre> * {@code * Governator.createInjector(new LifecycleModule(), new ShutdownHookModule()); * } * </pre> */ public final class ShutdownHookModule extends AbstractModule { @Singleton public static class SystemShutdownHook extends Thread { @Inject public SystemShutdownHook(final LifecycleShutdownSignal shutdown) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown.signal(); } }); } } @Override protected void configure() { bind(SystemShutdownHook.class).asEagerSingleton(); } @Override public boolean equals(Object obj) { return getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } @Override public String toString() { return "ShutdownHookModule[]"; } }
5,543
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/DefaultLifecycleShutdownSignal.java
package com.netflix.governator; import java.util.concurrent.CountDownLatch; import javax.inject.Inject; import javax.inject.Singleton; /** * Default shutdown signal, mostly to be used for runtime applications, using * a CountDown latch. * * @author elandau * */ @Singleton public class DefaultLifecycleShutdownSignal extends AbstractLifecycleShutdownSignal { @Inject public DefaultLifecycleShutdownSignal(LifecycleManager manager) { super(manager); } private final CountDownLatch latch = new CountDownLatch(1); @Override public void signal() { shutdown(); latch.countDown(); } @Override public void await() throws InterruptedException { latch.await(); } }
5,544
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LifecycleListenerModule.java
package com.netflix.governator; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.matcher.Matchers; import com.google.inject.spi.ProvisionListener; import com.netflix.governator.annotations.SuppressLifecycleUninitialized; import com.netflix.governator.spi.LifecycleListener; /** * Adds support for detection and invocation of {@link LifecycleListener} instances. */ public final class LifecycleListenerModule extends AbstractModule { private LifecycleListenerProvisionListener provisionListener = new LifecycleListenerProvisionListener(); @Override protected void configure() { requestStaticInjection(LifecycleListenerProvisionListener.class); bind(LifecycleListenerProvisionListener.class).toInstance(provisionListener); bindListener(Matchers.any(), provisionListener); } @Singleton @SuppressLifecycleUninitialized static class LifecycleListenerProvisionListener implements ProvisionListener { private LifecycleManager manager; private List<LifecycleListener> pendingLifecycleListeners = new ArrayList<>(); @Inject public static void initialize(LifecycleManager manager, LifecycleListenerProvisionListener provisionListener) { provisionListener.manager = manager; for (LifecycleListener l : provisionListener.pendingLifecycleListeners) { manager.addListener(l); } provisionListener.pendingLifecycleListeners.clear(); } @Override public String toString() { return "LifecycleListenerProvisionListener[]"; } @Override public <T> void onProvision(ProvisionInvocation<T> provision) { final T injectee = provision.provision(); if (injectee != null && injectee instanceof LifecycleListener) { if (manager == null) { pendingLifecycleListeners.add((LifecycleListener) injectee); } else { manager.addListener((LifecycleListener) injectee); } } } } @Override public boolean equals(Object obj) { return getClass()==obj.getClass(); } @Override public int hashCode() { return getClass().hashCode(); } @Override public String toString() { return "LifecycleListenerModule[]"; } }
5,545
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/GovernatorFeatures.java
package com.netflix.governator; /** * Core Governator features. Features are configured/enabled on {@link Governator} */ public final class GovernatorFeatures { /** * When disable the Governator process will continue running even if there is a catastrophic * startup failure. This allows the admin page to stay up so that the process may be * debugged more easily. */ public static final GovernatorFeature<Boolean> SHUTDOWN_ON_ERROR = GovernatorFeature.create("Governator.features.shutdownOnError", true); /** * Auto discover AutoBinders using the ServiceLoader */ public static final GovernatorFeature<Boolean> DISCOVER_AUTO_BINDERS = GovernatorFeature.create("Governator.features.discoverAutoBinders", true); /** * Enables strict validation of @PostConstruct / @PreDestroy annotations at runtime; default is false */ public static final GovernatorFeature<Boolean> STRICT_JSR250_VALIDATION = GovernatorFeature.create("Governator.features.strictJsr250Validation", false); }
5,546
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/AbstractLifecycleListener.java
package com.netflix.governator; import com.netflix.governator.spi.LifecycleListener; public abstract class AbstractLifecycleListener implements LifecycleListener { @Override public void onStopped(Throwable t) { } @Override public void onStarted() { } }
5,547
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/ProvisionMetricsModule.java
package com.netflix.governator; import com.google.inject.AbstractModule; import com.google.inject.Key; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.matcher.Matchers; import com.google.inject.spi.ProvisionListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; public final class ProvisionMetricsModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(ProvisionMetricsModule.class); @Singleton private static class MetricsProvisionListener implements ProvisionListener, com.netflix.governator.spi.LifecycleListener { private ProvisionMetrics metrics; private boolean doneLoading = false; @Inject public static void initialize(MetricsProvisionListener listener, ProvisionMetrics metrics) { listener.metrics = metrics; } @Override public <T> void onProvision(ProvisionInvocation<T> provision) { final Key<?> key = provision.getBinding().getKey(); if (metrics == null) { LOG.debug("LifecycleProvisionListener not initialized yet : {} source={}", key, provision.getBinding().getSource()); return; } if (doneLoading) { return; } // Instantiate the type and pass to the metrics. This time captured will // include invoking any lifecycle events. metrics.push(key); try { provision.provision(); } finally { metrics.pop(); } } @Override public void onStarted() { doneLoading = true; } @Override public void onStopped(Throwable error) { doneLoading = true; } } private MetricsProvisionListener listener = new MetricsProvisionListener(); @Override protected void configure() { bindListener(Matchers.any(), listener); requestStaticInjection(MetricsProvisionListener.class); } @Provides @Singleton MetricsProvisionListener getMetricsProvisionListener() { return listener; } @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object obj) { return getClass().equals(obj.getClass()); } @Override public String toString() { return "ProvisionMetricsModule[]"; } }
5,548
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/SimpleProvisionMetrics.java
package com.netflix.governator; import com.google.inject.Key; import java.util.ArrayList; import java.util.List; import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; @Singleton public final class SimpleProvisionMetrics implements ProvisionMetrics { private final ConcurrentMap<Long, Node> threads = new ConcurrentHashMap<>(); private static class Node { List<Entry> children = new ArrayList<>(); Stack<Entry> stack = new Stack<>(); void accept(Visitor visitor) { children.forEach(entry -> visitor.visit(entry)); } void push(Entry entry) { if (stack.isEmpty()) { children.add(entry); } else { stack.peek().add(entry); } stack.push(entry); } void pop() { stack.pop().finish(); } } public static class Entry implements Element { final Key<?> key; final List<Entry> children = new ArrayList<>(); final long startTime = System.nanoTime(); long endTime; Entry(Key<?> key) { this.key = key; } void add(Entry child) { children.add(child); } void finish() { endTime = System.nanoTime(); } @Override public Key<?> getKey() { return key; } @Override public void accept(Visitor visit) { for (Entry entry : children) { visit.visit(entry); } } @Override public long getDuration(TimeUnit units) { long childDuration = 0; for (Entry child : children) { childDuration += child.getTotalDuration(units); } return getTotalDuration(units) - childDuration; } @Override public long getTotalDuration(TimeUnit units) { return units.convert(endTime - startTime, TimeUnit.NANOSECONDS); } } private Node currentNode() { return threads.computeIfAbsent(Thread.currentThread().getId(), id -> new Node()); } @Override public void push(Key<?> key) { currentNode().push(new Entry(key)); } @Override public void pop() { currentNode().pop(); } @Override public void accept(Visitor visitor) { threads.forEach((id, data) -> data.accept(visitor)); } }
5,549
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/DefaultModule.java
package com.netflix.governator; import com.google.inject.AbstractModule; /** * @deprecated This class provides little value and may encourage an unnecessary dependency * between libraries and Governator instead of plain Guice. */ public class DefaultModule extends AbstractModule { @Override protected void configure() { } @Override public String toString() { return getClass().getSimpleName(); } }
5,550
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/LifecycleModule.java
package com.netflix.governator; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Inject; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.ProvisionException; import com.google.inject.matcher.Matchers; import com.google.inject.multibindings.Multibinder; import com.google.inject.multibindings.MultibindingsScanner; import com.google.inject.spi.ProvisionListener; import com.netflix.governator.annotations.SuppressLifecycleUninitialized; import com.netflix.governator.internal.BinaryConstant; import com.netflix.governator.internal.GovernatorFeatureSet; import com.netflix.governator.internal.JSR250LifecycleAction.ValidationMode; import com.netflix.governator.internal.PostConstructLifecycleFeature; import com.netflix.governator.internal.PreDestroyLifecycleFeature; import com.netflix.governator.internal.PreDestroyMonitor; /** * Adds support for standard lifecycle annotations @PostConstruct and @PreDestroy to Guice. * * <code> * public class MyService { * {@literal @}PostConstruct * public void init() { * } * * {@literal @}PreDestroy * public void shutdown() { * } * } * </code> * * To use simply add LifecycleModule to guice when creating the injector * * See {@link LifecycleInjector} for different scenarios for shutting down the LifecycleManager. */ public final class LifecycleModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(LifecycleModule.class); private LifecycleProvisionListener provisionListener = new LifecycleProvisionListener(); /** * Holder of actions for a specific type. */ static class TypeLifecycleActions { final List<LifecycleAction> postConstructActions = new ArrayList<LifecycleAction>(); final List<LifecycleAction> preDestroyActions = new ArrayList<>(); } @Singleton @SuppressLifecycleUninitialized static class LifecycleProvisionListener extends AbstractLifecycleListener implements ProvisionListener { private final ConcurrentMap<Class<?>, TypeLifecycleActions> cache = new ConcurrentHashMap<>(BinaryConstant.I12_4096); private Set<LifecycleFeature> features; private final AtomicBoolean isShutdown = new AtomicBoolean(); private PostConstructLifecycleFeature postConstructFeature; private PreDestroyLifecycleFeature preDestroyFeature; private PreDestroyMonitor preDestroyMonitor; private boolean shutdownOnFailure = true; @SuppressLifecycleUninitialized @Singleton static class OptionalArgs { @com.google.inject.Inject(optional = true) GovernatorFeatureSet governatorFeatures; boolean hasShutdownOnFailure() { return governatorFeatures == null ? true : governatorFeatures.get(GovernatorFeatures.SHUTDOWN_ON_ERROR); } ValidationMode getJsr250ValidationMode() { return governatorFeatures == null ? ValidationMode.LAX : governatorFeatures.get(GovernatorFeatures.STRICT_JSR250_VALIDATION) ? ValidationMode.STRICT : ValidationMode.LAX; } } @Inject public static void initialize( final Injector injector, OptionalArgs args, LifecycleManager manager, LifecycleProvisionListener provisionListener, Set<LifecycleFeature> features) { provisionListener.features = features; provisionListener.shutdownOnFailure = args.hasShutdownOnFailure(); ValidationMode validationMode = args.getJsr250ValidationMode(); provisionListener.postConstructFeature = new PostConstructLifecycleFeature(validationMode); provisionListener.preDestroyFeature = new PreDestroyLifecycleFeature(validationMode); provisionListener.preDestroyMonitor = new PreDestroyMonitor(injector.getScopeBindings()); LOG.debug("LifecycleProvisionListener initialized with features {}", features); } public TypeLifecycleActions getOrCreateActions(Class<?> type) { TypeLifecycleActions actions = cache.get(type); if (actions == null) { actions = new TypeLifecycleActions(); // Ordered set of actions to perform before PostConstruct for (LifecycleFeature feature : features) { actions.postConstructActions.addAll(feature.getActionsForType(type)); } // Finally, add @PostConstruct methods actions.postConstructActions.addAll(postConstructFeature.getActionsForType(type)); // Determine @PreDestroy methods actions.preDestroyActions.addAll(preDestroyFeature.getActionsForType(type)); TypeLifecycleActions existing = cache.putIfAbsent(type, actions); if (existing != null) { return existing; } } return actions; } /** * Invoke all shutdown actions */ @Override public synchronized void onStopped(Throwable optionalFailureReason) { if (shutdownOnFailure || optionalFailureReason == null) { if (isShutdown.compareAndSet(false, true)) { try { preDestroyMonitor.close(); } catch (Exception e) { LOG.error("failed closing preDestroyMonitor", e); } } } } @Override public String toString() { return "LifecycleProvisionListener@" + System.identityHashCode(this); } @Override public <T> void onProvision(ProvisionInvocation<T> provision) { final T injectee = provision.provision(); if (injectee == null) { return; } if (features == null) { if (!injectee.getClass().isAnnotationPresent(SuppressLifecycleUninitialized.class)) { LOG.debug("LifecycleProvisionListener not initialized yet : {}", injectee.getClass()); } // TODO: Add to PreDestroy list return; } //Ignore for Spring-managed bindings Object source = provision.getBinding().getSource(); if(source != null && source.toString().contains("spring-guice")) { return; } final TypeLifecycleActions actions = getOrCreateActions(injectee.getClass()); // Call all postConstructActions for this injectee if (!actions.postConstructActions.isEmpty()) { try { new ManagedInstanceAction(injectee, actions.postConstructActions).call(); } catch (Exception e) { throw new ProvisionException("postConstruct failed", e); } } // Add any PreDestroy methods to the shutdown list of actions if (!actions.preDestroyActions.isEmpty()) { if (isShutdown.get() == false) { preDestroyMonitor.register(injectee, provision.getBinding(), actions.preDestroyActions); } else { LOG.warn("Already shutting down. Shutdown methods {} on {} will not be invoked", actions.preDestroyActions, injectee.getClass().getName()); } } } } @Override protected void configure() { requestStaticInjection(LifecycleProvisionListener.class); bind(LifecycleProvisionListener.class).toInstance(provisionListener); bindListener(Matchers.any(), provisionListener); Multibinder.newSetBinder(binder(), LifecycleFeature.class); install(MultibindingsScanner.asModule()); } @Override public boolean equals(Object obj) { return getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } @Override public String toString() { return "LifecycleModule@" + System.identityHashCode(this); } }
5,551
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/AbstractLifecycleShutdownSignal.java
package com.netflix.governator; public abstract class AbstractLifecycleShutdownSignal implements LifecycleShutdownSignal { private final LifecycleManager manager; protected AbstractLifecycleShutdownSignal(LifecycleManager manager) { this.manager = manager; } protected void shutdown() { manager.notifyShutdown(); } }
5,552
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/SingletonModule.java
package com.netflix.governator; import java.lang.reflect.Modifier; import com.google.inject.AbstractModule; /** * Base module that ensures only one module is used when multiple modules * are installed using the concrete module class as the dedup key. To * ensure 'best practices' this class also forces the concrete module to * be final. This is done to prevent the use of inheritance for overriding * behavior in favor of using Modules.override(). * * @deprecated Extend AbstractModule directly and add the following equals and hashCode * * {@code @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } } */ @Deprecated public abstract class SingletonModule extends AbstractModule { public SingletonModule() { if (!Modifier.isFinal(getClass().getModifiers())) { throw new RuntimeException("Module " + getClass().getName() + " must be final"); } } @Override protected void configure() { } @Override public boolean equals(Object obj) { return obj != null && getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } @Override public String toString() { return getClass().getName(); } }
5,553
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/PropertiesPropertySource.java
package com.netflix.governator; import java.util.Properties; import com.google.inject.Binder; import com.google.inject.Module; import com.netflix.governator.spi.PropertySource; /** * Implementation of a PropertySource using a standard {@link Properties} object. * * PropertiesPropertySource is also a Guice module and can be installed to provide a * self binding to PropertySource.class. */ public final class PropertiesPropertySource extends AbstractPropertySource implements Module { private Properties props; public PropertiesPropertySource(Properties props) { this.props = new Properties(props); } public PropertiesPropertySource() { this(new Properties()); } public static PropertiesPropertySource from(Properties props) { return new PropertiesPropertySource(props); } public PropertiesPropertySource setProperty(String key, String value) { props.setProperty(key, value); return this; } @Override public boolean hasProperty(String key) { return props.containsKey(key); } @Override public String get(String key) { return props.getProperty(key); } @Override public String get(String key, String defaultValue) { return props.getProperty(key, defaultValue); } @Override public void configure(Binder binder) { binder.bind(PropertySource.class).toInstance(this); } @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object obj) { // equals() is used by Guice to dedup multiple installs. This is module has state so we only // allow one instance of it to ever be installed. This equals() implementation // forces guice to dedup as long as it is the same exact object. Installing multiple // PropertiesPropertySource instances will result in duplicate binding errors for PropertySource // where the errors will provide details about where the multiple installs came from. return this == obj; } @Override public String toString() { return "PropertiesPropertySource[count=" + props.size() + "]"; } }
5,554
0
Create_ds/governator/governator-core/src/main/java/com/netflix
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/ProvisionMetrics.java
package com.netflix.governator; import java.util.concurrent.TimeUnit; import com.google.inject.ImplementedBy; import com.google.inject.Key; /** * Interface invoked by LifecycleModule's ProvisionListener to * gather metrics on objects as they are provisioned. Through the * provision listener it's possible to generate a dependency tree * for the first initialization of all objects. Note that no call * will be made for singletons that are being injected but have * already been instantiated. */ @ImplementedBy(SimpleProvisionMetrics.class) public interface ProvisionMetrics { /** * Node used to track metrics for an object that has been provisioned */ public static interface Element { public Key<?> getKey(); public long getDuration(TimeUnit units); public long getTotalDuration(TimeUnit units); public void accept(Visitor visitor); } /** * Visitor API for traversing nodes */ public static interface Visitor { void visit(Element element); } /** * Notification that an object of type 'key' is about to be created. * Note that there will likely be several nested calls to push() as * dependencies are injected. * @param key */ public void push(Key<?> key); /** * Pop and finalize initialization of the latest object to be provisioned. * A matching pop will be called for each push(). */ public void pop(); /** * Traverse the elements using the visitor pattern. * @param visitor */ public void accept(Visitor visitor); }
5,555
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/visitors/BindingTracingVisitor.java
package com.netflix.governator.visitors; import com.google.inject.Binding; import com.google.inject.spi.DefaultElementVisitor; import com.netflix.governator.InjectorBuilder; /** * Visitor for logging the entire binding information for each Element * * To use with {@link InjectorBuilder}, * * <code> * InjectorBuilder * .withModules(new MyApplicationModule) * .forEachElement(new BindingTracingVisitor()) * .createInjector(); * </code> */ public class BindingTracingVisitor extends DefaultElementVisitor<String> { @Override public <T> String visit(Binding<T> binding) { return binding.toString(); } }
5,556
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/visitors/WarnOfStaticInjectionVisitor.java
package com.netflix.governator.visitors; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.StaticInjectionRequest; /** * Visitor that log a warning for any use of requestStaticInjection */ public class WarnOfStaticInjectionVisitor extends DefaultElementVisitor<String> { @Override public String visit(StaticInjectionRequest element) { return String.format("Static injection is fragile! Please fix %s at %s", element.getType().getName(), element.getSource()); } }
5,557
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/visitors/WarnOfToInstanceInjectionVisitor.java
package com.netflix.governator.visitors; import com.google.inject.Binding; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.InstanceBinding; /* * Specialized {@link DefaultElementVisitor} that formats a warning for any toInstance() binding. * Use this with {@link InjectorBuilder#forEachElement} to identify situations where toInstance() bindings * are used. The assertion here is that toInstance bindings are an indicator of provisioning being * done outside of Guice and could involve static initialization that violates ordering guarantees * of a DI framework. The recommendation is to replace toInstance() bindings with @Provides methods. */ public final class WarnOfToInstanceInjectionVisitor extends DefaultElementVisitor<String> { public <T> String visit(Binding<T> binding) { return binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, String>() { public String visit(InstanceBinding<? extends T> instanceBinding) { return String.format("toInstance() at %s can force undesireable static initialization. " + "Consider replacing with an @Provides method instead.", instanceBinding.getSource()); } }); } }
5,558
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/visitors/IsStaticInjectionVisitor.java
package com.netflix.governator.visitors; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Element; import com.google.inject.spi.StaticInjectionRequest; /** * Predicate visitor that returns 'true' if an Element is a requestStaticInjection. */ public class IsStaticInjectionVisitor extends DefaultElementVisitor<Boolean> { @Override protected Boolean visitOther(Element element) { return false; } @Override public Boolean visit(StaticInjectionRequest element) { return true; } }
5,559
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/visitors/ModuleSourceTracingVisitor.java
package com.netflix.governator.visitors; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Element; import com.google.inject.spi.ElementSource; /** * Visitor for logging the 'path' through which each binding was created */ public class ModuleSourceTracingVisitor extends DefaultElementVisitor<String> { @Override protected String visitOther(Element element) { Object source = element.getSource(); ElementSource elementSource = null; while (source instanceof ElementSource) { elementSource = (ElementSource)source; source = elementSource.getOriginalElementSource(); } if (elementSource != null) { return elementSource.getModuleClassNames().toString(); } return null; } }
5,560
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/visitors/IsNotStaticInjectionVisitor.java
package com.netflix.governator.visitors; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Element; import com.google.inject.spi.StaticInjectionRequest; /** * Predicate visitor that returns 'true' if an Element is a requestStaticInjection. */ public class IsNotStaticInjectionVisitor extends DefaultElementVisitor<Boolean> { @Override protected Boolean visitOther(Element element) { return true; } @Override public Boolean visit(StaticInjectionRequest element) { return false; } }
5,561
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/visitors/KeyTracingVisitor.java
package com.netflix.governator.visitors; import com.google.inject.Binding; import com.google.inject.spi.DefaultElementVisitor; import com.netflix.governator.InjectorBuilder; /** * Visitor for logging only the Key for each {@code Element} binding * * To use with {@link InjectorBuilder} * * <code> * InjectorBuilder * .fromModule(new MyApplicationModule) * .forEachElement(new BindingTracingVisitor()) * .createInjector(); * </code> */ public class KeyTracingVisitor extends DefaultElementVisitor<String> { @Override public <T> String visit(Binding<T> binding) { return binding.getKey().toString(); } }
5,562
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/visitors/ProvisionListenerTracingVisitor.java
package com.netflix.governator.visitors; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.ProvisionListenerBinding; public class ProvisionListenerTracingVisitor extends DefaultElementVisitor<String> { public String visit(ProvisionListenerBinding binding) { return String.format("Provision listener %s matching %s at %s", binding.getListeners(), binding.getBindingMatcher(), binding.getSource()); } }
5,563
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/test/TestLifecycleListener.java
package com.netflix.governator.test; import javax.inject.Inject; import com.google.inject.Injector; import com.netflix.governator.spi.LifecycleListener; public abstract class TestLifecycleListener implements LifecycleListener { @Inject Injector injector; private boolean isStarted = false; private boolean isStopped = false; private Throwable error = null; @Override public void onStarted() { isStarted = true; } @Override public void onStopped(Throwable t) { error = t; isStopped = true; } public boolean isStarted() { return isStarted; } public boolean isStopped() { return isStopped; } public Throwable getError() { return error; } protected abstract void onReady(Injector injector); }
5,564
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/test/TracingProvisionListener.java
package com.netflix.governator.test; import java.io.PrintStream; import com.google.common.base.Strings; import com.google.inject.spi.ProvisionListener; /** * Use TracingProvisionListener to debug issues with Guice Injector creation by tracing * the object initialization path. Various hooks are provided for the different stages * of object instantiation: before, after and on error. * * To enable add the following binding in any guice module * <code> * bindListener(Matchers.any(), TracingProvisionListener.createDefault()); * </code> * */ public class TracingProvisionListener implements ProvisionListener { private int indent = 0; private final String prefix; private final int indentAmount; private final BindingFormatter beforeFormatter; private final BindingFormatter afterFormatter; private final PrintStream stream; private ErrorFormatter errorFormatter; private static final BindingFormatter EMPTY_BINDING_FORMATTER = new BindingFormatter() { @Override public <T> String format(ProvisionInvocation<T> provision) { return ""; } }; private static final BindingFormatter SIMPLE_BINDING_FORMATTER = new BindingFormatter() { @Override public <T> String format(ProvisionInvocation<T> provision) { return provision.getBinding().getKey().toString(); } }; private static final ErrorFormatter SIMPLE_ERROR_FORMATTER = new ErrorFormatter() { @Override public <T> String format(ProvisionInvocation<T> provision, Throwable t) { return String.format("Error creating '%s'. %s", provision.getBinding().getKey().toString(), t.getMessage()); } }; /** * Builder for customizing the tracer output. */ public static class Builder { private String prefix = ""; private int indentAmount = 2; private BindingFormatter beforeFormatter = SIMPLE_BINDING_FORMATTER; private BindingFormatter afterFormatter = EMPTY_BINDING_FORMATTER; private ErrorFormatter errorFormatter = SIMPLE_ERROR_FORMATTER; private PrintStream stream = System.out; /** * Provide a custom formatter for messages written before a type is provisioned * Returning null or empty stream will result in no message being written * * @param formatter */ public Builder formatBeforeWith(BindingFormatter formatter) { this.beforeFormatter = formatter; return this; } /** * Provide a custom formatter for messages written after a type is provisioned. * Returning null or empty stream will result in no message being written * * @param formatter */ public Builder formatAfterWith(BindingFormatter formatter) { this.afterFormatter = formatter; return this; } /** * Provide a custom formatter for messages written when type provision throws * an exception * * @param formatter */ public Builder formatErrorsWith(ErrorFormatter formatter) { this.errorFormatter = formatter; return this; } /** * Indentation increment for each nested provisioning * @param amount - Number of spaces to indent */ public Builder indentBy(int amount) { this.indentAmount = amount; return this; } /** * Customized the PrintStream to which messages are written. By default * messages are written to System.err * * @param stream */ public Builder writeTo(PrintStream stream) { this.stream = stream; return this; } /** * String to prefix each row (prior to indentation). Default is "" * * @param prefix */ public Builder prefixLinesWith(String prefix) { this.prefix = prefix; return this; } public TracingProvisionListener build() { return new TracingProvisionListener(this); } } public static interface BindingFormatter { <T> String format(ProvisionInvocation<T> provision); } public static interface ErrorFormatter { <T> String format(ProvisionInvocation<T> provision, Throwable error); } public static TracingProvisionListener createDefault() { return new TracingProvisionListener(newBuilder()); } public static Builder newBuilder() { return new Builder(); } private TracingProvisionListener(Builder builder) { this.indentAmount = builder.indentAmount; this.beforeFormatter = builder.beforeFormatter; this.afterFormatter = builder.afterFormatter; this.errorFormatter = builder.errorFormatter; this.prefix = builder.prefix; this.stream = builder.stream; } @Override public <T> void onProvision(ProvisionInvocation<T> provision) { writeString(beforeFormatter.format(provision)); indent += indentAmount; try { provision.provision(); writeString(afterFormatter.format(provision)); } catch (Throwable t) { writeString(errorFormatter.format(provision, t)); throw t; } finally { indent -= indentAmount; } } private void writeString(String str) { if (str != null && !str.isEmpty()) { stream.println(prefix + Strings.repeat(" ", indent) + str); } } }
5,565
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/providers/SingletonProvider.java
package com.netflix.governator.providers; import javax.inject.Provider; /** * Base class for {@link Providers} that which to enforce singleton semantics * for a type. * * Note that this class is needed since annotating a Provider with @Singleton * makes the Provider a singleton and NOT the type is it providing. So the * same Provider is returned when the Provider is injector the a new call to * get() is made whenever the type T is injected. * * @author elandau * * @param <T> */ public abstract class SingletonProvider<T> implements Provider<T> { private volatile T obj; private Object lock = new Object(); /** * Return the caches instance or call the internal {@link create} method * when creating the object for the first time. * */ @Override public final T get() { if (obj == null) { synchronized (lock) { if (obj == null) { obj = create(); } } } return obj; } /** * Implement the actual object creation here instead of in get() * @return */ protected abstract T create(); }
5,566
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice/lazy/FineGrainedLazySingleton.java
package com.netflix.governator.guice.lazy; import com.google.inject.ScopeAnnotation; import com.google.inject.Scopes; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Same as {@link LazySingleton} with the addition of allowing for more * concurrency. The various {@link Scopes#SINGLETON} based scopes have * a major concurrency restriction due to a blunt synchronization (see * the comment inside of the Guice code). This version synchronizes * on the object key and, thus, can construct multiple types of singletons * concurrently. * * @deprecated Use javax.inject.Singleton instead. FineGrainedLazySingleton is not needed * as of Guice4 which fixes the global lock issue. */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @ScopeAnnotation public @interface FineGrainedLazySingleton { }
5,567
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice/lazy/LazySingletonScopeImpl.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.Key; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.Scopes; import com.netflix.governator.internal.AbstractScope; /** * A Guice {@link Scope} that enables lazy singletons */ final class LazySingletonScopeImpl extends AbstractScope { @Override public <T> Provider<T> scope(Key<T> key, Provider<T> unscoped) { return Scopes.SINGLETON.scope(key, unscoped); } public boolean isSingletonScope() { return true; } }
5,568
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice/lazy/LazySingletonScope.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.Scope; /** * A singleton factory that returns a Guice {@link Scope} that enables lazy singletons */ public class LazySingletonScope { /** * Returns the scope * @return scope */ public static Scope get() { return instance; } private static final Scope instance = new LazySingletonScopeImpl(); private LazySingletonScope() { } }
5,569
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice/lazy/FineGrainedLazySingletonScope.java
package com.netflix.governator.guice.lazy; import com.google.inject.Scope; /** * A singleton factory that returns a Guice {@link Scope} that enables fine grained lazy singletons. * * @see FineGrainedLazySingleton * @deprecated Use javax.inject.Singleton instead. FineGrainedLazySingleton is not needed * as of Guice4 which fixes the global lock issue. */ @Deprecated public class FineGrainedLazySingletonScope { private static final Scope instance = new FineGrainedLazySingletonScopeImpl(); /** * Returns the scope * @return scope */ public static Scope get() { return instance; } }
5,570
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice/lazy/FineGrainedLazySingletonScopeImpl.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.common.collect.Maps; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.netflix.governator.internal.AbstractScope; import java.util.Map; /** * @deprecated Use javax.inject.Singleton instead. FineGrainedLazySingleton is not needed * as of Guice4 which fixes the global lock issue. */ @Deprecated class FineGrainedLazySingletonScopeImpl extends AbstractScope { private static final Object NULL = new Object(); private static final Map<Key<?>, LockRecord> locks = Maps.newHashMap(); private static final Class<?> circularProxyClazz; static { Class<?> clz; try { clz = Class.forName("com.google.inject.internal.CircularDependencyProxy"); } catch (ClassNotFoundException e) { clz = null; // discard exception. } circularProxyClazz = clz; } private static class LockRecord { private final Object lock = new Object(); private int useCount = 0; } public <T> Provider<T> scope(final Key<T> key, final Provider<T> creator) { return new Provider<T>() { /* * The lazily initialized singleton instance. Once set, this will either have type T or will * be equal to NULL. */ private volatile Object instance; // DCL on a volatile is safe as of Java 5, which we obviously require. @SuppressWarnings("DoubleCheckedLocking") public T get() { if ( instance == null ) { try { final Object lock = getLock(key); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (lock) { if ( instance == null ) { T provided = creator.get(); // don't remember proxies; these exist only to serve circular dependencies // Don't do an instanceof check to avoid referencing Guice internal classes. if (circularProxyClazz != null && circularProxyClazz.isInstance(provided)) { return provided; } Object providedOrSentinel = (provided == null) ? NULL : provided; if ( (instance != null) && (instance != providedOrSentinel) ) { throw new ProvisionException("Provider was reentrant while creating a singleton"); } instance = providedOrSentinel; } } } finally { releaseLock(key); } } Object localInstance = instance; // This is safe because instance has type T or is equal to NULL @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"}) T returnedInstance = (localInstance != NULL) ? (T) localInstance : null; return returnedInstance; } public String toString() { return String.format("%s[%s]", creator, instance); } }; } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private Object getLock(Key<?> key) { synchronized(locks) { LockRecord lock = locks.get(key); if ( lock == null ) { lock = new LockRecord(); locks.put(key, lock); } ++lock.useCount; return lock.lock; } } private void releaseLock(Key<?> key) { synchronized(locks) { LockRecord lock = locks.get(key); if ( lock != null ) { if ( --lock.useCount <= 0 ) { locks.remove(key); } } } } public boolean isSingletonScope() { return true; } @Override public String toString() { return "FineGrainedLazySingletonScope.SCOPE"; } }
5,571
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/guice/lazy/LazySingleton.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.ScopeAnnotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Scope annotation that marks a class as singleton that should NOT be * allocated eagerly */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @ScopeAnnotation public @interface LazySingleton { }
5,572
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/GovernatorFeatureSet.java
package com.netflix.governator.internal; import com.netflix.governator.GovernatorFeature; /** * Container of Governator features. */ public interface GovernatorFeatureSet { /** * @return Get the value of the feature or the default if none is set */ <T> T get(GovernatorFeature<T> feature); }
5,573
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/PostConstructLifecycleFeature.java
package com.netflix.governator.internal; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Supplier; import com.netflix.governator.LifecycleAction; import com.netflix.governator.LifecycleFeature; import com.netflix.governator.internal.JSR250LifecycleAction.ValidationMode; import com.netflix.governator.internal.TypeInspector.TypeVisitor; /** * Special LifecycleFeature to support @PostConstruct annotation processing. * Note that this feature is implicit in LifecycleModule and therefore does not * need to be added using the LifecycleFeature multibinding. * * @author elandau */ public final class PostConstructLifecycleFeature implements LifecycleFeature { private static final Logger LOG = LoggerFactory.getLogger(PostConstructLifecycleFeature.class); private final ValidationMode validationMode; public PostConstructLifecycleFeature(ValidationMode validationMode) { this.validationMode = validationMode; } @Override public List<LifecycleAction> getActionsForType(final Class<?> type) { return TypeInspector.accept(type, new PostConstructVisitor()); } @Override public String toString() { return "PostConstruct"; } private class PostConstructVisitor implements TypeVisitor, Supplier<List<LifecycleAction>> { private final Set<String> visitContext; private final LinkedList<LifecycleAction> typeActions; public PostConstructVisitor() { this.visitContext = new HashSet<>(); this.typeActions = new LinkedList<>(); } @Override public boolean visit(final Class<?> clazz) { return !clazz.isInterface(); } @Override public boolean visit(final Method method) { final String methodName = method.getName(); if (method.isAnnotationPresent(PostConstruct.class)) { if (!visitContext.contains(methodName)) { try { LifecycleAction postConstructAction = new JSR250LifecycleAction(PostConstruct.class, method, validationMode); LOG.debug("adding action {}", postConstructAction); this.typeActions.addFirst(postConstructAction); visitContext.add(methodName); } catch (IllegalArgumentException e) { LOG.info("ignoring @PostConstruct method {}.{}() - {}", method.getDeclaringClass().getName(), methodName, e.getMessage()); } } } else if (method.getReturnType() == Void.TYPE && method.getParameterTypes().length == 0 && !Modifier.isFinal(method.getModifiers())) { // method potentially overrides superclass method and annotations visitContext.add(methodName); } return true; } @Override public boolean visit(Field field) { return true; } @Override public List<LifecycleAction> get() { return Collections.unmodifiableList(typeActions); } } }
5,574
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/TypeInspector.java
package com.netflix.governator.internal; import java.lang.reflect.Field; import java.lang.reflect.Method; import com.google.common.base.Supplier; /** * Utility class for class, field and method-based introspection. * * @author elandau */ public class TypeInspector { /** * visitor interface for introspection processing */ public interface TypeVisitor { boolean visit(Field field); boolean visit(Method method); boolean visit(Class<?> clazz); } public static <R, V extends Supplier<R>&TypeVisitor> R accept(Class<?> type, V visitor) { accept(type, (TypeVisitor)visitor); return visitor.get(); } public static void accept(Class<?> type, TypeVisitor visitor) { if (_accept(type, visitor)) { // check these only once at the top level for (Class<?> iface : type.getInterfaces()) { if (!_accept(iface, visitor)) break; } } } private static boolean _accept(Class<?> type, TypeVisitor visitor) { if (type == null) { return false; } boolean continueVisit = visitor.visit(type); if (continueVisit) { for (final Field field : type.getDeclaredFields()) { continueVisit = visitor.visit(field); if (!continueVisit) break; } if (continueVisit) { for (final Method method : type.getDeclaredMethods()) { continueVisit = visitor.visit(method); if (!continueVisit) break; } if (continueVisit) { continueVisit = _accept(type.getSuperclass(), visitor); } } } return continueVisit; } }
5,575
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/PreDestroyMonitor.java
package com.netflix.governator.internal; import com.google.common.collect.MapMaker; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.Scopes; import com.google.inject.spi.BindingScopingVisitor; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.Dependency; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.util.Providers; import com.netflix.governator.LifecycleAction; import com.netflix.governator.ManagedInstanceAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; /** * Monitors managed instances and invokes cleanup actions when they become * unreferenced * * @author tcellucci * */ public class PreDestroyMonitor implements AutoCloseable { private static Logger LOGGER = LoggerFactory.getLogger(PreDestroyMonitor.class); private static class ScopeCleanupMarker { static final Key<ScopeCleanupMarker> MARKER_KEY = Key.get(ScopeCleanupMarker.class); // simple id uses identity equality private final Object id = new Object(); private final ScopeCleanupAction cleanupAction; public ScopeCleanupMarker(ReferenceQueue<ScopeCleanupMarker> markerReferenceQueue) { this.cleanupAction = new ScopeCleanupAction(this, markerReferenceQueue); } Object getId() { return id; } public ScopeCleanupAction getCleanupAction() { return cleanupAction; } } static final class ScopeCleaner implements Provider<ScopeCleanupMarker> { ConcurrentMap<Object, ScopeCleanupAction> scopedCleanupActions = new ConcurrentHashMap<>( BinaryConstant.I14_16384); ReferenceQueue<ScopeCleanupMarker> markerReferenceQueue = new ReferenceQueue<>(); final ExecutorService reqQueueExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setDaemon(true).setNameFormat("predestroy-monitor-%d").build()); final AtomicBoolean running = new AtomicBoolean(true); final ScopeCleanupMarker singletonMarker = get(); { this.reqQueueExecutor.submit(new ScopedCleanupWorker()); } @Override public ScopeCleanupMarker get() { ScopeCleanupMarker marker = new ScopeCleanupMarker(markerReferenceQueue); scopedCleanupActions.put(marker.getId(), marker.getCleanupAction()); return marker; } public boolean isRunning() { return running.get(); } public boolean close() throws Exception { boolean rv = running.compareAndSet(true, false); if (rv) { reqQueueExecutor.shutdown(); // executor to stop // process any remaining scoped cleanup actions List<ScopeCleanupAction> values = new ArrayList<>(scopedCleanupActions.values()); scopedCleanupActions.clear(); Collections.sort(values); for (Callable<Void> actions : values) { actions.call(); } // make sure executor thread really ended if (!reqQueueExecutor.awaitTermination(90, TimeUnit.SECONDS)) { LOGGER.error("internal executor still active; shutting down now"); reqQueueExecutor.shutdownNow(); } markerReferenceQueue = null; } return rv; } /** * Processes unreferenced markers from the referenceQueue, until the 'running' * flag is false or interrupted * */ final class ScopedCleanupWorker implements Runnable { public void run() { try { while (running.get()) { Reference<? extends ScopeCleanupMarker> ref = markerReferenceQueue.remove(1000); if (ref != null && ref instanceof ScopeCleanupAction) { Object markerKey = ((ScopeCleanupAction) ref).getId(); ScopeCleanupAction cleanupAction = scopedCleanupActions.remove(markerKey); if (cleanupAction != null) { cleanupAction.call(); } } } LOGGER.info("PreDestroyMonitor.ScopedCleanupWorker is exiting"); } catch (InterruptedException e) { LOGGER.info("PreDestroyMonitor.ScopedCleanupWorker is exiting due to thread interrupt"); Thread.currentThread().interrupt(); // clear interrupted status } } } } private ConcurrentMap<Object, UnscopedCleanupAction> cleanupActions = new MapMaker().weakKeys().concurrencyLevel(256).makeMap(); private ScopeCleaner scopeCleaner = new ScopeCleaner(); private Map<Class<? extends Annotation>, Scope> scopeBindings; public PreDestroyMonitor(Map<Class<? extends Annotation>, Scope> scopeBindings) { this.scopeBindings = new HashMap<>(scopeBindings); } public <T> boolean register(T destroyableInstance, Binding<T> binding, Iterable<LifecycleAction> action) { if (scopeCleaner.isRunning()) { boolean visitNoScope = Optional .ofNullable(binding.acceptTargetVisitor(new ProviderInstanceBindingVisitor<>())).orElse(true); return binding.acceptScopingVisitor( new ManagedInstanceScopingVisitor(destroyableInstance, binding.getSource(), action, visitNoScope)); } return false; } /* * compatibility-mode - scope is assumed to be eager singleton */ public <T> boolean register(T destroyableInstance, Object context, Iterable<LifecycleAction> action) { return scopeCleaner.isRunning() ? new ManagedInstanceScopingVisitor(destroyableInstance, context, action).visitEagerSingleton() : false; } /** * allows late-binding of scopes to PreDestroyMonitor, useful if more than one * Injector contributes scope bindings * * @param bindings additional annotation-to-scope bindings to add */ public void addScopeBindings(Map<Class<? extends Annotation>, Scope> bindings) { if (scopeCleaner.isRunning()) { scopeBindings.putAll(bindings); } } /** * final cleanup of managed instances if any */ @Override public void close() throws Exception { if (scopeCleaner.close()) { // executor thread to exit processing loop LOGGER.info("closing PreDestroyMonitor..."); List<Map.Entry<Object, UnscopedCleanupAction>> actions = new ArrayList<>(cleanupActions.entrySet()); if (actions.size() > 0) { LOGGER.warn("invoking predestroy action for {} unscoped instances", actions.size()); actions.stream().map(Map.Entry::getValue).collect( Collectors.groupingBy(UnscopedCleanupAction::getContext, Collectors.counting())).forEach((source, count)->{ LOGGER.warn(" including {} objects from source '{}'", count, source); }); } actions.stream().sorted(Map.Entry.comparingByValue()).forEach(action->{ Optional.ofNullable(action.getKey()).ifPresent(obj->action.getValue().call(obj)); }); actions.clear(); cleanupActions.clear(); scopeBindings.clear(); scopeBindings = Collections.emptyMap(); } else { LOGGER.warn("PreDestroyMonitor.close() invoked but instance is not running"); } } /** * visits bindingScope of managed instance to set up an appropriate strategy for * cleanup, adding actions to either the scopedCleanupActions map or * cleanupActions list. Returns true if cleanup actions were added, false if no * cleanup strategy was selected. * */ private final class ManagedInstanceScopingVisitor implements BindingScopingVisitor<Boolean> { private final Object injectee; private final Object context; private final Iterable<LifecycleAction> lifecycleActions; private final boolean processNoScope; private ManagedInstanceScopingVisitor(Object injectee, Object context, Iterable<LifecycleAction> lifecycleActions) { this(injectee, context, lifecycleActions, true); } private ManagedInstanceScopingVisitor(Object injectee, Object context, Iterable<LifecycleAction> lifecycleActions, boolean processNoScope) { this.injectee = injectee; this.context = context; this.lifecycleActions = lifecycleActions; this.processNoScope = processNoScope; } /* * handle eager singletons same as singletons for cleanup purposes. * */ @Override public Boolean visitEagerSingleton() { return visitScope(Scopes.SINGLETON); } /* * use ScopeCleanupMarker dereferencing strategy to detect scope closure, add * new entry to scopedCleanupActions map * */ @Override public Boolean visitScope(Scope scope) { final Provider<ScopeCleanupMarker> scopedMarkerProvider; if (scope.equals(Scopes.SINGLETON) || (scope instanceof AbstractScope && ((AbstractScope) scope).isSingletonScope())) { scopedMarkerProvider = Providers.of(scopeCleaner.singletonMarker); } else if (scope.equals(Scopes.NO_SCOPE)) { return visitNoScoping(); } else { scopedMarkerProvider = scope.scope(ScopeCleanupMarker.MARKER_KEY, scopeCleaner); } ScopeCleanupMarker marker = scopedMarkerProvider.get(); marker.getCleanupAction().add(scopedMarkerProvider, new ManagedInstanceAction(injectee, lifecycleActions)); return true; } /* * lookup Scope by annotation, then delegate to visitScope() * */ @Override public Boolean visitScopeAnnotation(final Class<? extends Annotation> scopeAnnotation) { Scope scope = scopeBindings.get(scopeAnnotation); boolean rv; if (scope != null) { rv = visitScope(scope); } else { LOGGER.warn("no scope binding found for annotation " + scopeAnnotation.getName()); rv = false; } return rv; } /** * handle unscoped instances here using a 'best effort' strategy to clean up these instances iff they * still exist when the PreDestroyMonitor is closed. */ @Override public Boolean visitNoScoping() { if (processNoScope) { cleanupActions.computeIfAbsent(injectee, i->{ LOGGER.debug("predestroy action registered for unscoped instance {} from {}", i, context); return new UnscopedCleanupAction(context, lifecycleActions); }); } return true; } } private static final class UnscopedCleanupAction implements LifecycleAction, Comparable<UnscopedCleanupAction> { private volatile static long instanceCounter = 0; private final long ordinal; private final Object context; private final Iterable<LifecycleAction> lifecycleActions; public UnscopedCleanupAction(Object context, Iterable<LifecycleAction> lifecycleActions) { this.context = context; this.lifecycleActions = lifecycleActions; this.ordinal = instanceCounter++; } @Override public void call(Object obj) { lifecycleActions.forEach(action -> { try { action.call(obj); } catch (Exception e) { LOGGER.error("PreDestroy call failed for {} from {}", action, context, e); } }); } @Override public int compareTo(UnscopedCleanupAction o) { // invert so higher numbers are at the beginning of the list return Long.compare(o.ordinal, ordinal); } public Object getContext() { return context; } } /** * Runnable that weakly references a scopeCleanupMarker and strongly references * a list of delegate runnables. When the marker is unreferenced, delegates will * be invoked in the reverse order of addition. */ private static final class ScopeCleanupAction extends WeakReference<ScopeCleanupMarker> implements Callable<Void>, Comparable<ScopeCleanupAction> { private volatile static long instanceCounter = 0; private final Object id; private final long ordinal; private Deque<Object[]> delegates = new ConcurrentLinkedDeque<>(); private final AtomicBoolean complete = new AtomicBoolean(false); public ScopeCleanupAction(ScopeCleanupMarker marker, ReferenceQueue<ScopeCleanupMarker> refQueue) { super(marker, refQueue); this.id = marker.getId(); this.ordinal = instanceCounter++; } public Object getId() { return id; } public void add(Provider<ScopeCleanupMarker> scopeProvider, Callable<Void> action) { if (!complete.get()) { delegates.addFirst(new Object[] { action, scopeProvider }); // add first } } @SuppressWarnings("unchecked") @Override public Void call() { if (complete.compareAndSet(false, true) && delegates != null) { for (Object[] r : delegates) { try { ((Callable<Void>) r[0]).call(); } catch (Exception e) { LOGGER.error("PreDestroy call failed for " + r, e); } } delegates.clear(); clear(); } return null; } @Override public int compareTo(ScopeCleanupAction o) { return Long.compare(ordinal, o.ordinal); } } private static class ProviderInstanceBindingVisitor<T> extends DefaultBindingTargetVisitor<T, Boolean> { @Override public Boolean visit(ProviderInstanceBinding<? extends T> providerInstanceBinding) { Set<Dependency<?>> bindingDependencies = providerInstanceBinding.getDependencies(); if (bindingDependencies.size() == 1) { Dependency<?> parentDep = bindingDependencies.iterator().next(); if (parentDep.getParameterIndex() == -1) { if (parentDep.getKey().getTypeLiteral() .equals(providerInstanceBinding.getKey().getTypeLiteral())) { /* * this destroyableInstance was obtained from a Provider that _implicitly_ * depends only on another binding's destroyableInstance of the exact same type * (i.e., dependency is not an injected parameter). Do not add new lifecycle * method handler for this destroyableInstance if it is in 'no_scope' */ return false; } } } return true; } } }
5,576
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/AbstractScope.java
package com.netflix.governator.internal; import com.google.inject.Scope; public abstract class AbstractScope implements Scope { /** * @return Return true if this scope uses Guice's Scopes.SINGLETON as its underlying scope */ public boolean isSingletonScope() { return false; } }
5,577
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/DefaultPropertySource.java
package com.netflix.governator.internal; import javax.inject.Singleton; import com.netflix.governator.AbstractPropertySource; import com.netflix.governator.annotations.SuppressLifecycleUninitialized; /** * PropertySource based on system and environment properties with * system properties having precedence. * * @author elandau * */ @Singleton @SuppressLifecycleUninitialized public final class DefaultPropertySource extends AbstractPropertySource { @Override public String get(String key) { return get(key, (String)null); } @Override public String get(String key, String defaultValue) { String value = System.getProperty(key); if (value == null) { value = System.getenv(key); if (value == null) return defaultValue; } return value; } @Override public boolean hasProperty(String key) { return get(key, (String)null) != null; } }
5,578
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/PreDestroyLifecycleFeature.java
package com.netflix.governator.internal; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import javax.annotation.PreDestroy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Supplier; import com.netflix.governator.LifecycleAction; import com.netflix.governator.LifecycleFeature; import com.netflix.governator.internal.JSR250LifecycleAction.ValidationMode; import com.netflix.governator.internal.TypeInspector.TypeVisitor; /** * Special LifecycleFeature to support @PreDestroy annotation processing and * java.lang.AutoCloseable detection. Note that this feature is implicit in * LifecycleModule and therefore does not need to be added using the * LifecycleFeature multibinding. * * @author elandau */ public final class PreDestroyLifecycleFeature implements LifecycleFeature { private static final Logger LOG = LoggerFactory.getLogger(PreDestroyLifecycleFeature.class); private final ValidationMode validationMode; public PreDestroyLifecycleFeature(ValidationMode validationMode) { this.validationMode = validationMode; } @Override public List<LifecycleAction> getActionsForType(final Class<?> type) { return TypeInspector.accept(type, new PreDestroyVisitor()); } @Override public String toString() { return "PreDestroy"; } private class PreDestroyVisitor implements TypeVisitor, Supplier<List<LifecycleAction>> { private Set<String> visitContext = new HashSet<>(); private List<LifecycleAction> typeActions = new ArrayList<>(); @Override public boolean visit(final Class<?> clazz) { boolean continueVisit = !clazz.isInterface(); if (continueVisit && AutoCloseable.class.isAssignableFrom(clazz) && !ExecutorService.class.isAssignableFrom(clazz)) { AutoCloseableLifecycleAction closeableAction = new AutoCloseableLifecycleAction( clazz.asSubclass(AutoCloseable.class)); LOG.debug("adding action {}", closeableAction); typeActions.add(closeableAction); continueVisit = false; } return continueVisit; } @Override public boolean visit(final Method method) { final String methodName = method.getName(); if (method.isAnnotationPresent(PreDestroy.class)) { if (!visitContext.contains(methodName)) { try { LifecycleAction destroyAction = new JSR250LifecycleAction(PreDestroy.class, method, validationMode); LOG.debug("adding action {}", destroyAction); typeActions.add(destroyAction); visitContext.add(methodName); } catch (IllegalArgumentException e) { LOG.info("ignoring @PreDestroy method {}.{}() - {}", method.getDeclaringClass().getName(), methodName, e.getMessage()); } } } else if (method.getReturnType() == Void.TYPE && method.getParameterTypes().length == 0 && !Modifier.isFinal(method.getModifiers())) { // method potentially overrides superclass method and annotations visitContext.add(methodName); } return true; } @Override public boolean visit(Field field) { return true; } @Override public List<LifecycleAction> get() { return Collections.unmodifiableList(typeActions); } } private static final class AutoCloseableLifecycleAction implements LifecycleAction { private final String description; private AutoCloseableLifecycleAction(Class<? extends AutoCloseable> clazz) { this.description = new StringBuilder().append("AutoCloseable@").append(System.identityHashCode(this)).append("[").append(clazz.getName()).append(".") .append("close()").append("]").toString(); } @Override public void call(Object obj) throws Exception { LOG.info("calling action {}", description); AutoCloseable.class.cast(obj).close(); } @Override public String toString() { return description; } } }
5,579
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/BinaryConstant.java
package com.netflix.governator.internal; public enum BinaryConstant { B0_1, B1_2, B2_4, B3_8, B4_16, B5_32, B6_64, B7_128, B8_256, B9_512, B10_1024, B11_2048, B12_4096, B13_8192, B14_16384, B15_32768, B16_65536, B17_131072, B18_262144, B19_524288, B20_1048576, B21_2097152, B22_4194304, B23_8388608, B24_16777216, B25_33554432, B26_67108864, B27_134217728, B28_268435456, B29_536870912, B30_1073741824, B31_2147483648, B32_4294967296, B33_8589934592, B34_17179869184, B35_34359738368, B36_68719476736, B37_137438953472, B38_274877906944, B39_549755813888, B40_1099511627776, B41_2199023255552, B42_4398046511104, B43_8796093022208, B44_17592186044416, B45_35184372088832, B46_70368744177664, B47_140737488355328, B48_281474976710656, B49_562949953421312, B50_1125899906842624, B51_2251799813685248, B52_4503599627370496, B53_9007199254740992, B54_18014398509481984, B55_36028797018963968, B56_72057594037927936, B57_144115188075855872, B58_288230376151711744, B59_576460752303423488, B60_1152921504606846976, B61_2305843009213693952, B62_4611686018427387904, B63_N9223372036854775808; private final long value; private final String msg; private BinaryConstant() { this.value = 1L << ordinal(); this.msg = name() + "(2^" + ordinal() + "=" + value + ")"; } public String toString() { return msg; } public static final int I0_1 = 1; public static final int I1_2 = 2; public static final int I2_4 = 4; public static final int I3_8 = 8; public static final int I4_16 = 16; public static final int I5_32 = 32; public static final int I6_64 = 64; public static final int I7_128 = 128; public static final int I8_256 = 256; public static final int I9_512 = 512; public static final int I10_1024 = 1024; public static final int I11_2048 = 2048; public static final int I12_4096 = 4096; public static final int I13_8192 = 8192; public static final int I14_16384 = 16384; public static final int I15_32768 = 32768; public static final int I16_65536 = 65536; public static final int I17_131072 = 131072; public static final int I18_262144 = 262144; public static final int I19_524288 = 524288; public static final int I20_1048576 = 1048576; public static final int I21_2097152 = 2097152; public static final int I22_4194304 = 4194304; public static final int I23_8388608 = 8388608; public static final int I24_16777216 = 16777216; public static final int I25_33554432 = 33554432; public static final int I26_67108864 = 67108864; public static final int I27_134217728 = 134217728; public static final int I28_268435456 = 268435456; public static final int I29_536870912 = 536870912; public static final int I30_1073741824 = 1073741824; public static final int I31_2147483648 = -2147483648; public static final long L0_1 = 1L; public static final long L1_2 = 2L; public static final long L2_4 = 4L; public static final long L3_8 = 8L; public static final long L4_16 = 16L; public static final long L5_32 = 32L; public static final long L6_64 = 64L; public static final long L7_128 = 128L; public static final long L8_256 = 256L; public static final long L9_512 = 512L; public static final long L10_1024 = 1024L; public static final long L11_2048 = 2048L; public static final long L12_4096 = 4096L; public static final long L13_8192 = 8192L; public static final long L14_16384 = 16384L; public static final long L15_32768 = 32768L; public static final long L16_65536 = 65536L; public static final long L17_131072 = 131072L; public static final long L18_262144 = 262144L; public static final long L19_524288 = 524288L; public static final long L20_1048576 = 1048576L; public static final long L21_2097152 = 2097152L; public static final long L22_4194304 = 4194304L; public static final long L23_8388608 = 8388608L; public static final long L24_16777216 = 16777216L; public static final long L25_33554432 = 33554432L; public static final long L26_67108864 = 67108864L; public static final long L27_134217728 = 134217728L; public static final long L28_268435456 = 268435456L; public static final long L29_536870912 = 536870912L; public static final long L30_1073741824 = 1073741824L; public static final long L31_2147483648 = 2147483648L; public static final long L32_4294967296 = 4294967296L; public static final long L33_8589934592 = 8589934592L; public static final long L34_17179869184 = 17179869184L; public static final long L35_34359738368 = 34359738368L; public static final long L36_68719476736 = 68719476736L; public static final long L37_137438953472 = 137438953472L; public static final long L38_274877906944 = 274877906944L; public static final long L39_549755813888 = 549755813888L; public static final long L40_1099511627776 = 1099511627776L; public static final long L41_2199023255552 = 2199023255552L; public static final long L42_4398046511104 = 4398046511104L; public static final long L43_8796093022208 = 8796093022208L; public static final long L44_17592186044416 = 17592186044416L; public static final long L45_35184372088832 = 35184372088832L; public static final long L46_70368744177664 = 70368744177664L; public static final long L47_140737488355328 = 140737488355328L; public static final long L48_281474976710656 = 281474976710656L; public static final long L49_562949953421312 = 562949953421312L; public static final long L50_1125899906842624 = 1125899906842624L; public static final long L51_2251799813685248 = 2251799813685248L; public static final long L52_4503599627370496 = 4503599627370496L; public static final long L53_9007199254740992 = 9007199254740992L; public static final long L54_18014398509481984 = 18014398509481984L; public static final long L55_36028797018963968 = 36028797018963968L; public static final long L56_72057594037927936 = 72057594037927936L; public static final long L57_144115188075855872 = 144115188075855872L; public static final long L58_288230376151711744 = 288230376151711744L; public static final long L59_576460752303423488 = 576460752303423488L; public static final long L60_1152921504606846976 = 1152921504606846976L; public static final long L61_2305843009213693952 = 2305843009213693952L; public static final long L62_4611686018427387904 = 4611686018427387904L; public static final long L63_N9223372036854775808 = -9223372036854775808L; }
5,580
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/ModulesEx.java
package com.netflix.governator.internal; import com.google.inject.AbstractModule; import com.google.inject.Module; public final class ModulesEx { private static final Module EMPTY_MODULE = new AbstractModule() { @Override protected void configure() { } }; public static Module emptyModule() { return EMPTY_MODULE; } public static Module fromEagerSingleton(final Class<?> type) { return new AbstractModule() { @Override protected void configure() { bind(type).asEagerSingleton(); } }; } public static <T> Module fromInstance(final T object) { return new AbstractModule() { @Override protected void configure() { bind((Class<T>)object.getClass()).toInstance(object); this.requestInjection(object); } }; } }
5,581
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/JSR250LifecycleAction.java
package com.netflix.governator.internal; import java.lang.annotation.Annotation; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.governator.LifecycleAction; public class JSR250LifecycleAction implements LifecycleAction { private static final Lookup METHOD_HANDLE_LOOKUP = MethodHandles.lookup(); public enum ValidationMode { STRICT, LAX } private static final Logger LOG = LoggerFactory.getLogger(JSR250LifecycleAction.class); private final Method method; private final String description; private MethodHandle mh; public JSR250LifecycleAction(Class<? extends Annotation> annotationClass, Method method) { this(annotationClass, method, ValidationMode.STRICT); } public JSR250LifecycleAction(Class<? extends Annotation> annotationClass, Method method, ValidationMode validationMode) { validateAnnotationUsage(annotationClass, method, validationMode); if (!method.isAccessible()) { method.setAccessible(true); } this.method = method; try { this.mh = METHOD_HANDLE_LOOKUP.unreflect(method); } catch (IllegalAccessException e) { // that's ok we'll use reflected method.invoke() } this.description = String.format("%s@%d[%s.%s()]", annotationClass.getSimpleName(), System.identityHashCode(this), method.getDeclaringClass().getSimpleName(), method.getName()); } private void validateAnnotationUsage(Class<? extends Annotation> annotationClass, Method method, ValidationMode validationMode) { LOG.debug("method validationMode is " + validationMode); if (Modifier.isStatic(method.getModifiers())) { throw new IllegalArgumentException("method must not be static"); } else if (method.getParameterCount() > 0) { throw new IllegalArgumentException("method parameter count must be zero"); } else if (Void.TYPE != method.getReturnType() && validationMode == ValidationMode.STRICT) { throw new IllegalArgumentException("method must have void return type"); } else if (method.getExceptionTypes().length > 0 && validationMode == ValidationMode.STRICT) { for (Class<?> e : method.getExceptionTypes()) { if (!RuntimeException.class.isAssignableFrom(e)) { throw new IllegalArgumentException( "method must must not throw checked exception: " + e.getSimpleName()); } } } else { int annotationCount = 0; for (Method m : method.getDeclaringClass().getDeclaredMethods()) { if (m.isAnnotationPresent(annotationClass)) { annotationCount++; } } if (annotationCount > 1 && validationMode == ValidationMode.STRICT) { throw new IllegalArgumentException( "declaring class must not contain multiple @" + annotationClass.getSimpleName() + " methods"); } } } @Override public void call(Object obj) throws InvocationTargetException { LOG.debug("calling action {} on instance {}", description, obj); if (mh != null) { try { mh.invoke(obj); } catch( Throwable throwable) { if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else if (throwable instanceof Error) { throw (Error) throwable; } throw new InvocationTargetException(throwable, "invoke-dynamic"); } } else { try { method.invoke(obj); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } throw ite; } catch (Throwable e) { // extremely unlikely, as constructor sets the method to 'accessible' and validates that it takes no parameters throw new RuntimeException("unexpected exception in method invocation", e); } } } @Override public String toString() { return description; } }
5,582
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/ElementsEx.java
package com.netflix.governator.internal; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.inject.Binding; import com.google.inject.ImplementedBy; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.ProvidedBy; import com.google.inject.TypeLiteral; import com.google.inject.spi.ConstructorBinding; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Dependency; import com.google.inject.spi.Element; import com.google.inject.spi.ElementSource; import com.google.inject.spi.InjectionPoint; import com.google.inject.spi.InjectionRequest; import com.google.inject.spi.LinkedKeyBinding; import com.google.inject.spi.ProviderBinding; import com.google.inject.spi.ProviderKeyBinding; import com.google.inject.spi.ProviderLookup; import com.google.inject.spi.StaticInjectionRequest; import com.google.inject.spi.UntargettedBinding; final class ElementsEx { /** * @param elements List of elements * @return List all Module classes that were involved in setting up bindings for the list of Elements */ public static List<String> getAllSourceModules(List<Element> elements) { List<String> names = new ArrayList<>(); for (Element element : elements) { if (element.getSource().getClass().isAssignableFrom(ElementSource.class)) { ElementSource source = (ElementSource)element.getSource(); names.addAll(source.getModuleClassNames()); } } return names; } /** * Discover all unbound keys (excluding JIT enabled keys) that Guice will not be able to create. * This set of keys can then be fed into an autobinder * * @param elements * @return Set of interfaces or abstract classes for which there is no binding */ public static Set<Key<?>> getAllUnboundKeys(List<Element> elements) { final Set<Key<?>> boundKeys = new HashSet<>(); for (Element element : elements) { element.acceptVisitor(new DefaultElementVisitor<Void>() { public <T> Void visit(Binding<T> binding) { boundKeys.add(binding.getKey()); return null; } }); } final Set<Key<?>> foundKeys = new HashSet<>(); for (Element element : elements) { element.acceptVisitor(new DefaultElementVisitor<Void>() { @Override public <T> Void visit(Binding<T> binding) { binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, Void>() { @Override public Void visit(ProviderKeyBinding<? extends T> binding) { addFoundKeys(getUnboundDirectDependencies(binding.getProviderKey().getTypeLiteral(), boundKeys)); return null; } @Override public Void visit(LinkedKeyBinding<? extends T> binding) { if (!boundKeys.contains(binding.getLinkedKey())) { addFoundKeys(getUnboundDirectDependencies(binding.getLinkedKey().getTypeLiteral(), boundKeys)); } return null; } @Override public Void visit(UntargettedBinding<? extends T> binding) { addFoundKeys(getUnboundDirectDependencies(binding.getKey().getTypeLiteral(), boundKeys)); return null; } @Override public Void visit(ConstructorBinding<? extends T> binding) { addFoundKeys(getUnboundDirectDependencies(binding.getInjectableMembers(), boundKeys)); addFoundKeys(getUnboundDirectDependencies(binding.getDependencies(), boundKeys)); return null; } @Override public Void visit(ProviderBinding<? extends T> binding) { addFoundKeys(getUnboundDirectDependencies(binding.getProvidedKey().getTypeLiteral(), boundKeys)); return null; } private void addFoundKeys(Set<Key<?>> keys) { foundKeys.addAll(keys); } }); return null; } /** * Visit a request to inject the instance fields and methods of an instance. */ @Override public Void visit(InjectionRequest<?> request) { for (InjectionPoint ip : request.getInjectionPoints()) { for (Dependency<?> dep : ip.getDependencies()) { foundKeys.addAll(getUnboundDirectDependencies(dep.getKey().getTypeLiteral(), boundKeys)); } } return null; } /** * Visit a request to inject the static fields and methods of type. */ @Override public Void visit(StaticInjectionRequest request) { for (InjectionPoint ip : request.getInjectionPoints()) { for (Dependency<?> dep : ip.getDependencies()) { foundKeys.addAll(getUnboundDirectDependencies(dep.getKey().getTypeLiteral(), boundKeys)); } } return null; } /** * Visit a lookup of the provider for a type. */ @Override public <T> Void visit(ProviderLookup<T> lookup) { foundKeys.add(lookup.getDependency().getKey()); return null; } }); } // Recursively look at the final list of unbound keys to further discover dependencies // and exclude keys that may be instantiated using the JIT for (Key<?> key : foundKeys) { discoverDependencies(key, boundKeys); } foundKeys.removeAll(boundKeys); foundKeys.remove(Key.get(Injector.class)); return foundKeys; } static void discoverDependencies(Key<?> key, Set<Key<?>> boundKeys) { if (boundKeys.contains(key)) { return; } Class<?> rawType = key.getTypeLiteral().getRawType(); if (rawType.isInterface() || Modifier.isAbstract(rawType.getModifiers())) { ImplementedBy implementedBy = rawType.getAnnotation(ImplementedBy.class); if (implementedBy != null) { boundKeys.add(key); discoverDependencies(key, boundKeys); return; } ProvidedBy providedBy = rawType.getAnnotation(ProvidedBy.class); if (providedBy != null) { boundKeys.add(key); discoverDependencies(key, boundKeys); return; } } else { boundKeys.add(key); for (Key<?> dep : getUnboundDirectDependencies(key.getTypeLiteral(), boundKeys)) { discoverDependencies(dep, boundKeys); } } } static Set<Key<?>> getUnboundDirectDependencies(TypeLiteral<?> type, Set<Key<?>> boundKeys) { if (type.getRawType().isInterface()) { return Collections.emptySet(); } Set<Key<?>> keys = new HashSet<>(); keys.addAll(getUnboundDirectDependencies(InjectionPoint.forConstructorOf(type), boundKeys)); keys.addAll(getUnboundDirectDependencies(InjectionPoint.forInstanceMethodsAndFields(type), boundKeys)); return keys; } static Set<Key<?>> getUnboundDirectDependencies(Set<Dependency<?>> dependencies, Set<Key<?>> boundKeys) { Set<Key<?>> unboundKeys = new HashSet<>(); for (Dependency<?> dep : dependencies) { for (Dependency<?> dep2 : dep.getInjectionPoint().getDependencies()) { if (!boundKeys.contains(dep2.getKey())) { unboundKeys.add(dep2.getKey()); } } } return unboundKeys; } static Set<Key<?>> getUnboundDirectDependencies(InjectionPoint ip, Set<Key<?>> boundKeys) { Set<Key<?>> unboundKeys = new HashSet<>(); for (Dependency<?> dep : ip.getDependencies()) { if (!boundKeys.contains(dep.getKey())) { unboundKeys.add(dep.getKey()); } } return unboundKeys; } static Set<Key<?>> getUnboundDirectDependencies(Collection<InjectionPoint> ips, Set<Key<?>> boundKeys) { Set<Key<?>> unboundKeys = new HashSet<>(); for (InjectionPoint ip : ips) { for (Dependency<?> dep : ip.getDependencies()) { if (!boundKeys.contains(dep.getKey())) { unboundKeys.add(dep.getKey()); } } } return unboundKeys; } }
5,583
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/scanner/DirectoryClassFilter.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.internal.scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Locates files within a directory-based classpath resource that are contained with a particular base package. */ public class DirectoryClassFilter { private static final Logger LOG = LoggerFactory.getLogger(DirectoryClassFilter.class); private final ClassLoader loader; public DirectoryClassFilter(ClassLoader loader) { this.loader = loader; } public List<String> filesInPackage(URL url, String basePackage) { File dir = ClasspathUrlDecoder.toFile(url); List<String> classNames = new ArrayList<String>(); if (dir.isDirectory()) { scanDir(dir, classNames, (basePackage.length() > 0) ? (basePackage + ".") : ""); } return classNames; } public InputStream bytecodeOf(String className) throws IOException { int pos = className.indexOf("<"); if (pos > -1) { className = className.substring(0, pos); } pos = className.indexOf(">"); if (pos > -1) { className = className.substring(0, pos); } if (!className.endsWith(".class")) { className = className.replace('.', '/') + ".class"; } URL resource = loader.getResource(className); if ( resource != null ) { return new BufferedInputStream(resource.openStream()); } throw new IOException("Unable to open class with name " + className + " because the class loader was unable to locate it"); } private void scanDir(File dir, List<String> classNames, String packageName) { LOG.debug("Scanning dir {}", packageName); File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { scanDir(file, classNames, packageName + file.getName() + "."); } else if (file.getName().endsWith(".class")) { String name = file.getName(); name = name.replaceFirst(".class$", ""); if (name.contains(".")) { continue; } classNames.add(packageName + name); } } } }
5,584
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/internal/scanner/ClasspathUrlDecoder.java
package com.netflix.governator.internal.scanner; import java.io.ByteArrayOutputStream; import java.io.File; import java.net.URL; public class ClasspathUrlDecoder { public static File toFile(URL url) { if ( !"file".equals(url.getProtocol()) && !"vfs".equals(url.getProtocol()) ) { throw new IllegalArgumentException("not a file or vfs url: " + url); } String path = url.getFile(); File dir = new File(decode(path)); if (dir.getName().equals("META-INF")) { dir = dir.getParentFile(); // Scrape "META-INF" off } return dir; } public static String decode(String fileName) { if ( fileName.indexOf('%') == -1 ) { return fileName; } StringBuilder result = new StringBuilder(fileName.length()); ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int i = 0; i < fileName.length();) { char c = fileName.charAt(i); if (c == '%') { out.reset(); do { if (i + 2 >= fileName.length()) { throw new IllegalArgumentException("Incomplete % sequence at: " + i); } int d1 = Character.digit(fileName.charAt(i + 1), 16); int d2 = Character.digit(fileName.charAt(i + 2), 16); if (d1 == -1 || d2 == -1) { throw new IllegalArgumentException("Invalid % sequence (" + fileName.substring(i, i + 3) + ") at: " + String.valueOf(i)); } out.write((byte) ((d1 << 4) + d2)); i += 3; } while (i < fileName.length() && fileName.charAt(i) == '%'); result.append(out.toString()); continue; } else { result.append(c); } i++; } return result.toString(); } }
5,585
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/spi/PropertySource.java
package com.netflix.governator.spi; import com.google.inject.ImplementedBy; import com.netflix.governator.PropertiesPropertySource; import com.netflix.governator.internal.DefaultPropertySource; /** * Very simple config interface to be used by Conditional to gain access * to any type of configuration. * * @see PropertiesPropertySource */ @ImplementedBy(DefaultPropertySource.class) public interface PropertySource { /** * Get the value of a property or null if not found * * @param key Name of property to fetch * @return Value or null if not found */ public String get(String key); /** * Get the value of a property or default if not found * * @param key Name of property to fetch * @param defaultValue * @return Value or defaultValue if not found */ public String get(String key, String defaultValue); /** * Get a property value of a specific type * * @param key Name of property to fetch * @param type Type of value requested * @return Value of the request type or null if not found */ public <T> T get(String key, Class<T> type); /** * Get a property value of a specific type while returning a * default value if the property is not set. * * @param key Name of property to fetch * @param type Type of value requested * @param defaultValue Default value to return if key not found * @return Value or defaultValue if not found */ public <T> T get(String key, Class<T> type, T defaultValue); /** * Determine if the PropertySource contains the specified property key */ boolean hasProperty(String key); }
5,586
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/spi/AnnotatedClassScanner.java
package com.netflix.governator.spi; import com.google.inject.Binder; import com.google.inject.Key; import java.lang.annotation.Annotation; /** * @see ScanningModuleBuidler */ public interface AnnotatedClassScanner { /** * @return Annotation class handled by this scanner */ Class<? extends Annotation> annotationClass(); /** * Apply the found class on the provided binder. This can result in 0 or more bindings being * created * * @param binder The binder on which to create new bindings * @param annotation The found annotation * @param key Key for the found class */ <T> void applyTo(Binder binder, Annotation annotation, Key<T> key); }
5,587
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/spi/ModuleListTransformer.java
package com.netflix.governator.spi; import java.util.List; import com.google.inject.Module; /** * Module transformers are used to modify the final list of modules and return a * modified or augmented list of modules which may included additional or removed * bindings. * * ModuleTransfomers can be used to do the following types of functionality, * 1. Remove unwanted bindings * 2. Auto add non-existent bindings * 3. Warn on dangerous bindings like toInstance() and static injection. */ public interface ModuleListTransformer { /** * Using the provided list of modules (and bindings) return a new augments list * which may included additional bindings and modules. * * @param modules * @return New list of modules. Can be the old list. */ List<Module> transform(List<Module> modules); }
5,588
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/spi/InjectorCreator.java
package com.netflix.governator.spi; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjectorCreator; import com.netflix.governator.SimpleInjectorCreator; /** * Contract that makes Guice injector creation a pluggable strategy and allows for typed * extensions to the Injector within the context of the strategy. An InjectorCreator * may also implement post injector creation operations such as calling {@link LifecycleListener}s * prior to returning form createInjector(). * * InjectorCreator can be used directly with a module, * * <code> new LifecycleInjectorCreator().createInjector(new MyApplicationModule()); * </code> * * Alternatively, InjectorCreator can be used in conjunction with the {@link InjectorBuilder} DSL * * <code> LifecycleInjector injector = InjectorBuilder .fromModule(new MyApplicationModule()) .overrideWith(new MyApplicationOverrideModule()) .combineWith(new AdditionalModule() .createInjector(new LifecycleInjectorCreator()); } * </code> * * See {@link SimpleInjectorCreator} or {@link LifecycleInjectorCreator} */ public interface InjectorCreator<I extends Injector> { I createInjector(Stage stage, Module module); }
5,589
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/spi/ModuleTransformer.java
package com.netflix.governator.spi; import com.google.inject.Module; /** * Mapping function from one module to another. A transformer could perform operations * such as logging, removing dependencies or auto-generating bindings. */ public interface ModuleTransformer { Module transform(Module module); }
5,590
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/event/ApplicationEventModule.java
package com.netflix.governator.event; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.inject.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.TypeLiteral; import com.google.inject.matcher.Matchers; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.ProvisionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import com.netflix.governator.event.guava.GuavaApplicationEventModule; /** * Adds support for passing {@link ApplicationEvent}s. Default (Guava-based) implementation * can be found in {@link GuavaApplicationEventModule} * * See {@link EventListener} and {@link ApplicationEventDispatcher} for usage. */ public final class ApplicationEventModule extends AbstractModule { private static class ApplicationEventSubscribingTypeListener implements TypeListener { private static final Logger LOG = LoggerFactory.getLogger(ApplicationEventSubscribingTypeListener.class); private final Provider<ApplicationEventDispatcher> dispatcherProvider; public ApplicationEventSubscribingTypeListener(Provider<ApplicationEventDispatcher> dispatcherProvider) { this.dispatcherProvider = dispatcherProvider; } @Override public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { final Class<?> clazz = type.getRawType(); final List<Method> handlerMethods = getAllDeclaredHandlerMethods(clazz); if(!handlerMethods.isEmpty()) { encounter.register(new InjectionListener<Object>() { @Override public void afterInjection(Object injectee) { for (final Method handlerMethod : handlerMethods) { dispatcherProvider.get().registerListener(injectee, handlerMethod, (Class<? extends ApplicationEvent>) handlerMethod.getParameterTypes()[0]); } } }); } } private List<Method> getAllDeclaredHandlerMethods(Class<?> clazz) { final List<Method> handlerMethods = new ArrayList<>(); while (clazz != null && !Collection.class.isAssignableFrom(clazz) && !clazz.isArray()) { for (final Method handlerMethod : clazz.getDeclaredMethods()) { if (handlerMethod.isAnnotationPresent(EventListener.class)) { if (handlerMethod.getReturnType().equals(Void.TYPE) && handlerMethod.getParameterTypes().length == 1 && ApplicationEvent.class.isAssignableFrom(handlerMethod.getParameterTypes()[0])) { handlerMethods.add(handlerMethod); } else { throw new IllegalArgumentException("@EventListener " + clazz.getName() + "." + handlerMethod.getName() + "skipped. Methods must be public, void, and accept exactly" + " one argument extending com.netflix.governator.event.ApplicationEvent."); } } } clazz = clazz.getSuperclass(); } return handlerMethods; } } private static class ApplicationEventSubscribingProvisionListener implements ProvisionListener { private final Provider<ApplicationEventDispatcher> dispatcherProvider; public ApplicationEventSubscribingProvisionListener(Provider<ApplicationEventDispatcher> dispatcherProvider) { this.dispatcherProvider = dispatcherProvider; } @Override public <T> void onProvision(ProvisionInvocation<T> provision) { T provisioned = provision.provision(); if (provisioned != null && provisioned instanceof ApplicationEventListener) { dispatcherProvider.get().registerListener((ApplicationEventListener)provisioned); } } } @Override protected void configure() { com.google.inject.Provider<ApplicationEventDispatcher> dispatcherProvider = binder().getProvider(ApplicationEventDispatcher.class); bindListener(Matchers.any(), new ApplicationEventSubscribingTypeListener(dispatcherProvider)); bindListener(Matchers.any(), new ApplicationEventSubscribingProvisionListener(dispatcherProvider)); } @Override public boolean equals(Object obj) { return getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } @Override public String toString() { return "ApplicationEventModule[]"; } }
5,591
0
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/event
Create_ds/governator/governator-core/src/main/java/com/netflix/governator/event/guava/GuavaApplicationEventModule.java
package com.netflix.governator.event.guava; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import javax.inject.Inject; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.reflect.TypeToken; import com.google.inject.AbstractModule; import com.netflix.governator.event.ApplicationEvent; import com.netflix.governator.event.ApplicationEventDispatcher; import com.netflix.governator.event.ApplicationEventListener; import com.netflix.governator.event.ApplicationEventModule; import com.netflix.governator.event.ApplicationEventRegistration; public final class GuavaApplicationEventModule extends AbstractModule { @Override protected void configure() { install(new ApplicationEventModule()); bind(ApplicationEventDispatcher.class).to(GuavaApplicationEventDispatcher.class).asEagerSingleton(); } @Override public boolean equals(Object obj) { return getClass().equals(obj.getClass()); } @Override public int hashCode() { return getClass().hashCode(); } @Override public String toString() { return "GuavaApplicationEventModule[]"; } private static final class GuavaApplicationEventDispatcher implements ApplicationEventDispatcher { private final EventBus eventBus; private final Method eventListenerMethod; @Inject public GuavaApplicationEventDispatcher(EventBus eventBus) { this.eventBus = eventBus; try { this.eventListenerMethod = ApplicationEventListener.class.getDeclaredMethod("onEvent", ApplicationEvent.class); } catch (Exception e) { throw new RuntimeException("Failed to cache ApplicationEventListener method", e); } } public ApplicationEventRegistration registerListener(Object instance, Method method, Class<? extends ApplicationEvent> eventType) { GuavaSubscriberProxy proxy = new GuavaSubscriberProxy(instance, method, eventType); eventBus.register(proxy); return new GuavaEventRegistration(eventBus, proxy); } public <T extends ApplicationEvent> ApplicationEventRegistration registerListener(Class<T> eventType, ApplicationEventListener<T> eventListener) { GuavaSubscriberProxy proxy = new GuavaSubscriberProxy(eventListener, eventListenerMethod, eventType); eventBus.register(proxy); return new GuavaEventRegistration(eventBus, proxy); } public ApplicationEventRegistration registerListener(ApplicationEventListener<? extends ApplicationEvent> eventListener) { Type[] genericInterfaces = eventListener.getClass().getGenericInterfaces(); for (Type type : genericInterfaces) { if (ApplicationEventListener.class.isAssignableFrom(TypeToken.of(type).getRawType())) { ParameterizedType ptype = (ParameterizedType) type; Class<?> rawType = TypeToken.of(ptype.getActualTypeArguments()[0]).getRawType(); GuavaSubscriberProxy proxy = new GuavaSubscriberProxy(eventListener, eventListenerMethod, rawType); eventBus.register(proxy); return new GuavaEventRegistration(eventBus, proxy); } } return new ApplicationEventRegistration() { public void unregister() {} //no-op. Could not find anything to register. }; } private static class GuavaSubscriberProxy { private final Object handlerInstance; private final Method handlerMethod; private final Class<?> acceptedType; public GuavaSubscriberProxy(Object handlerInstance, Method handlerMethod, Class<?> acceptedType) { this.handlerInstance = handlerInstance; this.handlerMethod = handlerMethod; this.acceptedType = acceptedType; } @Subscribe public void invokeEventHandler(ApplicationEvent event) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (acceptedType.isAssignableFrom(event.getClass())) { if (!handlerMethod.isAccessible()) { handlerMethod.setAccessible(true); } handlerMethod.invoke(handlerInstance, event); } } } private static class GuavaEventRegistration implements ApplicationEventRegistration { private final EventBus eventBus; private final GuavaSubscriberProxy subscriber; public GuavaEventRegistration(EventBus eventBus, GuavaSubscriberProxy subscriber) { this.eventBus = eventBus; this.subscriber = subscriber; } public void unregister() { this.eventBus.unregister(subscriber); } } @Override public void publishEvent(ApplicationEvent event) { this.eventBus.post(event); } } }
5,592
0
Create_ds/governator/governator-test/src/test/java/com/netflix/governator/guice
Create_ds/governator/governator-test/src/test/java/com/netflix/governator/guice/test/AnnotationBasedTestInjectionManagerTest.java
package com.netflix.governator.guice.test; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.google.inject.AbstractModule; import com.netflix.governator.guice.test.AnnotationBasedTestInjectorManager; import com.netflix.governator.guice.test.ModulesForTesting; import com.netflix.governator.guice.test.mocks.MockHandler; public class AnnotationBasedTestInjectionManagerTest { @Test(expected=RuntimeException.class) public void testExceptionThrownWhenModuleWithNoDefaultConstructorProvided() { new AnnotationBasedTestInjectorManager(TestClassForModulesWithoutDefaultConstrutor.class, TestDefaultdMockHandler.class); } @Test public void testMockHandlerSelection() { AnnotationBasedTestInjectorManager annotationBasedTestInjectorManager = new AnnotationBasedTestInjectorManager(ParentTest.class, TestDefaultdMockHandler.class); assertTrue(annotationBasedTestInjectorManager.getMockHandler() instanceof TestParentMockHandler); } @Test public void testMockHandlerOverridenByChild() { AnnotationBasedTestInjectorManager annotationBasedTestInjectorManager = new AnnotationBasedTestInjectorManager(ChildTest.class, TestDefaultdMockHandler.class); assertTrue(annotationBasedTestInjectorManager.getMockHandler() instanceof TestChildMockHandler); } @Test public void testMockHandlerInheritence() { AnnotationBasedTestInjectorManager annotationBasedTestInjectorManager = new AnnotationBasedTestInjectorManager(InheritectMockHandlerTest.class, TestDefaultdMockHandler.class); assertTrue(annotationBasedTestInjectorManager.getMockHandler() instanceof TestParentMockHandler); } } @ModulesForTesting(ModuleWithoutDefaultConstructor.class) class TestClassForModulesWithoutDefaultConstrutor { } class ModuleWithoutDefaultConstructor extends AbstractModule { public ModuleWithoutDefaultConstructor(String someArg) {} @Override protected void configure() {} } @ModulesForTesting(mockHandler=TestParentMockHandler.class) class ParentTest { } @ModulesForTesting(mockHandler=TestChildMockHandler.class) class ChildTest extends ParentTest { } @ModulesForTesting class InheritectMockHandlerTest extends ParentTest { } class TestDefaultdMockHandler implements MockHandler { public <T> T createMock(Class<T> classToMock) { return null; } public <T> T createMock(Class<T> classToMock, Object args) { return null; } public <T> T createSpy(T objectToSpy) { return null; } public void resetMock(Object mockToReset) {} } class TestChildMockHandler implements MockHandler { public <T> T createMock(Class<T> classToMock) { return null; } public <T> T createMock(Class<T> classToMock, Object args) { return null; } public <T> T createSpy(T objectToSpy) { return null; } public void resetMock(Object mockToReset) {} } class TestParentMockHandler implements MockHandler { public <T> T createMock(Class<T> classToMock) { return null; } public <T> T createMock(Class<T> classToMock, Object args) { return null; } public <T> T createSpy(T objectToSpy) { return null; } public void resetMock(Object mockToReset) {} }
5,593
0
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test/WrapWithSpy.java
package com.netflix.governator.guice.test; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.mockito.Spy; /** * Wraps an existing binding with a Mockito {@link Spy}. * * Example: * <pre> * {@literal @}RunWith(GovernatorJunit4ClassRunner.class) * {@literal @}ModulesForTesting({ SomeTestModule.class }) * public class MyTestCase { * * {@literal @}Inject {@literal @}WrapWithSpy * SomeDependency someDependency; * * {@literal @}Test * public void test() { * someDependency.doSomething(); * verify(someDependency, times(1)).doSomething(); * } * } * * public class SomeTestModule extends AbstractModule { * * {@literal @}Override * protected void configure() { * * bind(SomeDependency.class); * } * * } * } * </pre> */ @Target(FIELD) @Retention(RUNTIME) @Documented public @interface WrapWithSpy { /** * The name of the binding you wish to wrap with a Spy. */ String name() default ""; }
5,594
0
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test/InjectorCreationMode.java
package com.netflix.governator.guice.test; public enum InjectorCreationMode { BEFORE_TEST_CLASS, BEFORE_EACH_TEST_METHOD }
5,595
0
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test/CopyBindingTargetVisitor.java
package com.netflix.governator.guice.test; import java.lang.reflect.Constructor; import com.google.inject.Scopes; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.ConstructorBinding; import com.google.inject.spi.ConvertedConstantBinding; import com.google.inject.spi.ExposedBinding; import com.google.inject.spi.InstanceBinding; import com.google.inject.spi.LinkedKeyBinding; import com.google.inject.spi.ProviderBinding; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderKeyBinding; import com.google.inject.spi.UntargettedBinding; class CopyBindingTargetVisitor<T> implements BindingTargetVisitor<T, Void> { private LinkedBindingBuilder<T> builder; public CopyBindingTargetVisitor(LinkedBindingBuilder<T> builder) { this.builder = builder; } @Override public Void visit(InstanceBinding<? extends T> binding) { builder.toInstance(binding.getInstance()); return null; } @SuppressWarnings("deprecation") @Override public Void visit(ProviderInstanceBinding<? extends T> binding) { builder.toProvider(binding.getProviderInstance()).in(Scopes.SINGLETON); return null; } @Override public Void visit(ProviderKeyBinding<? extends T> binding) { builder.toProvider(binding.getProviderKey()).in(Scopes.SINGLETON); return null; } @Override public Void visit(LinkedKeyBinding<? extends T> binding) { builder.to(binding.getLinkedKey()).in(Scopes.SINGLETON); return null; } @Override public Void visit(ExposedBinding<? extends T> binding) { builder.to(binding.getKey()).in(Scopes.SINGLETON); return null; } @Override public Void visit(UntargettedBinding<? extends T> binding) { builder.to(binding.getKey().getTypeLiteral()).in(Scopes.SINGLETON); return null; } @SuppressWarnings("unchecked") @Override public Void visit(ConstructorBinding<? extends T> binding) { builder.toConstructor((Constructor<T>) binding.getConstructor().getMember()).in(Scopes.SINGLETON); return null; } @Override public Void visit(ConvertedConstantBinding<? extends T> binding) { builder.toInstance(binding.getValue()); return null; } @Override public Void visit(ProviderBinding<? extends T> binding) { builder.toProvider(binding.getProvider()).in(Scopes.SINGLETON); return null; } }
5,596
0
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test/ModulesForTesting.java
package com.netflix.governator.guice.test; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; import com.google.inject.Module; import com.netflix.governator.guice.test.mocks.MockHandler; /** * Creates a Governator-Guice Injector using the provided modules for use in testing. * * Example: * <pre> * {@literal @}RunWith(GovernatorJunit4ClassRunner.class) * {@literal @}ModulesForTesting({ SomeTestModule.class }) * public class MyTestCase { * * {@literal @}Inject * SomeDependency someDependency; * * {@literal @}Test * public void test() { * assertNotNull(someDependency); * } * } * * public class SomeTestModule extends AbstractModule { * * {@literal @}Override * protected void configure() { * * bind(SomeDependency.class); * } * * } * } * </pre> */ @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface ModulesForTesting { Class<? extends Module>[] value() default {}; InjectorCreationMode injectorCreation() default InjectorCreationMode.BEFORE_TEST_CLASS; Class<? extends MockHandler> mockHandler() default MockHandler.class; }
5,597
0
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test/ReplaceWithMock.java
package com.netflix.governator.guice.test; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.mockito.Answers; /** * Creates an override binding for the annotated type. * * Example: * <pre> * {@literal @}RunWith(GovernatorJunit4ClassRunner.class) * {@literal @}ModulesForTesting({ SomeTestModule.class }) * public class MyTestCase { * * {@literal @}Inject {@literal @}ReplaceWithMock * SomeDependency someDependency; * * {@literal @}Test * public void test() { * Mockito.when(someDependency.doSomething()).thenReturn("something"); * assertEquals("something", someDependency.doSomething()); * } * } * * public class SomeTestModule extends AbstractModule { * * {@literal @}Override * protected void configure() { * * bind(SomeDependency.class); * } * * } * } * </pre> */ @Target(FIELD) @Retention(RUNTIME) @Documented public @interface ReplaceWithMock { /** * Sets the configured answer of this mock. */ Answers answer() default Answers.RETURNS_DEFAULTS; /** * The name of the binding you wish to mock. */ String name() default ""; }
5,598
0
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-test/src/main/java/com/netflix/governator/guice/test/AnnotationBasedTestInjectorManager.java
package com.netflix.governator.guice.test; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import org.apache.commons.lang3.ClassUtils; import com.google.inject.AbstractModule; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.Stage; import com.google.inject.TypeLiteral; import com.google.inject.binder.AnnotatedBindingBuilder; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.name.Names; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; import com.netflix.archaius.api.config.CompositeConfig; import com.netflix.archaius.api.config.SettableConfig; import com.netflix.archaius.api.inject.RuntimeLayer; import com.netflix.archaius.config.DefaultSettableConfig; import com.netflix.archaius.guice.Raw; import com.netflix.archaius.test.TestCompositeConfig; import com.netflix.archaius.test.TestPropertyOverride; import com.netflix.archaius.test.TestPropertyOverrideAnnotationReader; import com.netflix.governator.InjectorBuilder; import com.netflix.governator.LifecycleInjector; import com.netflix.governator.guice.test.mocks.MockHandler; import com.netflix.governator.providers.SingletonProvider; public class AnnotationBasedTestInjectorManager { private LifecycleInjector injector; private final InjectorCreationMode injectorCreationMode; private final MockHandler mockHandler; private final List<Object> mocksToReset = new ArrayList<>(); private final List<Module> modulesForTestClass = new ArrayList<>(); private final List<Module> overrideModules = new ArrayList<>(); private final List<Key<?>> spyTargets = new ArrayList<>(); private final SettableConfig classLevelOverrides = new DefaultSettableConfig(); private final SettableConfig methodLevelOverrides = new DefaultSettableConfig(); private final TestPropertyOverrideAnnotationReader testPropertyOverrideAnnotationReader = new TestPropertyOverrideAnnotationReader(); private TestCompositeConfig testCompositeConfig; public AnnotationBasedTestInjectorManager(Class<?> classUnderTest, Class<? extends MockHandler> defaultMockHandlerClass) { this.injectorCreationMode = getInjectorCreationModeForAnnotatedClass(classUnderTest); this.mockHandler = createMockHandlerForTestClass(classUnderTest, defaultMockHandlerClass); inspectModulesForTestClass(classUnderTest); inspectMocksForTestClass(classUnderTest); inspectSpiesForTargetKeys(Elements.getElements(Stage.TOOL, modulesForTestClass)); overrideModules.add(new ArchaiusTestConfigOverrideModule(classLevelOverrides, methodLevelOverrides)); } public void createInjector() { this.injector = createInjector(modulesForTestClass, overrideModules); this.testCompositeConfig = getInjector().getInstance(TestCompositeConfig.class); } /** * Injects dependencies into the provided test object. */ public void prepareTestFixture(Object testFixture) { getInjector().injectMembers(testFixture); } public void cleanUpMocks() { for (Object mock : mocksToReset) { getMockHandler().resetMock(mock); } } public void cleanUpMethodLevelConfig() { testCompositeConfig.resetForTest(); } public void cleanUpInjector() { getInjector().close(); } public InjectorCreationMode getInjectorCreationMode() { return this.injectorCreationMode; } protected LifecycleInjector createInjector(List<Module> modules, List<Module> overrides) { return InjectorBuilder.fromModules(modules).overrideWith(overrides).createInjector(); } protected MockHandler createMockHandlerForTestClass(Class<?> testClass, Class<? extends MockHandler> defaultMockHandler) { Class<? extends MockHandler> mockHandlerClass = defaultMockHandler; for(Class<?> superClass : getAllSuperClassesInReverseOrder(testClass)) { ModulesForTesting annotation = superClass.getAnnotation(ModulesForTesting.class); if(annotation != null && !annotation.mockHandler().equals(MockHandler.class)) { mockHandlerClass = annotation.mockHandler(); } } ModulesForTesting annotation = testClass.getAnnotation(ModulesForTesting.class); if(annotation != null && !annotation.mockHandler().equals(MockHandler.class)) { mockHandlerClass = annotation.mockHandler(); } if (mockHandlerClass != null) { try { return mockHandlerClass != MockHandler.class ? mockHandlerClass.newInstance() : defaultMockHandler.newInstance(); } catch (SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { throw new IllegalArgumentException("Failed to instantiate MockHandler " + mockHandlerClass.getName() + ". Ensure that is has an accessible no-arg constructor.", e); } } else { throw new IllegalStateException("No MockHandler specified!"); } } private void inspectModulesForTestClass(Class<?> testClass) { final List<Class<? extends Module>> moduleClasses = new ArrayList<>(); moduleClasses.addAll(getModulesForAnnotatedClass(testClass)); for (Class<?> parentClass : getAllSuperClassesInReverseOrder(testClass)) { moduleClasses.addAll(getModulesForAnnotatedClass(parentClass)); } for (Class<? extends Module> moduleClass : moduleClasses) { try { modulesForTestClass.add(moduleClass.newInstance()); } catch (InstantiationException | IllegalAccessException e) { try { Constructor<?> zeroArgConstructor = moduleClass.getDeclaredConstructor(); zeroArgConstructor.setAccessible(true); modulesForTestClass.add((Module) zeroArgConstructor.newInstance()); } catch (Exception ex) { throw new RuntimeException("Error instantiating module " + moduleClass + ". Please ensure that the module is public and has a no-arg constructor", e); } } } } private InjectorCreationMode getInjectorCreationModeForAnnotatedClass(Class<?> testClass) { final Annotation annotation = testClass.getAnnotation(ModulesForTesting.class); if (annotation != null) { return ((ModulesForTesting) annotation).injectorCreation(); } else { return InjectorCreationMode.BEFORE_TEST_CLASS; } } private List<Class<? extends Module>> getModulesForAnnotatedClass(Class<?> testClass) { final Annotation annotation = testClass.getAnnotation(ModulesForTesting.class); if (annotation != null) { return Arrays.asList(((ModulesForTesting) annotation).value()); } else { return Collections.emptyList(); } } private void inspectMocksForTestClass(Class<?> testClass) { getMocksForAnnotatedFields(testClass); for (Class<?> parentClass : getAllSuperClassesInReverseOrder(testClass)) { getMocksForAnnotatedFields(parentClass); } } private void getMocksForAnnotatedFields(Class<?> testClass) { for (Field field : testClass.getDeclaredFields()) { if (field.isAnnotationPresent(ReplaceWithMock.class)) { overrideModules.add(new MockitoOverrideModule<>(field.getAnnotation(ReplaceWithMock.class), field.getType())); } if (field.isAnnotationPresent(WrapWithSpy.class)) { WrapWithSpy spyAnnotation = field.getAnnotation(WrapWithSpy.class); if (spyAnnotation.name().isEmpty()) { spyTargets.add(Key.get(field.getType())); } else { spyTargets.add(Key.get(field.getType(), Names.named(spyAnnotation.name()))); } } } } private void inspectSpiesForTargetKeys(List<Element> elements) { for (Element element : elements) { element.acceptVisitor(new DefaultElementVisitor<Void>() { @Override public <T> Void visit(Binding<T> binding) { final Binding<T> finalBinding = binding; final Key<T> bindingKey = finalBinding.getKey(); final TypeLiteral<T> bindingType = bindingKey.getTypeLiteral(); if (spyTargets.contains(binding.getKey())) { AbstractModule spyModule = new AbstractModule() { protected void configure() { final String finalBindingName = "Spied " + (bindingKey.getAnnotation() != null ? bindingKey.getAnnotation().toString() : "") + bindingType; final Key<T> newUniqueKey = Key.get(bindingType, Names.named(finalBindingName)); finalBinding.acceptTargetVisitor(new CopyBindingTargetVisitor<>(binder().bind(newUniqueKey))); bind(finalBinding.getKey()).toProvider(new SingletonProvider<T>() { @Inject Injector injector; @Override protected T create() { T t = injector.getInstance(newUniqueKey); T spied = getMockHandler().createSpy(t); mocksToReset.add(spied); return spied; }; }); } }; overrideModules.add(spyModule); } return null; } }); } } public void prepareConfigForTestClass(Class<?> testClass) { for (Class<?> parentClass : getAllSuperClassesInReverseOrder(testClass)) { classLevelOverrides.setProperties(testPropertyOverrideAnnotationReader.getPropertiesForAnnotation(parentClass.getAnnotation(TestPropertyOverride.class))); } classLevelOverrides.setProperties(testPropertyOverrideAnnotationReader.getPropertiesForAnnotation(testClass.getAnnotation(TestPropertyOverride.class))); } public void prepareConfigForTestClass(Class<?> testClass, Method testMethod) { prepareConfigForTestClass(testClass); methodLevelOverrides.setProperties(testPropertyOverrideAnnotationReader.getPropertiesForAnnotation(testMethod.getAnnotation(TestPropertyOverride.class))); } private List<Class<?>> getAllSuperClassesInReverseOrder(Class<?> clazz) { List<Class<?>> allSuperclasses = ClassUtils.getAllSuperclasses(clazz); Collections.reverse(allSuperclasses); return allSuperclasses; } public MockHandler getMockHandler() { return mockHandler; } public LifecycleInjector getInjector() { return injector; } private class MockitoOverrideModule<T> extends AbstractModule { private final ReplaceWithMock annotation; private final Class<T> classToBind; public MockitoOverrideModule(ReplaceWithMock annotation, Class<T> classToBind) { this.annotation = annotation; this.classToBind = classToBind; } @Override protected void configure() { final T mock = getMockHandler().createMock(classToBind, annotation.answer().get()); mocksToReset.add(mock); LinkedBindingBuilder<T> bindingBuilder = bind(classToBind); if (!annotation.name().isEmpty()) { bindingBuilder = ((AnnotatedBindingBuilder<T>) bindingBuilder).annotatedWith(Names.named(annotation.name())); } bindingBuilder.toInstance(mock); } } private static class ArchaiusTestConfigOverrideModule extends AbstractModule { private SettableConfig classLevelOverrides; private SettableConfig methodLevelOverrides; public ArchaiusTestConfigOverrideModule(SettableConfig classLevelOverrides, SettableConfig methodLevelOverrides) { this.classLevelOverrides = classLevelOverrides; this.methodLevelOverrides = methodLevelOverrides; } @Singleton private static class OptionalConfigHolder { @com.google.inject.Inject(optional = true) @RuntimeLayer private SettableConfig runtime; public SettableConfig get() { if (runtime != null) { return runtime; } else { return new DefaultSettableConfig(); } } } @Override protected void configure() { } @Provides @Singleton public TestCompositeConfig compositeConfig(OptionalConfigHolder config) { return new TestCompositeConfig(config.get(), classLevelOverrides, methodLevelOverrides); } @Provides @Singleton @Raw public CompositeConfig compositeConfig(TestCompositeConfig config) { return config; } } }
5,599