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-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/resources/ObjectWithResources.java
package com.netflix.governator.lifecycle.resources; import javax.annotation.Resource; import javax.inject.Inject; import java.awt.*; import java.math.BigInteger; @Resource(name = "classResource", type = Double.class) public class ObjectWithResources { @Resource private String myResource; @Resource(name = "overrideInt") private BigInteger myOverrideResource; private Point p; private Rectangle r; @Inject public ObjectWithResources() { } @Resource public void setP(Point p) { this.p = p; } public Point getP() { return p; } public Rectangle getR() { return r; } @Resource(name = "overrideRect") public void setR(Rectangle r) { this.r = r; } public String getMyResource() { return myResource; } public BigInteger getMyOverrideResource() { return myOverrideResource; } }
5,700
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/resources/Jsr250EnabledService.java
package com.netflix.governator.lifecycle.resources; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.inject.Singleton; /** * @author Alexey Krylov (lexx) * @since 19.02.13 */ @Singleton public class Jsr250EnabledService { private boolean postConstuctInvoked; private Jsr250Resource resource; private boolean preDestroyInvoked; @PostConstruct protected void postConstuct() { postConstuctInvoked = true; } @Resource public void setResource(Jsr250Resource resource) { this.resource = resource; } public boolean isPostConstuctInvoked() { return postConstuctInvoked; } public boolean isResourceSet() { return resource != null; } @PreDestroy protected void preDestroy() { preDestroyInvoked = true; } public boolean isPreDestroyInvoked() { return preDestroyInvoked; } public Jsr250Resource getResource() { return resource; } }
5,701
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/warmup/Dag3.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.warmup; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.governator.annotations.WarmUp; public class Dag3 { /* Mix of classes with/without warmups and dependencies that cross tiers C < > BnW < A ==> D < B < > CnW */ @SuppressWarnings("UnusedParameters") @Singleton public static class A { private final Recorder recorder; @Inject public A(Recorder recorder, BnW bnw, B b, D d) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("A"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class B { private final Recorder recorder; @Inject public B(Recorder recorder, CnW cnw) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("B"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class BnW { @Inject public BnW(C c) { } } @SuppressWarnings("UnusedParameters") @Singleton public static class C { private final Recorder recorder; @Inject public C(Recorder recorder, D d) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("C"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class CnW { @Inject public CnW(D d) { } } @Singleton public static class D { private final Recorder recorder; @Inject public D(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("D"); } } }
5,702
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/warmup/DagInterface.java
package com.netflix.governator.lifecycle.warmup; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.governator.annotations.WarmUp; public class DagInterface { /* 3 Classes all with warmups B < A < C */ public interface A { } public interface B { } public interface C { } @SuppressWarnings("UnusedParameters") @Singleton public static class AImpl implements A { private final Recorder recorder; @Inject public AImpl(Recorder recorder, B b, C c) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("A"); } } @Singleton public static class BImpl implements B { private final Recorder recorder; @Inject public BImpl(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("B"); } } @Singleton public static class CImpl implements C { private final Recorder recorder; @Inject public CImpl(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("C"); } } }
5,703
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/warmup/Dag2.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.warmup; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.governator.annotations.WarmUp; public class Dag2 { /* 3 tiers of classes all with warmups B1 < > A1 C1 < > B2 < > A2 C2 < > B3 < > A3 C3 < > B4 */ @Singleton public static class C1 { private final Recorder recorder; @Inject public C1(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("C1"); } } @Singleton public static class C2 { private final Recorder recorder; @Inject public C2(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("C2"); } } @Singleton public static class C3 { private final Recorder recorder; @Inject public C3(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("C3"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class B1 { private final Recorder recorder; @Inject public B1(Recorder recorder, C1 c1) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("B1"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class B2 { private final Recorder recorder; @Inject public B2(Recorder recorder, C1 c1, C2 c2) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("B2"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class B3 { private final Recorder recorder; @Inject public B3(Recorder recorder, C2 c2, C3 c3) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("B3"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class B4 { private final Recorder recorder; @Inject public B4(Recorder recorder, C3 c3) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("B4"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class A1 { private final Recorder recorder; @Inject public A1(Recorder recorder, B1 b1, B2 b2) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("A1"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class A2 { private final Recorder recorder; @Inject public A2(Recorder recorder, B2 b2, B3 b3) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("A2"); } } @SuppressWarnings("UnusedParameters") @Singleton public static class A3 { private final Recorder recorder; @Inject public A3(Recorder recorder, B3 b3, B4 b4) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("A3"); } } }
5,704
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/warmup/Dag4.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.warmup; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.governator.annotations.WarmUp; public class Dag4 { /* E < < D \ < < \ B F \ < \ A \ < \ C - - - - - */ @SuppressWarnings("UnusedParameters") @Singleton public static class A { private final Recorder recorder; @Inject public A(Recorder recorder, B b, C c) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("A"); } } @Singleton @SuppressWarnings("UnusedParameters") public static class B { private final Recorder recorder; @Inject public B(Recorder recorder, D d) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("B"); } } @Singleton @SuppressWarnings("UnusedParameters") public static class C { private final Recorder recorder; @Inject public C(Recorder recorder, E e) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("C"); } } @Singleton @SuppressWarnings("UnusedParameters") public static class D { private final Recorder recorder; @Inject public D(Recorder recorder, E e, F f) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("D"); } } @Singleton public static class E { private final Recorder recorder; @Inject public E(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("E"); } } @Singleton public static class F { private final Recorder recorder; @Inject public F(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("F"); } } }
5,705
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/warmup/Flat.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.warmup; import javax.inject.Inject; import com.google.inject.Singleton; import com.netflix.governator.annotations.WarmUp; public class Flat { /* Root classes without dependencies */ @Singleton public static class A { @Inject public volatile Recorder recorder; @WarmUp public void warmUp() throws InterruptedException { recorder.record("A"); } } @Singleton public static class B { @Inject public volatile Recorder recorder; @WarmUp public void warmUp() throws InterruptedException { recorder.record("B"); } } }
5,706
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/warmup/WarmUpWithException.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.warmup; import com.netflix.governator.annotations.WarmUp; public class WarmUpWithException { @WarmUp public void warmUp() { throw new NullPointerException(); } }
5,707
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/warmup/TestWarmUpManager.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.warmup; import java.util.Arrays; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Sets; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Module; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.lifecycle.LifecycleManager; public class TestWarmUpManager extends LifecycleInjectorBuilderProvider { private static final Logger LOG = LoggerFactory.getLogger(TestWarmUpManager.class); @Test public void testPostStart() throws Exception { Injector injector = LifecycleInjector.builder().build().createInjector(); injector.getInstance(LifecycleManager.class).start(); injector.getInstance(Dag1.A.class); Recorder recorder = injector.getInstance(Recorder.class); LOG.info("" + recorder.getRecordings()); LOG.info("" + recorder.getConcurrents()); assertSingleExecution(recorder); assertNotConcurrent(recorder, "A", "B"); assertNotConcurrent(recorder, "A", "C"); Assert.assertEquals(recorder.getInterruptions().size(), 0); assertOrdering(recorder, "A", "B"); assertOrdering(recorder, "A", "C"); } @Test(expected = Error.class) public void testErrors() throws Exception { AbstractModule module = new AbstractModule() { @Override protected void configure() { binder().bind(WarmUpWithException.class).asEagerSingleton(); } }; LifecycleInjector.builder().withModules(module).build().createInjector().getInstance(LifecycleManager.class) .start(); } @Test public void testDag1MultiModule() throws Exception { final List<AbstractModule> modules = Arrays.asList(new AbstractModule() { @Override protected void configure() { bind(Dag1.A.class); } }, new AbstractModule() { @Override protected void configure() { bind(Dag1.B.class); } }, new AbstractModule() { @Override protected void configure() { bind(Dag1.C.class); } }); Injector injector = LifecycleInjector.builder().withModules(modules).build().createInjector(); injector.getInstance(LifecycleManager.class).start(); Recorder recorder = injector.getInstance(Recorder.class); LOG.info("" + recorder.getRecordings()); LOG.info("" + recorder.getConcurrents()); assertSingleExecution(recorder); assertNotConcurrent(recorder, "A", "B"); assertNotConcurrent(recorder, "A", "C"); Assert.assertEquals(recorder.getInterruptions().size(), 0); assertOrdering(recorder, "A", "B"); assertOrdering(recorder, "A", "C"); } @Test public void testDagInterfaceModule() throws Exception { final Module dag1Module = new AbstractModule() { @Override protected void configure() { bind(DagInterface.A.class).to(DagInterface.AImpl.class); bind(DagInterface.B.class).to(DagInterface.BImpl.class); bind(DagInterface.C.class).to(DagInterface.CImpl.class); } }; Injector injector = LifecycleInjector.builder().withModules(dag1Module).build().createInjector(); injector.getInstance(LifecycleManager.class).start(); Recorder recorder = injector.getInstance(Recorder.class); LOG.info("" + recorder.getRecordings()); LOG.info("" + recorder.getConcurrents()); assertSingleExecution(recorder); assertNotConcurrent(recorder, "A", "B"); assertNotConcurrent(recorder, "A", "C"); Assert.assertEquals(recorder.getInterruptions().size(), 0); assertOrdering(recorder, "A", "B"); assertOrdering(recorder, "A", "C"); } @Test public void testDag1() throws Exception { Injector injector = LifecycleInjector.builder().build().createInjector(); injector.getInstance(Dag1.A.class); injector.getInstance(LifecycleManager.class).start(); Recorder recorder = injector.getInstance(Recorder.class); LOG.info("" + recorder.getRecordings()); LOG.info("" + recorder.getConcurrents()); assertSingleExecution(recorder); assertNotConcurrent(recorder, "A", "B"); assertNotConcurrent(recorder, "A", "C"); Assert.assertEquals(recorder.getInterruptions().size(), 0); assertOrdering(recorder, "A", "B"); assertOrdering(recorder, "A", "C"); } @Test public void testDag2() throws Exception { Injector injector = LifecycleInjector.builder().build().createInjector(); injector.getInstance(Dag2.A1.class); injector.getInstance(Dag2.A2.class); injector.getInstance(Dag2.A3.class); injector.getInstance(LifecycleManager.class).start(); Recorder recorder = injector.getInstance(Recorder.class); LOG.info("" + recorder.getRecordings()); LOG.info("" + recorder.getConcurrents()); assertSingleExecution(recorder); assertNotConcurrent(recorder, "A1", "B1"); assertNotConcurrent(recorder, "A1", "B2"); assertNotConcurrent(recorder, "B1", "C1"); assertNotConcurrent(recorder, "B2", "C1"); assertNotConcurrent(recorder, "A2", "B2"); assertNotConcurrent(recorder, "A2", "B3"); assertNotConcurrent(recorder, "B2", "C2"); assertNotConcurrent(recorder, "B3", "C2"); assertNotConcurrent(recorder, "A3", "B3"); assertNotConcurrent(recorder, "A3", "B4"); assertNotConcurrent(recorder, "B3", "C3"); assertNotConcurrent(recorder, "B4", "C3"); Assert.assertEquals(recorder.getInterruptions().size(), 0); assertOrdering(recorder, "A1", "B1"); assertOrdering(recorder, "B1", "C1"); assertOrdering(recorder, "A1", "B2"); assertOrdering(recorder, "B2", "C1"); assertOrdering(recorder, "A2", "B2"); assertOrdering(recorder, "B2", "C2"); assertOrdering(recorder, "A2", "B3"); assertOrdering(recorder, "B3", "C2"); assertOrdering(recorder, "A3", "B3"); assertOrdering(recorder, "B3", "C3"); assertOrdering(recorder, "A3", "B4"); assertOrdering(recorder, "B4", "C3"); } @Test public void testDag3() throws Exception { Injector injector = LifecycleInjector.builder().build().createInjector(); injector.getInstance(Dag3.A.class); injector.getInstance(LifecycleManager.class).start(); Recorder recorder = injector.getInstance(Recorder.class); LOG.info("" + recorder.getRecordings()); LOG.info("" + recorder.getConcurrents()); assertSingleExecution(recorder); assertNotConcurrent(recorder, "C", "D"); assertNotConcurrent(recorder, "B", "D"); assertNotConcurrent(recorder, "A", "B"); assertNotConcurrent(recorder, "A", "C"); Assert.assertEquals(recorder.getInterruptions().size(), 0); assertOrdering(recorder, "A", "C"); assertOrdering(recorder, "C", "D"); assertOrdering(recorder, "A", "D"); assertOrdering(recorder, "B", "D"); } @Test public void testDag4() throws Exception { Injector injector = LifecycleInjector.builder().build().createInjector(); injector.getInstance(Dag4.A.class); injector.getInstance(LifecycleManager.class).start(); Recorder recorder = injector.getInstance(Recorder.class); LOG.info("" + recorder.getRecordings()); LOG.info("" + recorder.getConcurrents()); assertSingleExecution(recorder); Assert.assertEquals(recorder.getInterruptions().size(), 0); assertOrdering(recorder, "D", "E"); assertOrdering(recorder, "C", "E"); assertOrdering(recorder, "B", "D"); assertOrdering(recorder, "A", "B"); } @Test public void testFlat() throws Exception { Injector injector = LifecycleInjector.builder().build().createInjector(); Recorder recorder = injector.getInstance(Recorder.class); injector.getInstance(Flat.A.class).recorder = recorder; injector.getInstance(Flat.B.class).recorder = recorder; injector.getInstance(LifecycleManager.class).start(); LOG.info("" + recorder.getRecordings()); LOG.info("" + recorder.getConcurrents()); assertSingleExecution(recorder); Assert.assertEquals(recorder.getInterruptions().size(), 0); Assert.assertTrue(recorder.getRecordings().indexOf("A") >= 0); Assert.assertTrue(recorder.getRecordings().indexOf("B") >= 0); } private void assertSingleExecution(Recorder recorder) { Set<String> duplicateCheck = Sets.newHashSet(); for (String s : recorder.getRecordings()) { Assert.assertFalse(s + " ran more than once: " + recorder.getRecordings(), duplicateCheck.contains(s)); duplicateCheck.add(s); } } private void assertOrdering(Recorder recorder, String base, String dependency) { int baseIndex = recorder.getRecordings().indexOf(base); int dependencyIndex = recorder.getRecordings().indexOf(dependency); Assert.assertTrue(baseIndex >= 0); Assert.assertTrue(dependencyIndex >= 0); Assert.assertTrue("baseIndex: " + baseIndex + " - dependencyIndex: " + dependencyIndex, baseIndex > dependencyIndex); } private void assertNotConcurrent(Recorder recorder, String task1, String task2) { for (Set<String> s : recorder.getConcurrents()) { Assert.assertTrue(String.format("Incorrect concurrency for %s and %s: %s", task1, task2, s), !s.contains(task1) || !s.contains(task2)); } } }
5,708
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/warmup/Dag1.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.warmup; import javax.annotation.PostConstruct; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.governator.annotations.WarmUp; public class Dag1 { /* 3 Classes all with warmups B < A < C */ @SuppressWarnings("UnusedParameters") @Singleton public static class A { private final Recorder recorder; @Inject public A(Recorder recorder, B b, C c) { this.recorder = recorder; } @WarmUp @PostConstruct public void warmUp() throws InterruptedException { recorder.record("A"); } } @Singleton public static class B { private final Recorder recorder; @Inject public B(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("B"); } } @Singleton public static class C { private final Recorder recorder; @Inject public C(Recorder recorder) { this.recorder = recorder; } @WarmUp public void warmUp() throws InterruptedException { recorder.record("C"); } } }
5,709
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/lifecycle/warmup/Recorder.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle.warmup; import java.util.List; import java.util.Set; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class Recorder { private final List<String> recordings = Lists.newArrayList(); private final List<String> interruptions = Lists.newArrayList(); private final Set<Set<String>> concurrents = Sets.newHashSet(); private final Set<String> activeConcurrents = Sets.newHashSet(); @Inject public Recorder() { } public synchronized void record(String s) throws InterruptedException { recordings.add(s); activeConcurrents.add(s); try { concurrents.add(ImmutableSet.copyOf(activeConcurrents)); } finally { activeConcurrents.remove(s); } } public synchronized List<String> getRecordings() { return Lists.newArrayList(recordings); } public synchronized List<String> getInterruptions() { return Lists.newArrayList(interruptions); } public synchronized Set<Set<String>> getConcurrents() { return ImmutableSet.copyOf(concurrents); } }
5,710
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/ObjectWithCustomAutoBind.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.autobind; import com.google.inject.Inject; public class ObjectWithCustomAutoBind { private final MockInjectable injectable; @Inject public ObjectWithCustomAutoBind(@CustomAutoBind(str = "hey", value = 1234) MockInjectable injectable) { this.injectable = injectable; } public MockInjectable getInjectable() { return injectable; } }
5,711
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/MockWithParameter.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.autobind; import com.google.inject.Inject; public class MockWithParameter { private final String parameter; @Inject public MockWithParameter(String parameter) { this.parameter = parameter; } public String getParameter() { return parameter; } }
5,712
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/SimpleWithMethodAutoBind.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.autobind; import com.google.inject.Inject; import com.netflix.governator.annotations.AutoBind; public class SimpleWithMethodAutoBind { private MockWithParameter f1; private MockWithParameter f2; public MockWithParameter getF1() { return f1; } @Inject public void setF1(@AutoBind("f1") MockWithParameter f1) { this.f1 = f1; } public MockWithParameter getF2() { return f2; } @Inject public void setF2(@AutoBind("f2") MockWithParameter f2) { this.f2 = f2; } }
5,713
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/TestAutoBind.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.autobind; import com.google.common.collect.Lists; import com.google.inject.Binder; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.annotations.AutoBind; import com.netflix.governator.guice.AutoBindProvider; import com.netflix.governator.guice.AutoBinds; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Collections; @RunWith(DataProviderRunner.class) public class TestAutoBind extends LifecycleInjectorBuilderProvider { @Test @UseDataProvider("builders") public void testSimple(LifecycleInjectorBuilder lifecycleInjectorBuilder) { final AutoBindProvider<AutoBind> provider = new AutoBindProvider<AutoBind>() { @Override public void configure(Binder binder, AutoBind autoBindAnnotation) { binder.bind(String.class).annotatedWith(autoBindAnnotation).toInstance("a is a"); } }; Injector injector = lifecycleInjectorBuilder .ignoringAutoBindClasses(Collections.<Class<?>>singleton(ObjectWithCustomAutoBind.class)) .withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(new TypeLiteral<AutoBindProvider<AutoBind>>(){}).toInstance(provider); } } ) .usingBasePackages("com.netflix.governator.autobind") .createInjector(); SimpleAutoBind instance = injector.getInstance(SimpleAutoBind.class); Assert.assertEquals(instance.getString(), "a is a"); } @Test @UseDataProvider("builders") public void testCustom(LifecycleInjectorBuilder lifecycleInjectorBuilder) { @SuppressWarnings("RedundantCast") Injector injector = lifecycleInjectorBuilder .ignoringAutoBindClasses(Lists.newArrayList((Class<?>)SimpleAutoBind.class, (Class<?>)SimpleWithMultipleAutoBinds.class, (Class<?>)SimpleWithFieldAutoBind.class, (Class<?>)SimpleWithMethodAutoBind.class)) .withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(new TypeLiteral<AutoBindProvider<CustomAutoBind>>(){}).to(CustomAutoBindProvider.class).asEagerSingleton(); } } ) .usingBasePackages("com.netflix.governator.autobind") .createInjector(); ObjectWithCustomAutoBind instance = injector.getInstance(ObjectWithCustomAutoBind.class); Assert.assertEquals(instance.getInjectable().getStr(), "hey"); Assert.assertEquals(instance.getInjectable().getValue(), 1234); } @Test @UseDataProvider("builders") public void testMultiple(LifecycleInjectorBuilder lifecycleInjectorBuilder) { final AutoBindProvider<AutoBind> provider = new AutoBindProvider<AutoBind>() { @Override public void configure(Binder binder, AutoBind autoBindAnnotation) { binder.bind(MockWithParameter.class).annotatedWith(autoBindAnnotation).toInstance(new MockWithParameter(autoBindAnnotation.value())); } }; Injector injector = lifecycleInjectorBuilder .ignoringAutoBindClasses(Collections.<Class<?>>singleton(ObjectWithCustomAutoBind.class)) .withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(new TypeLiteral<AutoBindProvider<AutoBind>>(){}).toInstance(provider); } } ) .usingBasePackages("com.netflix.governator.autobind") .createInjector(); SimpleWithMultipleAutoBinds instance = injector.getInstance(SimpleWithMultipleAutoBinds.class); Assert.assertEquals(instance.getArg1().getParameter(), "one"); Assert.assertEquals(instance.getArg2().getParameter(), "two"); Assert.assertEquals(instance.getArg3().getParameter(), "three"); Assert.assertEquals(instance.getArg4().getParameter(), "four"); } @Test @UseDataProvider("builders") public void testField(LifecycleInjectorBuilder lifecycleInjectorBuilder) { final AutoBindProvider<AutoBind> provider = new AutoBindProvider<AutoBind>() { @Override public void configure(Binder binder, AutoBind autoBindAnnotation) { binder.bind(MockWithParameter.class).annotatedWith(autoBindAnnotation).toInstance(new MockWithParameter(autoBindAnnotation.value())); } }; Injector injector = lifecycleInjectorBuilder .ignoringAutoBindClasses(Collections.<Class<?>>singleton(ObjectWithCustomAutoBind.class)) .withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(new TypeLiteral<AutoBindProvider<AutoBind>>() { }).toInstance(provider); } } ) .usingBasePackages("com.netflix.governator.autobind") .createInjector(); SimpleWithFieldAutoBind instance = injector.getInstance(SimpleWithFieldAutoBind.class); Assert.assertEquals(instance.field1.getParameter(), "field1"); Assert.assertEquals(instance.field2.getParameter(), "field2"); } @Test @UseDataProvider("builders") public void testMethod(LifecycleInjectorBuilder lifecycleInjectorBuilder) { final AutoBindProvider<AutoBind> provider = new AutoBindProvider<AutoBind>() { @Override public void configure(Binder binder, AutoBind autoBindAnnotation) { binder.bind(MockWithParameter.class).annotatedWith(autoBindAnnotation).toInstance(new MockWithParameter(autoBindAnnotation.value())); } }; Injector injector = lifecycleInjectorBuilder .ignoringAutoBindClasses(Collections.<Class<?>>singleton(ObjectWithCustomAutoBind.class)) .withBootstrapModule ( new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(new TypeLiteral<AutoBindProvider<AutoBind>>(){}).toInstance(provider); } } ) .usingBasePackages("com.netflix.governator.autobind") .createInjector(); SimpleWithMethodAutoBind instance = injector.getInstance(SimpleWithMethodAutoBind.class); Assert.assertEquals(instance.getF1().getParameter(), "f1"); Assert.assertEquals(instance.getF2().getParameter(), "f2"); } @Test public void testNormally() { Injector injector = Guice.createInjector ( new Module() { @Override public void configure(Binder binder) { binder.bind(String.class).annotatedWith(AutoBinds.withValue("foo")).toInstance("we are the music makers"); } } ); Assert.assertEquals(injector.getInstance(SimpleAutoBind.class).getString(), "we are the music makers"); } private static class CustomAutoBindProvider implements AutoBindProvider<CustomAutoBind> { @Override public void configure(Binder binder, CustomAutoBind custom) { binder.bind(MockInjectable.class).annotatedWith(custom).toInstance(new MockInjectable(custom.str(), custom.value())); } } }
5,714
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/SimpleAutoBind.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.autobind; import com.google.inject.Inject; import com.netflix.governator.annotations.AutoBind; public class SimpleAutoBind { private final String aString; @Inject public SimpleAutoBind(@AutoBind("foo") String aString) { this.aString = aString; } public String getString() { return aString; } }
5,715
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/CustomAutoBind.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.autobind; import com.google.inject.BindingAnnotation; import com.netflix.governator.annotations.AutoBind; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.ANNOTATION_TYPE, ElementType.PARAMETER}) @BindingAnnotation @AutoBind public @interface CustomAutoBind { String str(); int value(); }
5,716
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/SimpleWithFieldAutoBind.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.autobind; import com.google.inject.Inject; import com.netflix.governator.annotations.AutoBind; public class SimpleWithFieldAutoBind { @AutoBind("field1") @Inject public MockWithParameter field1; @AutoBind("field2") @Inject public MockWithParameter field2; }
5,717
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/SimpleWithMultipleAutoBinds.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.autobind; import com.google.inject.Inject; import com.netflix.governator.annotations.AutoBind; public class SimpleWithMultipleAutoBinds { private final MockWithParameter arg1; private final MockWithParameter arg2; private final MockWithParameter arg3; private final MockWithParameter arg4; @Inject public SimpleWithMultipleAutoBinds ( @AutoBind("one") MockWithParameter arg1, @AutoBind("two") MockWithParameter arg2, @AutoBind("three") MockWithParameter arg3, @AutoBind("four") MockWithParameter arg4 ) { this.arg1 = arg1; this.arg2 = arg2; this.arg3 = arg3; this.arg4 = arg4; } public MockWithParameter getArg1() { return arg1; } public MockWithParameter getArg2() { return arg2; } public MockWithParameter getArg3() { return arg3; } public MockWithParameter getArg4() { return arg4; } }
5,718
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/MockInjectable.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.autobind; import com.google.inject.Inject; public class MockInjectable { private final String str; private final int value; @Inject public MockInjectable(String str, int value) { this.str = str; this.value = value; } public String getStr() { return str; } public int getValue() { return value; } }
5,719
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobind/scopes/TestAutoBindSingletonScopes.java
package com.netflix.governator.autobind.scopes; import com.google.inject.Injector; import com.google.inject.Stage; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.guice.LifecycleInjector; import com.netflix.governator.guice.LifecycleInjectorMode; import com.netflix.governator.guice.lazy.LazySingleton; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; public class TestAutoBindSingletonScopes { @AutoBindSingleton public static class AutoBindEagerSingleton { public static AtomicInteger counter = new AtomicInteger(); public AutoBindEagerSingleton() { counter.incrementAndGet(); } } @AutoBindSingleton(eager=false) public static class AutoBindNotEagerSingleton { public static AtomicInteger counter = new AtomicInteger(); public AutoBindNotEagerSingleton() { counter.incrementAndGet(); } } @AutoBindSingleton @LazySingleton public static class AutoBindLazySingleton { public static AtomicInteger counter = new AtomicInteger(); public AutoBindLazySingleton() { counter.incrementAndGet(); } } @Before public void before() { AutoBindEagerSingleton.counter.set(0); AutoBindLazySingleton.counter.set(0); AutoBindNotEagerSingleton.counter.set(0); } @Test public void scopesAreHonoredInDevMode() { Injector injector = LifecycleInjector.builder() .inStage(Stage.DEVELOPMENT) .usingBasePackages("com.netflix.governator.autobind.scopes") .build() .createInjector(); injector.getInstance(AutoBindEagerSingleton.class); injector.getInstance(AutoBindEagerSingleton.class); Assert.assertEquals(1, AutoBindEagerSingleton.counter.get()); Assert.assertEquals(0, AutoBindNotEagerSingleton.counter.get()); Assert.assertEquals(0, AutoBindLazySingleton.counter.get()); } @Test public void scopesAreHonoredInProd() { Injector injector = LifecycleInjector.builder() .inStage(Stage.PRODUCTION) .usingBasePackages("com.netflix.governator.autobind.scopes") .build() .createInjector(); injector.getInstance(AutoBindEagerSingleton.class); injector.getInstance(AutoBindEagerSingleton.class); Assert.assertEquals(1, AutoBindEagerSingleton.counter.get()); Assert.assertEquals(0, AutoBindNotEagerSingleton.counter.get()); Assert.assertEquals(0, AutoBindLazySingleton.counter.get()); } @Test public void scopesAreHonoredInDevModeNoChild() { Injector injector = LifecycleInjector.builder() .inStage(Stage.DEVELOPMENT) .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .usingBasePackages("com.netflix.governator.autobind.scopes") .build() .createInjector(); injector.getInstance(AutoBindEagerSingleton.class); injector.getInstance(AutoBindEagerSingleton.class); Assert.assertEquals(1, AutoBindEagerSingleton.counter.get()); Assert.assertEquals(0, AutoBindNotEagerSingleton.counter.get()); Assert.assertEquals(0, AutoBindLazySingleton.counter.get()); } @Test public void scopesAreHonoredInProdNoChild() { Injector injector = LifecycleInjector.builder() .inStage(Stage.PRODUCTION) .withMode(LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS) .usingBasePackages("com.netflix.governator.autobind.scopes") .build() .createInjector(); injector.getInstance(AutoBindEagerSingleton.class); injector.getInstance(AutoBindEagerSingleton.class); Assert.assertEquals(1, AutoBindEagerSingleton.counter.get()); Assert.assertEquals(0, AutoBindNotEagerSingleton.counter.get()); Assert.assertEquals(0, AutoBindLazySingleton.counter.get()); } }
5,720
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmodule
Create_ds/governator/governator-legacy/src/test/java/com/netflix/governator/autobindmodule/good/TestAutoBindModuleInjection.java
package com.netflix.governator.autobindmodule.good; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.name.Names; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.guice.LifecycleInjector; import org.junit.Assert; import org.junit.Test; import javax.inject.Inject; public class TestAutoBindModuleInjection { public static class FooModule extends AbstractModule { @Override protected void configure() { bind(String.class).annotatedWith(Names.named("foo")).toInstance("found"); } } @AutoBindSingleton public static class MyModule extends AbstractModule { @Inject private MyModule(FooModule foo) { } @Override protected void configure() { bind(String.class).annotatedWith(Names.named("MyModule")).toInstance("found"); } } @AutoBindSingleton public static class MyModule2 extends AbstractModule { @Inject private MyModule2() { } @Override protected void configure() { bind(String.class).annotatedWith(Names.named("MyModule2")).toInstance("found"); } } @Test public void shouldInjectModule() { Injector injector = LifecycleInjector.builder().usingBasePackages("com.netflix.governator.autobindmodule") .build() .createInjector(); Assert.assertEquals("found", injector.getInstance(Key.get(String.class, Names.named("MyModule")))); Assert.assertEquals("found", injector.getInstance(Key.get(String.class, Names.named("MyModule2")))); Assert.assertEquals("found", injector.getInstance(Key.get(String.class, Names.named("foo")))); } }
5,721
0
Create_ds/governator/governator-legacy/src/test/java/com/netflix/external/governator/guice
Create_ds/governator/governator-legacy/src/test/java/com/netflix/external/governator/guice/modules/ModuleDepdenciesTest.java
/** * This test is in an 'external' module to bypass the restriction that governator * internal modules cannot be picked up via module depdency */ package com.netflix.external.governator.guice.modules; import com.google.common.collect.Lists; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Singleton; import com.google.inject.Stage; import com.google.inject.TypeLiteral; import com.netflix.governator.LifecycleInjectorBuilderProvider; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.atomic.AtomicLong; @RunWith(DataProviderRunner.class) public class ModuleDepdenciesTest extends LifecycleInjectorBuilderProvider { private static final Logger LOG = LoggerFactory.getLogger(ModuleDepdenciesTest.class); private static final TypeLiteral<List<Integer>> LIST_TYPE_LITERAL = new TypeLiteral<List<Integer>>() { }; private static AtomicLong counter = new AtomicLong(0); @Singleton public static class ModuleA extends AbstractModule { public ModuleA() { LOG.info("ModuleA created"); } @Override protected void configure() { LOG.info("ConfigureA"); counter.incrementAndGet(); } } @After public void afterEachTest() { counter.set(0); } @Singleton public static class ModuleB extends AbstractModule { @Inject public ModuleB(ModuleA a) { LOG.info("ModuleB created"); } @Override protected void configure() { LOG.info("ConfigureB"); counter.incrementAndGet(); } } @Test @UseDataProvider("builders") public void testModuleDependency(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { lifecycleInjectorBuilder.withAdditionalModuleClasses(ModuleB.class).build().createInjector(); } @Singleton public static class A1 { @Inject public A1(List<Integer> list) { list.add(1); } } @Singleton public static class A2 { @Inject public A2(List<Integer> list) { list.add(2); } } @Singleton public static class A3 { @Inject public A3(List<Integer> list) { list.add(3); } } @Singleton public static class A4 { @Inject public A4(List<Integer> list) { list.add(4); } } @Singleton public static class ModuleA1 extends AbstractModule { protected void configure() { bind(A1.class); } } @Singleton public static class ModuleA2 extends AbstractModule { @Inject public ModuleA2(ModuleA1 moduleA1) { } public ModuleA2() { } protected void configure() { bind(A2.class); } } @Singleton public static class ModuleA3 extends AbstractModule { public ModuleA3() { } @Inject public ModuleA3(ModuleA2 moduleA3) { } protected void configure() { bind(A3.class); } } @Singleton public static class ModuleA4 extends AbstractModule { public ModuleA4() { } @Inject public ModuleA4(ModuleA3 moduleA3) { } protected void configure() { bind(A4.class); } } @Test @UseDataProvider("builders") public void confirmBindingSingletonOrder(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { final List<Integer> actual = Lists.newArrayList(); final List<Module> modules = Lists.<Module>newArrayList(new ModuleA1(), new ModuleA2(), new ModuleA3(), new ModuleA4()); BootstrapModule bootstrap = new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(LIST_TYPE_LITERAL).toInstance(actual); } }; // Confirm that singletons are created in binding order final List<Integer> expected = Lists.newArrayList(1, 2, 3, 4); Injector injector = lifecycleInjectorBuilder.inStage(Stage.PRODUCTION).withModules(modules).withBootstrapModule(bootstrap).build().createInjector(); Assert.assertEquals(actual, expected); } @Test @UseDataProvider("builders") public void confirmBindingReverseSingletonOrder(LifecycleInjectorBuilder lifecycleInjectorBuilder) throws Exception { final List<Integer> actual = Lists.newArrayList(); final List<Module> modules = Lists.<Module>newArrayList(new ModuleA1(), new ModuleA2(), new ModuleA3(), new ModuleA4()); BootstrapModule bootstrap = new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(LIST_TYPE_LITERAL).toInstance(actual); } }; // Reverse the order of modules in the list to confirm that singletons // are now created in reverse order final List<Integer> expected = Lists.newArrayList(1, 2, 3, 4); Injector injector = lifecycleInjectorBuilder.inStage(Stage.PRODUCTION).withModules(Lists.reverse(modules)).withBootstrapModule(bootstrap).build().createInjector(); LOG.info(actual.toString()); Assert.assertEquals(actual, Lists.reverse(expected)); } @Test @UseDataProvider("builders") public void confirmMultiWithModuleClasses(LifecycleInjectorBuilder lifecycleInjectorBuilder) { final List<Integer> actual = Lists.newArrayList(); BootstrapModule bootstrap = new BootstrapModule() { @Override public void configure(BootstrapBinder binder) { binder.bind(LIST_TYPE_LITERAL).toInstance(actual); } }; Injector injector = lifecycleInjectorBuilder .inStage(Stage.PRODUCTION) .withModuleClasses(ModuleA2.class, ModuleA3.class) .withBootstrapModule(bootstrap).build().createInjector(); final List<Integer> expected = Lists.newArrayList(1, 2, 3); LOG.info(actual.toString()); Assert.assertEquals(actual, expected); } }
5,722
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/ConfigurationModule.java
package com.netflix.governator; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder; import com.netflix.governator.configuration.ConfigurationProvider; /** * Install this module to enable @Configuration and @ConfigurationParameter * annotation processing. * * @author elandau * */ public class ConfigurationModule extends AbstractModule { @Override protected void configure() { Multibinder.newSetBinder(binder(), LifecycleFeature.class).addBinding().to(ConfigurationLifecycleFeature.class); requireBinding(ConfigurationProvider.class); } }
5,723
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/ConfigurationLifecycleFeature.java
package com.netflix.governator; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import com.google.inject.ProvisionException; import com.netflix.governator.annotations.Configuration; import com.netflix.governator.configuration.ConfigurationDocumentation; import com.netflix.governator.configuration.ConfigurationMapper; import com.netflix.governator.configuration.ConfigurationProvider; import com.netflix.governator.lifecycle.LifecycleMethods; /** * Feature to enable @Configuration annotation processing. * * To enable install the ConfigurationModule. * * <pre> * {@code * install(new ConfigurationModule()); * } * </pre> * @author elandau * */ @Singleton public class ConfigurationLifecycleFeature implements LifecycleFeature { private static class Mapper { private ConfigurationMapper mapper; private ConfigurationProvider configurationProvider; private ConfigurationDocumentation configurationDocumentation; @Inject Mapper(ConfigurationMapper mapper, ConfigurationProvider configurationProvider, ConfigurationDocumentation configurationDocumentation) { this.mapper = mapper; this.configurationProvider = configurationProvider; this.configurationDocumentation = configurationDocumentation; } private void mapConfiguration(Object obj, LifecycleMethods methods) throws Exception { mapper.mapConfiguration(configurationProvider, configurationDocumentation, obj, methods); } } private volatile Provider<Mapper> mapper; @Inject public void initialize(Provider<Mapper> state) { this.mapper = state; } @Override public List<LifecycleAction> getActionsForType(final Class<?> type) { final LifecycleMethods methods = new LifecycleMethods(type); if (methods.annotatedFields(Configuration.class).length > 0) { return Arrays.<LifecycleAction>asList(new LifecycleAction() { @Override public void call(Object obj) throws Exception { if (mapper == null) { throw new ProvisionException("Trying to map fields of type " + type.getName() + " before ConfigurationLifecycleFeature was fully initialized by the injector"); } try { mapper.get().mapConfiguration(obj, methods); } catch (Exception e) { throw new ProvisionException("Failed to map configuration for type " + type.getName(), e); } } }); } else { return Collections.emptyList(); } } @Override public String toString() { return "ConfigurationLifecycleFeature[]"; } }
5,724
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationOwnershipPolicies.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. */ /* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import java.util.Map; /** * Convenience factory for getting standard ownership policies */ public class ConfigurationOwnershipPolicies { /** * Return an ownership policy that returns true for {@link ConfigurationOwnershipPolicy#has(ConfigurationKey, Map)} * * @return policy */ public static ConfigurationOwnershipPolicy ownsAll() { return new ConfigurationOwnershipPolicy() { @Override public boolean has(ConfigurationKey key, Map<String, String> variables) { return true; } }; } /** * Return an ownership policy that returns true for {@link ConfigurationOwnershipPolicy#has(ConfigurationKey, Map)} * when the given regular expression matches * * @return regex policy */ public static ConfigurationOwnershipPolicy ownsByRegex(String regex) { return new RegexConfigurationOwnershipPolicy(regex); } private ConfigurationOwnershipPolicies() { } }
5,725
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/SystemConfigurationProvider.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import java.util.Date; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; /** * ConfigurationProvider backed by the system properties */ public class SystemConfigurationProvider extends AbstractObjectConfigurationProvider { private final Map<String, String> variableValues; public SystemConfigurationProvider() { this(Maps.<String, String>newHashMap()); } public SystemConfigurationProvider(Map<String, String> variableValues) { this(variableValues, null); } public SystemConfigurationProvider(Map<String, String> variableValues, ObjectMapper objectMapper) { super(objectMapper); this.variableValues = Maps.newHashMap(variableValues); } /** * Change a variable value * * @param name name * @param value value */ public void setVariable(String name, String value) { variableValues.put(name, value); } @Override public boolean has(ConfigurationKey key) { return System.getProperty(key.getKey(variableValues), null) != null; } @Override public Property<Boolean> getBooleanProperty(final ConfigurationKey key, final Boolean defaultValue) { return new Property<Boolean>() { @Override public Boolean get() { String value = System.getProperty(key.getKey(variableValues)); if ( value == null ) { return defaultValue; } return Boolean.parseBoolean(value); } }; } @Override public Property<Integer> getIntegerProperty(final ConfigurationKey key, final Integer defaultValue) { return new Property<Integer>() { @Override public Integer get() { Integer value; try { value = Integer.parseInt(System.getProperty(key.getKey(variableValues))); } catch (NumberFormatException ex) { return defaultValue; } return value; } }; } @Override public Property<Long> getLongProperty(final ConfigurationKey key, final Long defaultValue) { return new Property<Long>() { @Override public Long get() { Long value; try { value = Long.parseLong(System.getProperty(key.getKey(variableValues))); } catch (NumberFormatException ex) { return defaultValue; } return value; } }; } @Override public Property<Double> getDoubleProperty(final ConfigurationKey key, final Double defaultValue) { return new Property<Double>() { @Override public Double get() { Double value; try { value = Double.parseDouble(System.getProperty(key.getKey(variableValues))); } catch (NumberFormatException ex) { return defaultValue; } return value; } }; } @Override public Property<String> getStringProperty(final ConfigurationKey key, final String defaultValue) { return new Property<String>() { @Override public String get() { String value = System.getProperty(key.getKey(variableValues)); if ( value == null ) { return defaultValue; } return value; } }; } @Override public Property<Date> getDateProperty(ConfigurationKey key, Date defaultValue) { return new DateWithDefaultProperty(getStringProperty(key, null), defaultValue); } }
5,726
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/Property.java
package com.netflix.governator.configuration; import com.google.common.base.Supplier; public abstract class Property<T> { public static <T> Property<T> from(final T value) { return new Property<T>() { @Override public T get() { return value; } }; } public static <T> Property<T> from(final Supplier<T> value) { return new Property<T>() { @Override public T get() { return value.get(); } }; } public static <T> Supplier<T> from(final Property<T> value) { return new Supplier<T>() { @Override public T get() { return value.get(); } }; } public abstract T get(); }
5,727
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationDocumentation.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import com.google.common.collect.Maps; import com.google.inject.Singleton; import java.lang.reflect.Field; import java.util.Map; /** * Used internally to display configuration documentation */ @Singleton public class ConfigurationDocumentation { private final Map<String, Entry> entries = Maps.newConcurrentMap(); public static class Entry { public final Field field; public final String configurationName; public final boolean has; public final String defaultValue; public final String value; public final String documentation; private Entry(Field field, String configurationName, boolean has, String defaultValue, String value, String documentation) { this.field = field; this.configurationName = configurationName; this.has = has; this.defaultValue = defaultValue; this.value = value; this.documentation = documentation; } } public void registerConfiguration(Field field, String configurationName, boolean has, String defaultValue, String value, String documentation) { entries.put(configurationName, new Entry(field, configurationName, has, defaultValue, value, documentation)); } public Map<String, Entry> getSortedEntries() { Map<String, Entry> sortedEntries = Maps.newTreeMap(); sortedEntries.putAll(entries); return sortedEntries; } }
5,728
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/DateWithDefaultSupplier.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import com.google.common.base.Supplier; import javax.xml.bind.DatatypeConverter; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.util.Locale; /** * Special supplier that converts a string date to a Date * * @author elandau */ public class DateWithDefaultSupplier implements Supplier<Date> { private final Date defaultValue; private final Supplier<String> supplier; private final DateFormat formatter; public DateWithDefaultSupplier(Supplier<String> supplier, Date defaultValue) { this.defaultValue = defaultValue; this.supplier = supplier; formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); formatter.setLenient(false); } @Override public Date get() { String current = supplier.get(); if ( current != null ) { Date newDate = parseDate(current); if ( newDate != null ) { return newDate; } } return defaultValue; } private Date parseDate(String value) { if ( value == null ) { return null; } try { return formatter.parse(value); } catch ( ParseException e ) { // ignore as the fallback is the DatattypeConverter. } try { return DatatypeConverter.parseDateTime(value).getTime(); } catch ( IllegalArgumentException e ) { // ignore as the fallback is the DatattypeConverter. } return null; } }
5,729
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationMapper.java
package com.netflix.governator.configuration; import com.google.inject.ImplementedBy; import com.netflix.governator.lifecycle.DefaultConfigurationMapper; import com.netflix.governator.lifecycle.LifecycleMethods; /** * Interface definition for mapping a configuration on an instance * * TODO: Ideally ConfigurationProvider and ConfigurationDocumentation should * be specific to the specific configuration mapper implementation * * @author elandau */ @ImplementedBy(DefaultConfigurationMapper.class) public interface ConfigurationMapper { void mapConfiguration( ConfigurationProvider configurationProvider, ConfigurationDocumentation configurationDocumentation, Object obj, LifecycleMethods methods) throws Exception; }
5,730
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/DateWithDefaultProperty.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import com.netflix.governator.configuration.Property; import javax.xml.bind.DatatypeConverter; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.util.Locale; /** * Special supplier that converts a string date to a Date * * @author elandau */ public class DateWithDefaultProperty extends Property<Date> { private final Date defaultValue; private final Property<String> supplier; private final DateFormat formatter; public DateWithDefaultProperty(Property<String> supplier, Date defaultValue) { this.defaultValue = defaultValue; this.supplier = supplier; formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); formatter.setLenient(false); } @Override public Date get() { String current = supplier.get(); if ( current != null ) { Date newDate = parseDate(current); if ( newDate != null ) { return newDate; } } return defaultValue; } private Date parseDate(String value) { if ( value == null ) { return null; } try { return formatter.parse(value); } catch ( ParseException e ) { // ignore as the fallback is the DatattypeConverter. } try { return DatatypeConverter.parseDateTime(value).getTime(); } catch ( IllegalArgumentException e ) { // ignore as the fallback is the DatattypeConverter. } return null; } }
5,731
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationOwnershipPolicy.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import java.util.Map; /** * Policy to determine if a configuration key is owned by a ConfigurationProvider * * @author elandau */ public interface ConfigurationOwnershipPolicy { /** * Return true if there is a configuration value set for the given key + variables * * @param key configuration key * @param variableValues map of variable names to values * @return true/false */ public boolean has(ConfigurationKey key, Map<String, String> variableValues); }
5,732
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/RegexConfigurationOwnershipPolicy.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import java.util.Map; import java.util.regex.Pattern; /** * Configuration property ownership policy that checks a property against a * regex to determine if a ConfigurationProvider owns the property. Use this * for dynamic configuration to give ownership in a situations where the * configuration key may not exist in the provider at startup * * @author elandau */ public class RegexConfigurationOwnershipPolicy implements ConfigurationOwnershipPolicy { private Pattern pattern; public RegexConfigurationOwnershipPolicy(String regex) { pattern = Pattern.compile(regex); } @Override public boolean has(ConfigurationKey key, Map<String, String> variables) { return pattern.matcher(key.getKey(variables)).matches(); } }
5,733
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/PropertiesConfigurationProvider.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import java.util.Date; import java.util.Map; import java.util.Properties; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; /** * ConfigurationProvider backed by a {#link Properties} */ public class PropertiesConfigurationProvider extends AbstractObjectConfigurationProvider { private final Properties properties; private final Map<String, String> variableValues; /** * @param properties the properties */ public PropertiesConfigurationProvider(Properties properties) { this(properties, Maps.<String, String>newHashMap()); } public PropertiesConfigurationProvider(Properties properties, Map<String, String> variableValues) { this(properties, variableValues, null); } public PropertiesConfigurationProvider(Properties properties, Map<String, String> variableValues, ObjectMapper objectMapper) { super(objectMapper); this.properties = properties; this.variableValues = Maps.newHashMap(variableValues); } /** * Change a variable value * * @param name name * @param value value */ public void setVariable(String name, String value) { variableValues.put(name, value); } @Override public boolean has(ConfigurationKey key) { return properties.containsKey(key.getKey(variableValues)); } @Override public Property<Boolean> getBooleanProperty(final ConfigurationKey key, final Boolean defaultValue) { return new Property<Boolean>() { @Override public Boolean get() { String value = properties.getProperty(key.getKey(variableValues)); if ( value == null ) { return defaultValue; } return Boolean.parseBoolean(value); } }; } @Override public Property<Integer> getIntegerProperty(final ConfigurationKey key, final Integer defaultValue) { return new Property<Integer>() { @Override public Integer get() { Integer value; try { value = Integer.parseInt(properties.getProperty(key.getKey(variableValues))); } catch (NumberFormatException ex) { return defaultValue; } return value; } }; } @Override public Property<Long> getLongProperty(final ConfigurationKey key, final Long defaultValue) { return new Property<Long>() { @Override public Long get() { Long value; try { value = Long.parseLong(properties.getProperty(key.getKey(variableValues))); } catch (NumberFormatException ex) { return defaultValue; } return value; } }; } @Override public Property<Double> getDoubleProperty(final ConfigurationKey key, final Double defaultValue) { return new Property<Double>() { @Override public Double get() { Double value; try { value = Double.parseDouble(properties.getProperty(key.getKey(variableValues))); } catch (NumberFormatException ex) { return defaultValue; } return value; } }; } @Override public Property<String> getStringProperty(final ConfigurationKey key, final String defaultValue) { return new Property<String>() { @Override public String get() { String value = properties.getProperty(key.getKey(variableValues)); if ( value == null ) { return defaultValue; } return value; } }; } @Override public Property<Date> getDateProperty(ConfigurationKey key, Date defaultValue) { return new DateWithDefaultProperty(getStringProperty(key, null), defaultValue); } }
5,734
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/ColumnPrinter.java
/* * Copyright 2010 Proofpoint, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; // copied from https://raw.github.com/proofpoint/platform/master/bootstrap/src/main/java/com/proofpoint/bootstrap/ColumnPrinter.java import com.google.common.collect.Lists; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * A utility for outputting columnar text */ class ColumnPrinter { private final List<List<String>> data = Lists.newArrayList(); private final List<String> columnNames = Lists.newArrayList(); private int margin; private static final int DEFAULT_MARGIN = 2; ColumnPrinter() { margin = DEFAULT_MARGIN; } /** * Add a column * * @param columnName name of the column */ void addColumn(String columnName) { data.add(new ArrayList<String>()); columnNames.add(columnName); } /** * Add a value to the first column with the given name * * @param columnName name of the column to add to * @param value value to add */ void addValue(String columnName, String value) { addValue(columnNames.indexOf(columnName), value); } /** * Add a value to the nth column * * @param columnIndex n * @param value value to add */ void addValue(int columnIndex, String value) { if ( (columnIndex < 0) || (columnIndex >= data.size()) ) { throw new IllegalArgumentException(); } List<String> stringList = data.get(columnIndex); stringList.add(value); } /** * Change the margin from the default * * @param margin new margin between columns */ void setMargin(int margin) { this.margin = margin; } /** * Output the columns/data * * @param out stream */ void print(PrintWriter out) { for ( String s : generate() ) { out.println(s); } } /** * Generate the output as a list of string lines * * @return lines */ List<String> generate() { List<String> lines = Lists.newArrayList(); StringBuilder workStr = new StringBuilder(); List<AtomicInteger> columnWidths = getColumnWidths(); List<Iterator<String>> dataIterators = getDataIterators(); Iterator<AtomicInteger> columnWidthIterator = columnWidths.iterator(); for ( String columnName : columnNames ) { int thisWidth = columnWidthIterator.next().intValue(); printValue(workStr, columnName, thisWidth); } pushLine(lines, workStr); boolean done = false; while ( !done ) { boolean hadValue = false; Iterator<Iterator<String>> rowIterator = dataIterators.iterator(); for ( AtomicInteger width : columnWidths ) { Iterator<String> thisDataIterator = rowIterator.next(); if ( thisDataIterator.hasNext() ) { hadValue = true; String value = thisDataIterator.next(); printValue(workStr, value, width.intValue()); } else { printValue(workStr, "", width.intValue()); } } pushLine(lines, workStr); if ( !hadValue ) { done = true; } } return lines; } private void pushLine(List<String> lines, StringBuilder workStr) { lines.add(workStr.toString()); workStr.setLength(0); } private void printValue(StringBuilder str, String value, int thisWidth) { str.append(String.format(widthSpec(thisWidth), value)); } private String widthSpec(int thisWidth) { return "%-" + (thisWidth + margin) + "s"; } private List<Iterator<String>> getDataIterators() { List<Iterator<String>> dataIterators = Lists.newArrayList(); for ( List<String> valueList : data ) { dataIterators.add(valueList.iterator()); } return dataIterators; } private List<AtomicInteger> getColumnWidths() { List<AtomicInteger> columnWidths = Lists.newArrayList(); for ( String columnName : columnNames ) { columnWidths.add(new AtomicInteger(columnName.length())); } int columnIndex = 0; for ( List<String> valueList : data ) { AtomicInteger width = columnWidths.get(columnIndex++); for ( String value : valueList ) { width.set(Math.max(value.length(), width.intValue())); } } return columnWidths; } }
5,735
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationKeyPart.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; /** * A portion of a configuration name */ public class ConfigurationKeyPart { private final String value; private final boolean isVariable; /** * @param value the string or variable name * @param variable true if this is a variable substitution */ public ConfigurationKeyPart(String value, boolean variable) { this.value = value; isVariable = variable; } /** * @return the name or variable name */ public String getValue() { return value; } /** * @return true if this is a variable substitution */ public boolean isVariable() { return isVariable; } @Override public String toString() { return "ConfigurationKeyPart [value=" + value + ", isVariable=" + isVariable + "]"; } }
5,736
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationProvider.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import com.google.common.base.Supplier; import com.google.inject.ImplementedBy; import com.netflix.governator.annotations.Configuration; import com.netflix.governator.lifecycle.LifecycleConfigurationProviders; import java.util.Date; /** * Abstraction for get configuration values to use for fields annotated * with {@link Configuration} */ @ImplementedBy(LifecycleConfigurationProviders.class) public interface ConfigurationProvider { /** * Return true if there is a configuration value set for the given key * * @param key configuration key * @return true/false */ public boolean has(ConfigurationKey key); /** * Return the given configuration as a boolean. Use this when the configuration * value is expected to change at run time. * * @param key configuration key * @return value */ public Supplier<Boolean> getBooleanSupplier(ConfigurationKey key, Boolean defaultValue); /** * Return the given configuration as an integer. Use this when the configuration * value is expected to change at run time. * * @param key configuration key * @return value */ public Supplier<Integer> getIntegerSupplier(ConfigurationKey key, Integer defaultValue); /** * Return the given configuration as a long. Use this when the configuration * value is expected to change at run time. * * @param key configuration key * @return value */ public Supplier<Long> getLongSupplier(ConfigurationKey key, Long defaultValue); /** * Return the given configuration as a double. Use this when the configuration * value is expected to change at run time. * * @param key configuration key * @return value */ public Supplier<Double> getDoubleSupplier(ConfigurationKey key, Double defaultValue); /** * Return the given configuration as a string. Use this when the configuration * value is expected to change at run time. * * @param key configuration key * @return value */ public Supplier<String> getStringSupplier(ConfigurationKey key, String defaultValue); /** * Return the given configuration as a date. Use this when the configuration * value is expected to change at run time. * * @param key configuration key * @return value */ public Supplier<Date> getDateSupplier(ConfigurationKey key, Date defaultValue); /** * Return the given configuration as an object of the given type. * * @param key configuration key * @param defaultValue value to return when key is not found * @param objectType Class of the configuration to return * @param <T> type of the configuration to return * @return the object for this configuration. */ public <T> Supplier<T> getObjectSupplier(ConfigurationKey key, T defaultValue, Class<T> objectType); }
5,737
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/KeyParser.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import com.google.common.collect.Lists; import java.util.List; import java.util.Map; public class KeyParser { public static List<ConfigurationKeyPart> parse(String raw) { return parse(raw, null); } /** * Parse a key into parts * * @param raw the key * @return parts */ public static List<ConfigurationKeyPart> parse(String raw, Map<String, String> contextOverrides) { List<ConfigurationKeyPart> parts = Lists.newArrayList(); int caret = 0; for (; ; ) { int startIndex = raw.indexOf("${", caret); if ( startIndex < 0 ) { break; } int endIndex = raw.indexOf("}", startIndex); if ( endIndex < 0 ) { break; } if ( startIndex > caret ) { parts.add(new ConfigurationKeyPart(raw.substring(caret, startIndex), false)); } startIndex += 2; if ( startIndex < endIndex ) { String name = raw.substring(startIndex, endIndex); if (contextOverrides != null && contextOverrides.containsKey(name)) { parts.add(new ConfigurationKeyPart(contextOverrides.get(name), false)); } else { parts.add(new ConfigurationKeyPart(name, true)); } } caret = endIndex + 1; } if ( caret < raw.length() ) { parts.add(new ConfigurationKeyPart(raw.substring(caret), false)); } if ( parts.size() == 0 ) { parts.add(new ConfigurationKeyPart("", false)); } return parts; } private KeyParser() { } }
5,738
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/CompositeConfigurationProvider.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * A configuration provider that composites multiple providers. The first * provider (in order) that has a configuration set (via {@link #has(ConfigurationKey)} is used * to return the configuration. */ public class CompositeConfigurationProvider implements ConfigurationProvider { private final List<ConfigurationProvider> providers; /** * @param providers ordered providers */ public CompositeConfigurationProvider(ConfigurationProvider... providers) { this(Lists.newArrayList(Arrays.asList(providers))); } /** * @param providers ordered providers */ public CompositeConfigurationProvider(Collection<ConfigurationProvider> providers) { this.providers = new CopyOnWriteArrayList<ConfigurationProvider>(providers); } @VisibleForTesting public void add(ConfigurationProvider configurationProvider) { providers.add(0, configurationProvider); } @Override public boolean has(ConfigurationKey key) { for ( ConfigurationProvider provider : providers ) { if ( provider.has(key) ) { return true; } } return false; } @Override public Supplier<Boolean> getBooleanSupplier(ConfigurationKey key, Boolean defaultValue) { for ( ConfigurationProvider provider : providers ) { if ( provider.has(key) ) { return provider.getBooleanSupplier(key, defaultValue); } } return null; } @Override public Supplier<Integer> getIntegerSupplier(ConfigurationKey key, Integer defaultValue) { for ( ConfigurationProvider provider : providers ) { if ( provider.has(key) ) { return provider.getIntegerSupplier(key, defaultValue); } } return null; } @Override public Supplier<Long> getLongSupplier(ConfigurationKey key, Long defaultValue) { for ( ConfigurationProvider provider : providers ) { if ( provider.has(key) ) { return provider.getLongSupplier(key, defaultValue); } } return null; } @Override public Supplier<Double> getDoubleSupplier(ConfigurationKey key, Double defaultValue) { for ( ConfigurationProvider provider : providers ) { if ( provider.has(key) ) { return provider.getDoubleSupplier(key, defaultValue); } } return null; } @Override public Supplier<String> getStringSupplier(ConfigurationKey key, String defaultValue) { for ( ConfigurationProvider provider : providers ) { if ( provider.has(key) ) { return provider.getStringSupplier(key, defaultValue); } } return null; } @Override public Supplier<Date> getDateSupplier(ConfigurationKey key, Date defaultValue) { for ( ConfigurationProvider provider : providers ) { if ( provider.has(key) ) { return provider.getDateSupplier(key, defaultValue); } } return null; } @Override public <T> Supplier<T> getObjectSupplier(ConfigurationKey key, T defaultValue, Class<T> objectType) { for ( ConfigurationProvider provider : providers ) { if ( provider.has(key) ) { return provider.getObjectSupplier(key, defaultValue, objectType); } } return null; } }
5,739
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationKey.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.configuration; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.List; import java.util.Map; /** * Abstracts configuration names with variable replacements */ public class ConfigurationKey { private final Logger log = LoggerFactory.getLogger(getClass()); private final String rawKey; private final List<ConfigurationKeyPart> parts; /** * @param rawKey the unprocessed value * @param parts the parsed values */ public ConfigurationKey(String rawKey, List<ConfigurationKeyPart> parts) { this.rawKey = rawKey; this.parts = ImmutableList.copyOf(parts); } /** * @return the unprocessed key */ public String getRawKey() { return rawKey; } /** * Return the final key applying variables as needed * * @param variableValues map of variable names to values * @return the key */ public String getKey(Map<String, String> variableValues) { StringBuilder key = new StringBuilder(); for ( ConfigurationKeyPart p : parts ) { if ( p.isVariable() ) { String value = variableValues.get(p.getValue()); if ( value == null ) { log.warn("No value found for variable: " + p.getValue()); value = ""; } key.append(value); } else { key.append(p.getValue()); } } return key.toString(); } /** * @return the parsed key parts */ public List<ConfigurationKeyPart> getParts() { return parts; } /** * Return the names of the variables specified in the key if any * * @return names (might be zero sized) */ public Collection<String> getVariableNames() { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); for ( ConfigurationKeyPart p : parts ) { if ( p.isVariable() ) { builder.add(p.getValue()); } } return builder.build(); } @Override public String toString() { return rawKey; } }
5,740
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/DefaultConfigurationProvider.java
package com.netflix.governator.configuration; import java.util.Date; import com.google.common.base.Supplier; /** * This is a hack in preparation for removing Supplier from the API. * * @author elandau * */ public abstract class DefaultConfigurationProvider implements ConfigurationProvider { @Override public boolean has(ConfigurationKey key) { return false; } @Override public Supplier<Boolean> getBooleanSupplier(ConfigurationKey key, Boolean defaultValue) { return Property.from(getBooleanProperty(key, defaultValue)); } @Override public Supplier<Integer> getIntegerSupplier(ConfigurationKey key, Integer defaultValue) { return Property.from(getIntegerProperty(key, defaultValue)); } @Override public Supplier<Long> getLongSupplier(ConfigurationKey key, Long defaultValue) { return Property.from(getLongProperty(key, defaultValue)); } @Override public Supplier<Double> getDoubleSupplier(ConfigurationKey key, Double defaultValue) { return Property.from(getDoubleProperty(key, defaultValue)); } @Override public Supplier<String> getStringSupplier(ConfigurationKey key, String defaultValue) { return Property.from(getStringProperty(key, defaultValue)); } @Override public Supplier<Date> getDateSupplier(ConfigurationKey key, Date defaultValue) { return Property.from(getDateProperty(key, defaultValue)); } @Override public <T> Supplier<T> getObjectSupplier(ConfigurationKey key, T defaultValue, Class<T> objectType) { return Property.from(getObjectProperty(key, defaultValue, objectType)); } public abstract Property<Boolean> getBooleanProperty(ConfigurationKey key, Boolean defaultValue); public abstract Property<Integer> getIntegerProperty(ConfigurationKey key, Integer defaultValue); public abstract Property<Long> getLongProperty(ConfigurationKey key, Long defaultValue); public abstract Property<Double> getDoubleProperty(ConfigurationKey key, Double defaultValue); public abstract Property<String> getStringProperty(ConfigurationKey key, String defaultValue); public abstract Property<Date> getDateProperty(ConfigurationKey key, Date defaultValue); public abstract <T> Property<T> getObjectProperty(ConfigurationKey key, T defaultValue, Class<T> objectType); }
5,741
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/ConfigurationColumnWriter.java
package com.netflix.governator.configuration; import java.io.PrintWriter; import java.util.Map; import org.slf4j.Logger; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.netflix.governator.configuration.ConfigurationDocumentation.Entry; /** * Simple implementation of a configuration writer that outputs in column format * * @author elandau * */ public class ConfigurationColumnWriter { private final ConfigurationDocumentation config; @Inject public ConfigurationColumnWriter(ConfigurationDocumentation config) { this.config = config; } /** * Write the documentation table to a logger * @param log */ public void output(Logger log) { Map<String, Entry> entries = config.getSortedEntries(); if ( entries.isEmpty() ) { return; } ColumnPrinter printer = build(entries); log.debug("Configuration Details"); for ( String line : printer.generate() ) { log.debug(line); } } /** * Write the documentation table to System.out */ public void output() { output(new PrintWriter(System.out)); } /** * Output documentation table to a PrintWriter * * @param out */ public void output(PrintWriter out) { Map<String, Entry> entries = config.getSortedEntries(); if ( entries.isEmpty() ) { return; } ColumnPrinter printer = build(entries); out.println("Configuration Details"); printer.print(out); } /** * Construct a ColumnPrinter using the entries * * @param entries * @return */ private ColumnPrinter build(Map<String, Entry> entries) { ColumnPrinter printer = new ColumnPrinter(); printer.addColumn("PROPERTY"); printer.addColumn("FIELD"); printer.addColumn("DEFAULT"); printer.addColumn("VALUE"); printer.addColumn("DESCRIPTION"); Map<String, Entry> sortedEntries = Maps.newTreeMap(); sortedEntries.putAll(entries); for ( Entry entry : sortedEntries.values() ) { printer.addValue(0, entry.configurationName); printer.addValue(1, entry.field.getDeclaringClass().getName() + "#" + entry.field.getName()); printer.addValue(2, entry.defaultValue); printer.addValue(3, entry.has ? entry.value : ""); printer.addValue(4, entry.documentation); } return printer; } }
5,742
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/configuration/AbstractObjectConfigurationProvider.java
package com.netflix.governator.configuration; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; /** * Implements the deserialization part of {@link ConfigurationProvider} to simplify implementations. * * Created by jad.naous on 4/2/14. */ public abstract class AbstractObjectConfigurationProvider extends DefaultConfigurationProvider { private final Logger logger; private final ObjectMapper mapper; protected AbstractObjectConfigurationProvider() { this(null); } protected AbstractObjectConfigurationProvider(ObjectMapper mapper) { if (mapper == null) { this.mapper = new ObjectMapper(); } else { this.mapper = mapper; } this.logger = LoggerFactory.getLogger(getClass()); } @Override public <T> Property<T> getObjectProperty(final ConfigurationKey key, final T defaultValue, final Class<T> objectType) { return new Property<T>() { @Override public T get() { String serialized = getStringSupplier(key, null).get(); if (serialized == null || serialized.length() == 0) { return defaultValue; } try { return mapper.readValue(serialized, objectType); } catch (IOException e) { logger.warn("Could not deserialize configuration with key " + key.getRawKey() + " to type " + objectType, e); return defaultValue; } } }; } }
5,743
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/AutoBindProvider.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import com.google.inject.Binder; import com.netflix.governator.annotations.AutoBind; import java.lang.annotation.Annotation; /** * Used to perform the binding for a given {@link AutoBind} annotation */ public interface AutoBindProvider<T extends Annotation> { /** * Called for auto binding of constructor arguments * * @param binder the Guice binder * @param autoBindAnnotation the @AutoBind or custom annotation */ public void configure(Binder binder, T autoBindAnnotation); }
5,744
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/AutoBinds.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import com.netflix.governator.annotations.AutoBind; /** * Used to build an {@link AutoBind} instance. Normally you won't * use this directly. */ public class AutoBinds { public static AutoBind withValue(String value) { return new AutoBindImpl(value); } private AutoBinds() { } }
5,745
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/LifecycleInjectorBuilderSuite.java
package com.netflix.governator.guice; /** * Each concrete LifecycleInjectorSuite represent a specific set operations * on a LifecycleInjectorBuilder that should logically be grouped together. * Multiple suites can then be applied to the LifecycleInjectorBuilder. * * @author elandau * * @deprecated This class is deprecated in favor of using {@link BootstrapModule} or just {@link ModuleInfo}. All the * {@link LifecycleInjectorBuilder} functionality is now available via the {@link BootstrapBinder} * passed to {@link BootstrapModule} */ @Deprecated public interface LifecycleInjectorBuilderSuite { /** * Override this to perform any combination of operations on the * LifecycleInjectorBuilder * * @param builder */ public void configure(LifecycleInjectorBuilder builder); }
5,746
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/LifecycleInjectorBuilderImpl.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.netflix.governator.lifecycle.ClasspathScanner; import java.util.Arrays; import java.util.Collection; import java.util.List; class LifecycleInjectorBuilderImpl implements LifecycleInjectorBuilder { private ModuleListBuilder modules = new ModuleListBuilder(); private Collection<Class<?>> ignoreClasses = Lists.newArrayList(); private Collection<String> basePackages = Lists.newArrayList(); private boolean disableAutoBinding = false; private boolean requireExplicitBindings = false; private List<BootstrapModule> bootstrapModules = Lists.newArrayList(); private ClasspathScanner scanner = null; private Stage stage = Stage.PRODUCTION; @SuppressWarnings("deprecation") private LifecycleInjectorMode lifecycleInjectorMode = LifecycleInjectorMode.REAL_CHILD_INJECTORS; private List<PostInjectorAction> actions = ImmutableList.of(); private List<ModuleTransformer> transformers = ImmutableList.of(); public LifecycleInjectorBuilder withBootstrapModule(BootstrapModule module) { this.bootstrapModules = ImmutableList.of(module); return this; } @Override public LifecycleInjectorBuilder withAdditionalBootstrapModules(BootstrapModule... additionalBootstrapModules) { return withAdditionalBootstrapModules(ImmutableList.copyOf(additionalBootstrapModules)); } @Override public LifecycleInjectorBuilder withAdditionalBootstrapModules(Iterable<? extends BootstrapModule> additionalBootstrapModules) { if (additionalBootstrapModules != null) { this.bootstrapModules = ImmutableList.<BootstrapModule>builder() .addAll(this.bootstrapModules) .addAll(additionalBootstrapModules) .build(); } return this; } @Override public LifecycleInjectorBuilder withModules(Module... modules) { this.modules = new ModuleListBuilder().includeModules(ImmutableList.copyOf(modules)); return this; } @Override public LifecycleInjectorBuilder withModules(Iterable<? extends Module> modules) { if (modules != null) { this.modules = new ModuleListBuilder().includeModules(modules); } return this; } @Override public LifecycleInjectorBuilder withAdditionalModules(Iterable<? extends Module> additionalModules) { if (additionalModules != null) { try { this.modules.includeModules(additionalModules); } catch (Exception e) { throw new RuntimeException(e); } } return this; } @Override public LifecycleInjectorBuilder withAdditionalModules(Module... modules) { return withAdditionalModules(ImmutableList.copyOf(modules)); } @Override public LifecycleInjectorBuilder withRootModule(Class<?> rootModule) { if (rootModule == null) return this; return withModuleClass((Class<? extends Module>) rootModule); } @Override public LifecycleInjectorBuilder withModuleClass(Class<? extends Module> module) { if (module != null) { this.modules.include(module); } return this; } @Override public LifecycleInjectorBuilder withModuleClasses(Iterable<Class<? extends Module>> modules) { if (modules != null) { this.modules.include(modules); } return this; } @Override public LifecycleInjectorBuilder withModuleClasses(Class<?> ... modules) { this.modules.include(ImmutableList.<Class<? extends Module>>copyOf( Iterables.transform(Lists.newArrayList(modules), new Function<Class<?>, Class<? extends Module>>() { @SuppressWarnings("unchecked") @Override public Class<? extends Module> apply(Class<?> input) { return (Class<? extends Module>) input; } } ))); return this; } @Override public LifecycleInjectorBuilder withAdditionalModuleClasses(Iterable<Class<? extends Module>> modules) { this.modules.include(modules); return this; } @Override public LifecycleInjectorBuilder withAdditionalModuleClasses(Class<?> ... modules) { this.modules.include(ImmutableList.<Class<? extends Module>>builder() .addAll(Iterables.transform(Lists.newArrayList(modules), new Function<Class<?>, Class<? extends Module>>() { @SuppressWarnings("unchecked") @Override public Class<? extends Module> apply(Class<?> input) { return (Class<? extends Module>) input; } })) .build()); return this; } @Override public LifecycleInjectorBuilder withoutModuleClasses(Class<? extends Module> ... modules) { this.modules.exclude(ImmutableList.copyOf(modules)); return this; } @Override public LifecycleInjectorBuilder withoutModuleClass(Class<? extends Module> module) { this.modules.exclude(module); return this; } @Override public LifecycleInjectorBuilder withoutModuleClasses(Iterable<Class<? extends Module>> modules) { this.modules.exclude(modules); return this; } @Override public LifecycleInjectorBuilder ignoringAutoBindClasses(Collection<Class<?>> ignoreClasses) { this.ignoreClasses = ImmutableList.copyOf(ignoreClasses); return this; } @Override public LifecycleInjectorBuilder ignoringAllAutoBindClasses() { this.disableAutoBinding = true; return this; } @Override public LifecycleInjectorBuilder requiringExplicitBindings() { this.requireExplicitBindings = true; return this; } @Override public LifecycleInjectorBuilder usingBasePackages(String... basePackages) { return usingBasePackages(Arrays.asList(basePackages)); } @Override public LifecycleInjectorBuilder usingBasePackages(Collection<String> basePackages) { this.basePackages = Lists.newArrayList(basePackages); return this; } @Override public LifecycleInjectorBuilder usingClasspathScanner(ClasspathScanner scanner) { this.scanner = scanner; return this; } @Override public LifecycleInjectorBuilder withMode(LifecycleInjectorMode mode) { this.lifecycleInjectorMode = mode; return this; } @Override public LifecycleInjectorBuilder inStage(Stage stage) { this.stage = stage; return this; } @Override public LifecycleInjectorBuilder withModuleTransformer(ModuleTransformer filter) { if (filter != null) { this.transformers = ImmutableList.<ModuleTransformer>builder() .addAll(this.transformers) .add(filter) .build(); } return this; } @Override public LifecycleInjectorBuilder withModuleTransformer(Collection<? extends ModuleTransformer> filters) { if (this.transformers != null) { this.transformers = ImmutableList.<ModuleTransformer>builder() .addAll(this.transformers) .addAll(filters) .build(); } return this; } @Override public LifecycleInjectorBuilder withModuleTransformer(ModuleTransformer... filters) { if (this.transformers != null) { this.transformers = ImmutableList.<ModuleTransformer>builder() .addAll(this.transformers) .addAll(ImmutableList.copyOf(filters)) .build(); } return this; } @Override public LifecycleInjectorBuilder withPostInjectorAction(PostInjectorAction action) { this.actions = ImmutableList.<PostInjectorAction>builder() .addAll(this.actions) .add(action) .build(); return this; } @Override public LifecycleInjectorBuilder withPostInjectorActions(Collection<? extends PostInjectorAction> actions) { if (actions != null) { this.actions = ImmutableList.<PostInjectorAction>builder() .addAll(this.actions) .addAll(actions) .build(); } return this; } @Override public LifecycleInjectorBuilder withPostInjectorActions(PostInjectorAction... actions) { this.actions = ImmutableList.<PostInjectorAction>builder() .addAll(this.actions) .addAll(ImmutableList.copyOf(actions)) .build(); return this; } @Override public LifecycleInjector build() { try { return new LifecycleInjector(this); } catch (Exception e) { throw new RuntimeException(e); } } @Override @Deprecated public Injector createInjector() { return build().createInjector(); } LifecycleInjectorBuilderImpl() { } ModuleListBuilder getModuleListBuilder() { return modules; } Collection<Class<?>> getIgnoreClasses() { return ignoreClasses; } Collection<String> getBasePackages() { return basePackages; } List<BootstrapModule> getBootstrapModules() { return bootstrapModules; } ClasspathScanner getClasspathScanner() { return scanner; } Stage getStage() { return stage; } LifecycleInjectorMode getLifecycleInjectorMode() { return lifecycleInjectorMode; } List<PostInjectorAction> getPostInjectorActions() { return actions; } List<ModuleTransformer> getModuleTransformers() { return transformers; } boolean isDisableAutoBinding() { return this.disableAutoBinding; } boolean isRequireExplicitBindings() { return this.requireExplicitBindings; } }
5,747
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/AutoBindImpl.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import com.netflix.governator.annotations.AutoBind; import java.lang.annotation.Annotation; @SuppressWarnings("ClassExplicitlyAnnotation") class AutoBindImpl implements AutoBind { private final String value; AutoBindImpl(String value) { this.value = value; } public String value() { return this.value; } public int hashCode() { // This is specified in java.lang.Annotation. return (127 * "value".hashCode()) ^ value.hashCode(); } public boolean equals(Object o) { if ( !(o instanceof AutoBind) ) { return false; } AutoBind other = (AutoBind)o; return value.equals(other.value()); } public String toString() { return "@" + AutoBind.class.getName() + "(value=" + value + ")"; } public Class<? extends Annotation> annotationType() { return AutoBind.class; } @SuppressWarnings("UnusedDeclaration") private static final long serialVersionUID = 0; }
5,748
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/MemberInjectingInstanceProvider.java
package com.netflix.governator.guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderWithExtensionVisitor; import com.google.inject.spi.Toolable; /** * Specialized {@link Provider} for an existing object instance that * will force member injection before injecting the instance * @author elandau * */ class MemberInjectingInstanceProvider<T> implements ProviderWithExtensionVisitor<T> { private final T module; public MemberInjectingInstanceProvider(T module) { this.module = module; } @Override public T get() { return module; } @Override public <B, V> V acceptExtensionVisitor( BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) { return visitor.visit(binding); } @Inject @Toolable void initialize(Injector injector) { injector.injectMembers(module); } }
5,749
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/BootstrapBinder.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Collection; import org.aopalliance.intercept.MethodInterceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.inject.Binder; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.MembersInjector; import com.google.inject.Module; import com.google.inject.PrivateBinder; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.Stage; import com.google.inject.TypeLiteral; import com.google.inject.binder.AnnotatedBindingBuilder; import com.google.inject.binder.AnnotatedConstantBindingBuilder; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.matcher.Matcher; import com.google.inject.multibindings.Multibinder; import com.google.inject.spi.Dependency; import com.google.inject.spi.Message; import com.google.inject.spi.ModuleAnnotatedMethodScanner; import com.google.inject.spi.ProvisionListener; import com.google.inject.spi.TypeConverter; import com.google.inject.spi.TypeListener; import com.netflix.governator.configuration.ConfigurationProvider; import com.netflix.governator.lifecycle.LifecycleListener; import com.netflix.governator.lifecycle.ResourceLocator; public class BootstrapBinder implements Binder { private final Logger log = LoggerFactory.getLogger(getClass()); private final Binder binder; private Stage stage; private LifecycleInjectorMode mode; private ModuleListBuilder modules; private boolean disableAutoBinding; BootstrapBinder(Binder binder, Stage stage, LifecycleInjectorMode mode, ModuleListBuilder modules, Collection<PostInjectorAction> actions, Collection<ModuleTransformer> transformers, boolean disableAutoBinding) { this.binder = binder; this.mode = mode; this.stage = stage; this.modules = modules; Multibinder<ModuleTransformer> transformerBinder = Multibinder.newSetBinder(binder, ModuleTransformer.class); Multibinder<PostInjectorAction> actionBinder = Multibinder.newSetBinder(binder, PostInjectorAction.class); for (PostInjectorAction action : actions) { actionBinder.addBinding().toInstance(action); } for (ModuleTransformer transformer : transformers) { transformerBinder.addBinding().toInstance(transformer); } } private String getBindingLocation() { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for (int i = 1; i < stack.length ; i++) { StackTraceElement elem = stack[i]; if (!elem.getClassName().equals(BootstrapBinder.class.getCanonicalName())) return elem.toString(); } return stack[0].toString(); } @Override public void bindInterceptor(Matcher<? super Class<?>> classMatcher, Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors) { binder.bindInterceptor(classMatcher, methodMatcher, interceptors); } @Override public void bindScope(Class<? extends Annotation> annotationType, Scope scope) { binder.bindScope(annotationType, scope); } /** * Bind actions to perform after the injector is created. * * @return a binding builder used to add a new element in the set. */ public LinkedBindingBuilder<PostInjectorAction> bindPostInjectorAction() { return Multibinder.newSetBinder(binder, PostInjectorAction.class).addBinding(); } /** * Bind module transform operations to perform on the final list of modul. * * @return a binding builder used to add a new element in the set. */ public LinkedBindingBuilder<ModuleTransformer> bindModuleTransformer() { return Multibinder.newSetBinder(binder, ModuleTransformer.class).addBinding(); } /** * Use this to bind a {@link LifecycleListener}. It internally uses a Multibinder to do the * binding so that you can bind multiple LifecycleListeners * * @return a binding builder used to add a new element in the set. */ public LinkedBindingBuilder<LifecycleListener> bindLifecycleListener() { return Multibinder.newSetBinder(binder, LifecycleListener.class).addBinding(); } /** * Use this to bind a {@link ResourceLocator}. It internally uses a Multibinder to do the * binding so that you can bind multiple ResourceLocators * * @return a binding builder used to add a new element in the set. */ public LinkedBindingBuilder<ResourceLocator> bindResourceLocator() { return Multibinder.newSetBinder(binder, ResourceLocator.class).addBinding(); } /** * Use this to bind {@link ConfigurationProvider}s. Do NOT use standard Guice binding. * * @return configuration binding builder */ public LinkedBindingBuilder<ConfigurationProvider> bindConfigurationProvider() { return Multibinder.newSetBinder(binder, ConfigurationProvider.class).addBinding(); } @Override public <T> LinkedBindingBuilder<T> bind(Key<T> key) { warnOnSpecialized(key.getTypeLiteral().getRawType()); return binder.withSource(getBindingLocation()).bind(key); } @Override public <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral) { warnOnSpecialized(typeLiteral.getRawType()); return binder.withSource(getBindingLocation()).bind(typeLiteral); } @Override public <T> AnnotatedBindingBuilder<T> bind(Class<T> type) { warnOnSpecialized(type); return binder.withSource(getBindingLocation()).bind(type); } @Override public AnnotatedConstantBindingBuilder bindConstant() { return binder.withSource(getBindingLocation()).bindConstant(); } @Override public <T> void requestInjection(TypeLiteral<T> type, T instance) { binder.withSource(getBindingLocation()).requestInjection(type, instance); } @Override public void requestInjection(Object instance) { binder.withSource(getBindingLocation()).requestInjection(instance); } @Override public void requestStaticInjection(Class<?>... types) { binder.withSource(getBindingLocation()).requestStaticInjection(types); } @Override public void install(Module module) { binder.withSource(getBindingLocation()).install(module); } public void include(Class<? extends Module> module) { this.modules.include(module); } public void include(Class<? extends Module> ... modules) { this.modules.include(Lists.newArrayList(modules)); } public void include(Collection<Class<? extends Module>> modules) { this.modules.include(modules); } public void include(Module module) { this.modules.include(module); } public void includeModules(Collection<? extends Module> modules) { this.modules.includeModules(modules); } public void includeModules(Module ... modules) { this.modules.includeModules(Lists.newArrayList(modules)); } public void exclude(Class<? extends Module> module) { this.modules.exclude(module); } public void exclude(Class<? extends Module> ... modules) { this.modules.exclude(Lists.newArrayList(modules)); } public void exclude(Collection<Class<? extends Module>> modules) { this.modules.exclude(modules); } public void inStage(Stage stage) { this.stage = stage; } public void inMode(LifecycleInjectorMode mode) { this.mode = mode; } @Override public Stage currentStage() { return binder.currentStage(); } @Override public void addError(String message, Object... arguments) { binder.addError(message, arguments); } @Override public void addError(Throwable t) { binder.addError(t); } @Override public void addError(Message message) { binder.addError(message); } @Override public <T> Provider<T> getProvider(Key<T> key) { return binder.getProvider(key); } @Override public <T> Provider<T> getProvider(Class<T> type) { return binder.getProvider(type); } @Override public <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral) { return binder.getMembersInjector(typeLiteral); } @Override public <T> MembersInjector<T> getMembersInjector(Class<T> type) { return binder.getMembersInjector(type); } @Override public void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter converter) { binder.convertToTypes(typeMatcher, converter); } @Override public void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher, TypeListener listener) { binder.withSource(getBindingLocation()).bindListener(typeMatcher, listener); } @Override public Binder withSource(Object source) { return binder.withSource(source); } @Override public Binder skipSources(@SuppressWarnings("rawtypes") Class... classesToSkip) { return binder.skipSources(classesToSkip); } @Override public PrivateBinder newPrivateBinder() { return binder.newPrivateBinder(); } @Override public void requireExplicitBindings() { binder.requireExplicitBindings(); } @Override public void disableCircularProxies() { binder.disableCircularProxies(); } public void disableAutoBinding() { disableAutoBinding = true; } private<T> void warnOnSpecialized(Class<T> clazz) { if ( ConfigurationProvider.class.isAssignableFrom(clazz) ) { log.warn("You should use the specialized binding method for ConfigurationProviders"); } if ( LifecycleListener.class.isAssignableFrom(clazz) ) { log.warn("You should use the specialized binding method for LifecycleListener"); } if ( ResourceLocator.class.isAssignableFrom(clazz) ) { log.warn("You should use the specialized binding method for ResourceLocator"); } } Stage getStage() { return stage; } LifecycleInjectorMode getMode() { return mode; } boolean isDisabledAutoBinding() { return disableAutoBinding; } @Override public <T> Provider<T> getProvider(Dependency<T> dependency) { return binder.getProvider(dependency); } @Override public void bindListener(Matcher<? super Binding<?>> bindingMatcher, ProvisionListener... listeners) { binder.bindListener(bindingMatcher, listeners); } @Override public void requireAtInjectOnConstructors() { binder.requireAtInjectOnConstructors(); } @Override public void requireExactBindingAnnotations() { binder.requireExactBindingAnnotations(); } @Override public void scanModulesForAnnotatedMethods( ModuleAnnotatedMethodScanner scanner) { binder.scanModulesForAnnotatedMethods(scanner); } }
5,750
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/LifecycleInjector.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Resource; import javax.annotation.Resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.AbstractModule; import com.google.inject.Binding; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.Scopes; import com.google.inject.Stage; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder; import com.netflix.governator.LifecycleListenerModule; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.configuration.ConfigurationMapper; import com.netflix.governator.configuration.ConfigurationProvider; import com.netflix.governator.guice.annotations.Bootstrap; 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; import com.netflix.governator.lifecycle.ClasspathScanner; import com.netflix.governator.lifecycle.LifecycleManager; /** * <p> * When using Governator, do NOT create a Guice injector manually. Instead, use a LifecycleInjector to create a Guice injector. * </p> * * <p> * Governator uses a two pass binding. The bootstrap binding injects: * <li>{@link LifecycleManager}</li> * <li>Any application defined bootstrap instances</li> * <br/> * The main binding injects everything else. * </p> * * <p> * The bootstrap binding occurs when the LifecycleInjector is created. The main binding * occurs when {@link #createInjector()} is called. * </p> */ public class LifecycleInjector { private static final Logger LOG = LoggerFactory.getLogger(LifecycleInjector.class); private final ClasspathScanner scanner; private final List<Module> modules; private final Collection<Class<?>> ignoreClasses; private final boolean ignoreAllClasses; private boolean requireExplicitBindings; private final LifecycleManager lifecycleManager; private final Injector injector; private final Stage stage; private final LifecycleInjectorMode mode; private Set<PostInjectorAction> actions; private Set<ModuleTransformer> transformers; /** * Create a new LifecycleInjector builder * * @return builder */ public static LifecycleInjectorBuilder builder() { return new LifecycleInjectorBuilderImpl(); } public static Injector bootstrap(final Class<?> main) { return bootstrap(main, (Module)null); } public static Injector bootstrap(final Class<?> main, final BootstrapModule... externalBootstrapModules) { return bootstrap(main, null, externalBootstrapModules); } @SuppressWarnings("unused") private static BootstrapModule forAnnotation(final Annotation annot) { final Class<? extends Annotation> type = annot.annotationType(); return new BootstrapModule() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void configure(BootstrapBinder binder) { binder.bind(Key.get(type)) .toProvider(new Provider() { @Override public Object get() { return annot; } }) .in(Scopes.SINGLETON); } }; } /** * This is a shortcut to configuring the LifecycleInjectorBuilder using annotations. * * Using bootstrap a main application class can simply be annotated with * custom annotations that are mapped to {@link BootstrapModule}s. * Each annotations can then map to a subsystem or feature that is enabled on * the main application class. {@link BootstrapModule}s are installed in the order in which * they are defined. * * @see {@link Bootstrap} * @param main Main application bootstrap class * @param externalBindings Bindings that are provided externally by the caller to bootstrap. These * bindings are injectable into the BootstrapModule instances * @param externalBootstrapModules Optional modules that are processed after all the main class bootstrap modules * @return The created injector */ @Beta public static Injector bootstrap(final Class<?> main, final Module externalBindings, final BootstrapModule... externalBootstrapModules) { final LifecycleInjectorBuilder builder = LifecycleInjector.builder(); // Create a temporary Guice injector for the purpose of constructing the list of // BootstrapModules which can inject any of the bootstrap annotations as well as // the externally provided bindings. // Creation order, // 1. Construct all BootstrapModule classes // 2. Inject external bindings into BootstrapModule instances // 3. Create the bootstrap injector with these modules Injector injector = Guice.createInjector(new AbstractModule() { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected void configure() { if (externalBindings != null) install(externalBindings); Multibinder<BootstrapModule> bootstrapModules = Multibinder.newSetBinder(binder(), BootstrapModule.class); Multibinder<LifecycleInjectorBuilderSuite> suites = Multibinder.newSetBinder(binder(), LifecycleInjectorBuilderSuite.class); if (externalBootstrapModules != null) { for (final BootstrapModule bootstrapModule : externalBootstrapModules) { bootstrapModules .addBinding() .toProvider(new MemberInjectingInstanceProvider<BootstrapModule>(bootstrapModule)); } } // Iterate through all annotations of the main class and convert them into // their BootstrapModules for (final Annotation annot : main.getDeclaredAnnotations()) { final Class<? extends Annotation> type = annot.annotationType(); LOG.info("Found bootstrap annotation {}", type.getName()); Bootstrap bootstrap = type.getAnnotation(Bootstrap.class); if (bootstrap != null) { boolean added = false; // This is a suite if (!bootstrap.value().equals(Bootstrap.NullLifecycleInjectorBuilderSuite.class)) { LOG.info("Adding Suite {}", bootstrap.bootstrap()); suites .addBinding() .to(bootstrap.value()) .asEagerSingleton(); added = true; } // This is a bootstrap module if (!bootstrap.bootstrap().equals(Bootstrap.NullBootstrapModule.class)) { Preconditions.checkState(added==false, "%s already added as a LifecycleInjectorBuilderSuite", bootstrap.annotationType().getName()); added = true; LOG.info("Adding BootstrapModule {}", bootstrap.bootstrap()); bootstrapModules .addBinding() .to(bootstrap.bootstrap()) .asEagerSingleton(); // Make this annotation injectable into any plain Module builder.withAdditionalBootstrapModules(forAnnotation(annot)); } // This is a plain guice module if (!bootstrap.module().equals(Bootstrap.NullModule.class)) { Preconditions.checkState(added==false, "%s already added as a BootstrapModule", bootstrap.annotationType().getName()); added = true; LOG.info("Adding Module {}", bootstrap.bootstrap()); builder.withAdditionalModuleClasses(bootstrap.module()); // Make the annotation injectable into the module builder.withAdditionalBootstrapModules(forAnnotation(annot)); } // Makes the annotation injectable into LifecycleInjectorBuilderSuite bind(Key.get(type)) .toProvider(new Provider() { @Override public Object get() { return annot; } }) .in(Scopes.SINGLETON); } } } }); // First, give all LifecycleInjectorBuilderSuite's priority Set<LifecycleInjectorBuilderSuite> suites = injector.getInstance(Key.get(new TypeLiteral<Set<LifecycleInjectorBuilderSuite>>() {})); for (LifecycleInjectorBuilderSuite suite : suites) { suite.configure(builder); } // Next, install BootstrapModule's builder.withAdditionalBootstrapModules(injector.getInstance(Key.get(new TypeLiteral<Set<BootstrapModule>>() {}))); // The main class is added last so it can override any bindings from the BootstrapModule's and LifecycleInjectorBuilderSuite's if (Module.class.isAssignableFrom(main)) { try { builder.withAdditionalModuleClasses(main); } catch (Exception e) { throw new ProvisionException(String.format("Failed to create module for main class '%s'", main.getName()), e); } } // Finally, create and return the injector return builder.build().createInjector(); } /** * If you need early access to the CLASSPATH scanner. For performance reasons, you should * pass the scanner to the builder via {@link LifecycleInjectorBuilder#usingClasspathScanner(ClasspathScanner)}. * * @param basePackages packages to recursively scan * @return scanner */ public static ClasspathScanner createStandardClasspathScanner(Collection<String> basePackages) { return createStandardClasspathScanner(basePackages, null); } /** * If you need early access to the CLASSPATH scanner. For performance reasons, you should * pass the scanner to the builder via {@link LifecycleInjectorBuilder#usingClasspathScanner(ClasspathScanner)}. * * @param basePackages packages to recursively scan * @param additionalAnnotations any additional annotations to scan for * @return scanner */ public static ClasspathScanner createStandardClasspathScanner(Collection<String> basePackages, List<Class<? extends Annotation>> additionalAnnotations) { List<Class<? extends Annotation>> annotations = Lists.newArrayList(); annotations.add(AutoBindSingleton.class); annotations.add(Inject.class); annotations.add(javax.inject.Inject.class); annotations.add(Resource.class); annotations.add(Resources.class); if ( additionalAnnotations != null ) { annotations.addAll(additionalAnnotations); } return new ClasspathScanner(basePackages, annotations); } /** * Return the internally created lifecycle manager * * @return manager */ public LifecycleManager getLifecycleManager() { return lifecycleManager; } /** * Create an injector that is a child of the bootstrap bindings only * * @param modules binding modules * @return injector */ public Injector createChildInjector(Module... modules) { return createChildInjector(Arrays.asList(modules)); } /** * Create an injector that is a child of the bootstrap bindings only * * @param modules binding modules * @return injector */ public Injector createChildInjector(Collection<Module> modules) { Injector childInjector; Collection<Module> localModules = modules; for (ModuleTransformer transformer : transformers) { localModules = transformer.call(localModules); } //noinspection deprecation if ( mode == LifecycleInjectorMode.REAL_CHILD_INJECTORS ) { childInjector = injector.createChildInjector(localModules); } else { childInjector = createSimulatedChildInjector(localModules); } for (PostInjectorAction action : actions) { action.call(childInjector); } return childInjector; } /** * Create the main injector * * @return injector */ public Injector createInjector() { return createInjector(Lists.<Module>newArrayList()); } /** * Create the main injector * * @param modules any additional modules * @return injector */ public Injector createInjector(Module... modules) { return createInjector(Arrays.asList(modules)); } /** * Create the main injector * * @param additionalModules any additional modules * @return injector */ public Injector createInjector(Collection<Module> additionalModules) { List<Module> localModules = Lists.newArrayList(); // Add the discovered modules FIRST. The discovered modules // are added, and will subsequently be configured, in module dependency // order which will ensure that any singletons bound in these modules // will be created in the same order as the bind() calls are made. // Note that the singleton ordering is only guaranteed for // singleton scope. //Add the LifecycleListener module localModules.add(new LifecycleListenerModule()); localModules.add(new AbstractModule() { @Override public void configure() { if (requireExplicitBindings) { binder().requireExplicitBindings(); } } }); if ( additionalModules != null ) { localModules.addAll(additionalModules); } localModules.addAll(modules); // Finally, add the AutoBind module, which will use classpath scanning // to creating singleton bindings. These singletons will be instantiated // in an indeterminate order but are guaranteed to occur AFTER singletons // bound in any of the discovered modules. if ( !ignoreAllClasses ) { Collection<Class<?>> localIgnoreClasses = Sets.newHashSet(ignoreClasses); localModules.add(new InternalAutoBindModule(injector, scanner, localIgnoreClasses)); } return createChildInjector(localModules); } LifecycleInjector(LifecycleInjectorBuilderImpl builder) { this.scanner = (builder.getClasspathScanner() != null) ? builder.getClasspathScanner() : createStandardClasspathScanner(builder.isDisableAutoBinding() ? Collections.<String>emptyList() : builder.getBasePackages()); AtomicReference<LifecycleManager> lifecycleManagerRef = new AtomicReference<LifecycleManager>(); InternalBootstrapModule internalBootstrapModule = new InternalBootstrapModule( ImmutableList.<BootstrapModule>builder() .addAll(builder.getBootstrapModules()) .add(new LoadersBootstrapModule(scanner)) .add(new InternalAutoBindModuleBootstrapModule(scanner, builder.getIgnoreClasses())) .build(), scanner, builder.getStage(), builder.getLifecycleInjectorMode(), builder.getModuleListBuilder(), builder.getPostInjectorActions(), builder.getModuleTransformers(), builder.isDisableAutoBinding()); this.requireExplicitBindings = builder.isRequireExplicitBindings(); injector = Guice.createInjector ( builder.getStage(), internalBootstrapModule, new InternalLifecycleModule(lifecycleManagerRef) ); this.mode = Preconditions.checkNotNull(internalBootstrapModule.getMode(), "mode cannot be null"); this.stage = Preconditions.checkNotNull(internalBootstrapModule.getStage(), "stage cannot be null"); this.ignoreAllClasses = internalBootstrapModule.isDisableAutoBinding(); this.ignoreClasses = ImmutableList.copyOf(builder.getIgnoreClasses()); Set<PostInjectorAction> actions = injector.getInstance(Key.get(new TypeLiteral<Set<PostInjectorAction>>() {})); this.transformers = injector.getInstance(Key.get(new TypeLiteral<Set<ModuleTransformer>>() {})); try { this.modules = internalBootstrapModule.getModuleListBuilder().build(injector); } catch (Exception e) { throw new ProvisionException("Unable to resolve list of modules", e); } lifecycleManager = injector.getInstance(LifecycleManager.class); this.actions = new LinkedHashSet<>(); this.actions.add(lifecycleManager); this.actions.addAll(actions); lifecycleManagerRef.set(lifecycleManager); } private Injector createSimulatedChildInjector(Collection<Module> modules) { AbstractModule parentObjects = new AbstractModule() { @Override protected void configure() { bindScope(LazySingleton.class, LazySingletonScope.get()); bindScope(FineGrainedLazySingleton.class, FineGrainedLazySingletonScope.get()); // Manually copy bindings from the bootstrap injector to the simulated child injector. Map<Key<?>, Binding<?>> bindings = injector.getAllBindings(); for (Entry<Key<?>, Binding<?>> binding : bindings.entrySet()) { Class<?> cls = binding.getKey().getTypeLiteral().getRawType(); if ( Module.class.isAssignableFrom(cls) || Injector.class.isAssignableFrom(cls) || Stage.class.isAssignableFrom(cls) || Logger.class.isAssignableFrom(cls) || java.util.logging.Logger.class.isAssignableFrom(cls) ) { continue; } Provider provider = binding.getValue().getProvider(); bind(binding.getKey()).toProvider(provider); } } }; AtomicReference<LifecycleManager> lifecycleManagerAtomicReference = new AtomicReference<LifecycleManager>(lifecycleManager); InternalLifecycleModule internalLifecycleModule = new InternalLifecycleModule(lifecycleManagerAtomicReference); List<Module> localModules = Lists.newArrayList(modules); localModules.add(parentObjects); localModules.add(internalLifecycleModule); return Guice.createInjector(stage, localModules); } }
5,751
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/InternalLifecycleModule.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.governator.guice; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.inject.AbstractModule; import com.google.inject.Binding; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.matcher.Matchers; import com.google.inject.spi.ProvisionListener; import com.netflix.governator.lifecycle.LifecycleListener; import com.netflix.governator.lifecycle.LifecycleManager; import com.netflix.governator.lifecycle.LifecycleMethods; import static com.netflix.governator.internal.BinaryConstant.*; class InternalLifecycleModule extends AbstractModule implements ProvisionListener { private static final Logger LOGGER = LoggerFactory.getLogger(InternalLifecycleModule.class); private final LoadingCache<Class<?>, LifecycleMethods> lifecycleMethods = CacheBuilder .newBuilder() .initialCapacity(I13_8192) // number of classes with metadata .concurrencyLevel(I8_256) // number of concurrent metadata producers (no locks for read) .softValues() .build(new CacheLoader<Class<?>, LifecycleMethods>() { @Override public LifecycleMethods load(Class<?> key) throws Exception { return new LifecycleMethods(key); } }); private final AtomicReference<LifecycleManager> lifecycleManager; InternalLifecycleModule(AtomicReference<LifecycleManager> lifecycleManager) { this.lifecycleManager = lifecycleManager; } @Override public void configure() { bindListener( Matchers.any(), this); } @Override public <T> void onProvision(ProvisionInvocation<T> provision) { T instance = provision.provision(); if (instance != null) { Binding<T> binding = provision.getBinding(); LifecycleManager manager = lifecycleManager.get(); if (manager != null) { Key<T> bindingKey = binding.getKey(); LOGGER.trace("provisioning instance of {}", bindingKey); TypeLiteral<T> bindingType = bindingKey.getTypeLiteral(); for (LifecycleListener listener : manager.getListeners()) { listener.objectInjected(bindingType, instance); } try { LifecycleMethods methods = lifecycleMethods.get(instance.getClass()); if (methods.hasLifecycleAnnotations()) { manager.add(instance, binding, methods); } } catch (ExecutionException e) { // caching problem throw new RuntimeException(e); } catch (Throwable e) { // unknown problem will abort injector start up throw new Error(e); } } } } }
5,752
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/LoadersBootstrapModule.java
package com.netflix.governator.guice; import com.google.common.base.Preconditions; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.configuration.ConfigurationProvider; import com.netflix.governator.lifecycle.ClasspathScanner; public class LoadersBootstrapModule implements BootstrapModule { private ClasspathScanner scanner; public LoadersBootstrapModule(ClasspathScanner scanner) { this.scanner = scanner; } @Override public void configure(BootstrapBinder binder) { for ( Class<?> clazz : scanner.getClasses() ) { if ( clazz.isAnnotationPresent(AutoBindSingleton.class) && ConfigurationProvider.class.isAssignableFrom(clazz) ) { AutoBindSingleton annotation = clazz.getAnnotation(AutoBindSingleton.class); Preconditions.checkState(annotation.value() == AutoBindSingleton.class, "@AutoBindSingleton value cannot be set for ConfigurationProviders"); Preconditions.checkState(annotation.baseClass() == AutoBindSingleton.class, "@AutoBindSingleton value cannot be set for ConfigurationProviders"); Preconditions.checkState(!annotation.multiple(), "@AutoBindSingleton(multiple=true) value cannot be set for ConfigurationProviders"); @SuppressWarnings("unchecked") Class<? extends ConfigurationProvider> configurationProviderClass = (Class<? extends ConfigurationProvider>)clazz; binder.bindConfigurationProvider().to(configurationProviderClass).asEagerSingleton(); } } } }
5,753
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/BootstrapModule.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; /** * Abstraction for binding during the bootstrap phase */ public interface BootstrapModule { /** * Called to allow for binding * * @param binder the bootstrap binder */ public void configure(BootstrapBinder binder); }
5,754
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/LifecycleInjectorMode.java
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; public enum LifecycleInjectorMode { /** * @deprecated using Guice child injectors has unwanted side effects. It also makes some patterns (e.g. injecting the Injector) difficult */ REAL_CHILD_INJECTORS, /** * In this mode {@link LifecycleInjector} no longer uses Guice child injectors. Instead, bootstrap objects are copied into a new injector */ SIMULATED_CHILD_INJECTORS }
5,755
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/DelegatingLifecycleInjectorBuilder.java
package com.netflix.governator.guice; import java.util.Collection; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.netflix.governator.lifecycle.ClasspathScanner; /** * Decorator for LifecycleInjectorBuilder which makes the original withModules methods * additive instead of replacing any pre-defined module. This class also acts as a default * implementation for overriding the behavior of LifecycleInjectorBuilder so that code * does not break every time a new method is added. * * @author elandau */ public class DelegatingLifecycleInjectorBuilder implements LifecycleInjectorBuilder { private LifecycleInjectorBuilder delegate; public DelegatingLifecycleInjectorBuilder(LifecycleInjectorBuilder delegate) { this.delegate = delegate; } @Override public LifecycleInjectorBuilder withBootstrapModule(BootstrapModule module) { this.delegate = delegate.withAdditionalBootstrapModules(module); return this; } @Override public LifecycleInjectorBuilder withAdditionalBootstrapModules( BootstrapModule... modules) { this.delegate = delegate.withAdditionalBootstrapModules(modules); return this; } @Override public LifecycleInjectorBuilder withAdditionalBootstrapModules( Iterable<? extends BootstrapModule> modules) { this.delegate = delegate.withAdditionalBootstrapModules(modules); return this; } @Override public LifecycleInjectorBuilder withModules(Module... modules) { this.delegate = delegate.withAdditionalModules(modules); return this; } @Override public LifecycleInjectorBuilder withModules( Iterable<? extends Module> modules) { this.delegate = delegate.withAdditionalModules(modules); return this; } @Override public LifecycleInjectorBuilder withAdditionalModules( Iterable<? extends Module> modules) { this.delegate = delegate.withAdditionalModules(modules); return this; } @Override public LifecycleInjectorBuilder withAdditionalModules(Module... modules) { this.delegate = delegate.withAdditionalModules(modules); return this; } @Override @Deprecated public LifecycleInjectorBuilder withRootModule(Class<?> mainModule) { this.delegate = delegate.withRootModule(mainModule); return this; } @Override public LifecycleInjectorBuilder withModuleClass( Class<? extends Module> module) { this.delegate = delegate.withAdditionalModuleClasses(module); return this; } @Override public LifecycleInjectorBuilder withModuleClasses( Iterable<Class<? extends Module>> modules) { this.delegate = delegate.withAdditionalModuleClasses(modules); return this; } @Override public LifecycleInjectorBuilder withModuleClasses( Class<?>... modules) { this.delegate = delegate.withAdditionalModuleClasses(modules); return this; } @Override public LifecycleInjectorBuilder withAdditionalModuleClasses( Iterable<Class<? extends Module>> modules) { this.delegate = delegate.withAdditionalModuleClasses(modules); return this; } @Override public LifecycleInjectorBuilder withAdditionalModuleClasses(Class<?>... modules) { this.delegate = delegate.withAdditionalModuleClasses(modules); return this; } @Override public LifecycleInjectorBuilder ignoringAutoBindClasses( Collection<Class<?>> ignoreClasses) { this.delegate = delegate.ignoringAutoBindClasses(ignoreClasses); return this; } @Override public LifecycleInjectorBuilder ignoringAllAutoBindClasses() { this.delegate = delegate.ignoringAllAutoBindClasses(); return this; } @Override public LifecycleInjectorBuilder requiringExplicitBindings() { this.delegate = delegate.requiringExplicitBindings(); return this; } @Override public LifecycleInjectorBuilder usingBasePackages(String... basePackages) { this.delegate = delegate.usingBasePackages(basePackages); return this; } @Override public LifecycleInjectorBuilder usingBasePackages( Collection<String> basePackages) { this.delegate = delegate.usingBasePackages(basePackages); return this; } @Override public LifecycleInjectorBuilder usingClasspathScanner( ClasspathScanner scanner) { this.delegate = delegate.usingClasspathScanner(scanner); return this; } @Override public LifecycleInjectorBuilder inStage(Stage stage) { this.delegate = delegate.inStage(stage); return this; } @Override public LifecycleInjectorBuilder withMode(LifecycleInjectorMode mode) { this.delegate = delegate.withMode(mode); return this; } @Override public LifecycleInjectorBuilder withModuleTransformer( ModuleTransformer transformer) { this.delegate = delegate.withModuleTransformer(transformer); return this; } @Override public LifecycleInjectorBuilder withModuleTransformer( Collection<? extends ModuleTransformer> transformers) { this.delegate = delegate.withModuleTransformer(transformers); return this; } @Override public LifecycleInjectorBuilder withModuleTransformer( ModuleTransformer... transformers) { this.delegate = delegate.withModuleTransformer(transformers); return this; } @Override public LifecycleInjectorBuilder withPostInjectorAction( PostInjectorAction action) { this.delegate = delegate.withPostInjectorAction(action); return this; } @Override public LifecycleInjectorBuilder withPostInjectorActions( Collection<? extends PostInjectorAction> actions) { this.delegate = delegate.withPostInjectorActions(actions); return this; } @Override public LifecycleInjectorBuilder withPostInjectorActions( PostInjectorAction... actions) { this.delegate = delegate.withPostInjectorActions(actions); return this; } @Override public LifecycleInjectorBuilder withoutModuleClasses( Iterable<Class<? extends Module>> modules) { this.delegate = delegate.withoutModuleClasses(modules); return this; } @Override public LifecycleInjectorBuilder withoutModuleClasses( Class<? extends Module>... modules) { this.delegate = delegate.withoutModuleClasses(modules); return this; } @Override public LifecycleInjectorBuilder withoutModuleClass( Class<? extends Module> module) { this.delegate = delegate.withoutModuleClass(module); return this; } @Override public LifecycleInjector build() { return delegate.build(); } @Override @Deprecated public Injector createInjector() { return delegate.createInjector(); } }
5,756
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/ProviderBinderUtil.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import com.google.inject.Binder; import com.google.inject.Inject; import com.google.inject.Injector; import javax.inject.Provider; import com.google.inject.Scope; class ProviderBinderUtil { static void bind(Binder binder, Class<? extends Provider> clazz, Scope scope) { Class<?> providedType; try { providedType = clazz.getMethod("get").getReturnType(); } catch ( NoSuchMethodException e ) { throw new RuntimeException(e); } //noinspection unchecked binder.bind(providedType) .toProvider ( new MyProvider(clazz) ) .in(scope); } private ProviderBinderUtil() { } private static class MyProvider implements com.google.inject.Provider { private final Class<? extends Provider> clazz; @Inject private Injector injector; @Inject public MyProvider(Class<? extends Provider> clazz) { this.clazz = clazz; } @Override public Object get() { Provider provider = injector.getInstance(clazz); return provider.get(); } } }
5,757
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/InternalBootstrapModule.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import java.util.Collection; import java.util.Set; import com.google.common.collect.Sets; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.Stage; import com.netflix.governator.configuration.ConfigurationDocumentation; import com.netflix.governator.configuration.ConfigurationMapper; import com.netflix.governator.configuration.ConfigurationProvider; 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; import com.netflix.governator.lifecycle.ClasspathScanner; import com.netflix.governator.lifecycle.LifecycleConfigurationProviders; import com.netflix.governator.lifecycle.LifecycleManager; import com.netflix.governator.lifecycle.LifecycleManagerArguments; class InternalBootstrapModule extends AbstractModule { private BootstrapBinder bootstrapBinder; private ClasspathScanner scanner; private Stage stage; private LifecycleInjectorMode mode; private ModuleListBuilder modules; private Collection<PostInjectorAction> actions; private Collection<ModuleTransformer> transformers; private boolean disableAutoBinding; private final Collection<BootstrapModule> bootstrapModules; private static class LifecycleConfigurationProvidersProvider implements Provider<LifecycleConfigurationProviders> { @Inject(optional = true) private Set<ConfigurationProvider> configurationProviders = Sets.newHashSet(); @Override public LifecycleConfigurationProviders get() { return new LifecycleConfigurationProviders(configurationProviders); } } public InternalBootstrapModule(Collection<BootstrapModule> bootstrapModules, ClasspathScanner scanner, Stage stage, LifecycleInjectorMode mode, ModuleListBuilder modules, Collection<PostInjectorAction> actions, Collection<ModuleTransformer> transformers, boolean disableAutoBinding) { this.scanner = scanner; this.stage = stage; this.mode = mode; this.modules = modules; this.actions = actions; this.transformers = transformers; this.bootstrapModules = bootstrapModules; this.disableAutoBinding = disableAutoBinding; } BootstrapBinder getBootstrapBinder() { return bootstrapBinder; } @Override protected void configure() { bind(ConfigurationDocumentation.class).in(Scopes.SINGLETON); bindScope(LazySingleton.class, LazySingletonScope.get()); bindScope(FineGrainedLazySingleton.class, FineGrainedLazySingletonScope.get()); bootstrapBinder = new BootstrapBinder(binder(), stage, mode, modules, actions, transformers, disableAutoBinding); if ( bootstrapModules != null ) { for (BootstrapModule bootstrapModule : bootstrapModules) { bootstrapModule.configure(bootstrapBinder); } } bind(com.netflix.governator.LifecycleManager.class).in(Scopes.SINGLETON); binder().bind(LifecycleManagerArguments.class).in(Scopes.SINGLETON); binder().bind(LifecycleManager.class).asEagerSingleton(); binder().bind(LifecycleConfigurationProviders.class).toProvider(LifecycleConfigurationProvidersProvider.class).asEagerSingleton(); this.stage = bootstrapBinder.getStage(); this.mode = bootstrapBinder.getMode(); } Stage getStage() { return stage; } LifecycleInjectorMode getMode() { return mode; } boolean isDisableAutoBinding() { return disableAutoBinding; } ModuleListBuilder getModuleListBuilder() { return modules; } @Provides @Singleton public ClasspathScanner getClasspathScanner() { return scanner; } }
5,758
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/ModulesEx.java
package com.netflix.governator.guice; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Module; import com.google.inject.util.Modules; import com.netflix.governator.guice.annotations.Bootstrap; /** * Utility class similar to Guice's Modules that simplifies recipes for * combing Guice modules. * * @author elandau * */ public class ModulesEx { private static final Logger LOG = LoggerFactory.getLogger(ModulesEx.class); public static Module combineAndOverride(Module ... modules) { return combineAndOverride(Arrays.asList(modules)); } /** * Generate a single module that is produced by accumulating and overriding * each module with the next. * * <pre> * {@code * Guice.createInjector(ModuleUtils.combineAndOverride(moduleA, moduleAOverrides, moduleB)); * } * </pre> * * @param modules * @return */ public static Module combineAndOverride(List<? extends Module> modules) { Iterator<? extends Module> iter = modules.iterator(); Module current = Modules.EMPTY_MODULE; if (iter.hasNext()) { current = iter.next(); if (iter.hasNext()) { current = Modules.override(current).with(iter.next()); } } return current; } public static Module fromClass(final Class<?> cls) { return fromClass(cls, true); } /** * Create a single module that derived from all bootstrap annotations * on a class, where that class itself is a module. * * For example, * <pre> * {@code * public class MainApplicationModule extends AbstractModule { * @Override * public void configure() { * // Application specific bindings here * } * * public static void main(String[] args) { * Guice.createInjector(ModulesEx.fromClass(MainApplicationModule.class)); * } * } * } * </pre> * @author elandau */ public static Module fromClass(final Class<?> cls, final boolean override) { List<Module> modules = new ArrayList<>(); // Iterate through all annotations of the main class, create a binding for the annotation // and add the module to the list of modules to install for (final Annotation annot : cls.getDeclaredAnnotations()) { final Class<? extends Annotation> type = annot.annotationType(); Bootstrap bootstrap = type.getAnnotation(Bootstrap.class); if (bootstrap != null) { LOG.info("Adding Module {}", bootstrap.module()); try { modules.add(bootstrap.module().getConstructor(type).newInstance(annot)); } catch (Exception e) { throw new RuntimeException(e); } } } try { if (override) { return Modules.override(combineAndOverride(modules)).with((Module)cls.newInstance()); } else { return Modules.combine(Modules.combine(modules), (Module)cls.newInstance()); } } catch (Exception e) { throw new RuntimeException(e); } } }
5,759
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/LifecycleInjectorBuilder.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.lifecycle.ClasspathScanner; import java.util.Collection; /** * Builder for a {@link LifecycleInjector} */ public interface LifecycleInjectorBuilder { /** * Specify a bootstrap module * * @param module the module * @return this */ public LifecycleInjectorBuilder withBootstrapModule(BootstrapModule module); /** * Specify additional bootstrap modules to use * * @param modules modules * @return this */ public LifecycleInjectorBuilder withAdditionalBootstrapModules(BootstrapModule... modules); /** * Specify additional bootstrap modules to use * * @param modules modules * @return this */ public LifecycleInjectorBuilder withAdditionalBootstrapModules(Iterable<? extends BootstrapModule> modules); /** * Specify standard Guice modules for the main binding phase. Note that any * modules provided in a previous call to withModules will be discarded. * To add to the list of modules call {@link #withAdditionalModules} * * @param modules modules * @return this */ public LifecycleInjectorBuilder withModules(Module... modules); /** * Specify standard Guice modules for the main binding phase. Note that any * modules provided in a previous call to withModules will be discarded. * To add to the list of modules call {@link #withAdditionalModules} * * @param modules modules * @return this */ public LifecycleInjectorBuilder withModules(Iterable<? extends Module> modules); /** * Add to any modules already specified via {@link #withModules(Iterable)} * * @param modules modules * @return this */ public LifecycleInjectorBuilder withAdditionalModules(Iterable<? extends Module> modules); /** * Add to any modules already specified via {@link #withModules(Iterable)} * * @param modules modules * @return this */ public LifecycleInjectorBuilder withAdditionalModules(Module... modules); /** * Specify a root application module class from which a set of additional modules * may be derived using module dependencies. Module dependencies are specified * using @Inject on the module constructor and indicating the dependent modules * as constructor arguments. * * @param mainModule root application module * @return this * * @deprecated 2016-07-19 This method of adding modules has been deemed an anti-pattern. Use * module instances with hashCode() and equals() for deduping. */ @Deprecated public LifecycleInjectorBuilder withRootModule(Class<?> mainModule); /** * Specify a module class from which a set of additional modules may be derived * using module dependencies. Module dependencies are specified * using @Inject on the module constructor and indicating the dependent modules * as constructor arguments. * * @param module root application module * @return this * * @deprecated 2016-07-19 This method of adding modules has been deemed an anti-pattern. Use * module instances with hashCode() and equals() for deduping. */ @Deprecated public LifecycleInjectorBuilder withModuleClass(Class<? extends Module> module); /** * Specify a set of module classes from which a set of additional modules may be derived * using module dependencies. Module dependencies are specified * using @Inject on the module constructor and indicating the dependent modules * as constructor arguments. * * Note that any existing modules that were added will be removed by this call * * @param modules root application modules * @return this * * @deprecated 2016-07-19 This method of adding modules has been deemed an anti-pattern. Use * module instances with hashCode() and equals() for deduping. */ @Deprecated public LifecycleInjectorBuilder withModuleClasses(Iterable<Class<? extends Module>> modules); /** * Specify a set of module classes from which a set of additional modules may be derived * using module dependencies. Module dependencies are specified * using @Inject on the module constructor and indicating the dependent modules * as constructor arguments. * * Note that any existing modules that were added will be removed by this call * * @param modules root application modules * @return this * * @deprecated 2016-07-19 This method of adding modules has been deemed an anti-pattern. Use * module instances with hashCode() and equals() for deduping. */ @Deprecated public LifecycleInjectorBuilder withModuleClasses(Class<?> ... modules); /** * Specify a set of module classes from which a set of additional modules may be derived * using module dependencies. Module dependencies are specified * using @Inject on the module constructor and indicating the dependent modules * as constructor arguments. * * Note that any existing modules that were added will be removed by this call * @param modules root application modules * @return this * * @deprecated 2016-07-19 This method of adding modules has been deemed an anti-pattern. Use * module instances with hashCode() and equals() for deduping. */ @Deprecated public LifecycleInjectorBuilder withAdditionalModuleClasses(Iterable<Class<? extends Module>> modules); /** * Specify a set of module classes from which a set of additional modules may be derived * using module dependencies. Module dependencies are specified * using @Inject on the module constructor and indicating the dependent modules * as constructor arguments. * * @param modules root application modules * @return this * * @deprecated 2016-07-19 This method of adding modules has been deemed an anti-pattern. Use * module instances with hashCode() and equals() for deduping. */ @Deprecated public LifecycleInjectorBuilder withAdditionalModuleClasses(Class<?> ... modules); /** * When using module dependencies ignore the specified classes * * @param modules to exclude * @return this * * @deprecated 2016-07-19 This method of adding modules has been deemed an anti-pattern. Use * module instances with hashCode() and equals() for deduping. */ @Deprecated public LifecycleInjectorBuilder withoutModuleClasses(Iterable<Class<? extends Module>> modules); /** * When using module dependencies ignore the specified classes * @param modules to exclude * @return this * * @deprecated This method of adding modules has been deemed an anti-pattern as it detracts from * Guice's reliance on module instances and deduping via hashCode() and equals(). */ @Deprecated public LifecycleInjectorBuilder withoutModuleClasses(Class<? extends Module> ... modules); /** * When using module dependencies ignore the specified class * @param module to exclude * @return this * * @deprecated 2016-07-19 This method of adding modules has been deemed an anti-pattern. Use * module instances with hashCode() and equals() for deduping. */ @Deprecated public LifecycleInjectorBuilder withoutModuleClass(Class<? extends Module> module); /** * Specify specific {@link AutoBindSingleton} classes that should NOT be bound in the main * binding phase * * @param ignoreClasses classes to not bind * @return this */ public LifecycleInjectorBuilder ignoringAutoBindClasses(Collection<Class<?>> ignoreClasses); /** * Do not bind ANY {@link AutoBindSingleton} classes * * @return this */ public LifecycleInjectorBuilder ignoringAllAutoBindClasses(); /** * Do not use implicit bindings * * @return this */ public LifecycleInjectorBuilder requiringExplicitBindings(); /** * Specify the base packages for CLASSPATH scanning. Packages are recursively scanned * * @param basePackages packages * @return this */ public LifecycleInjectorBuilder usingBasePackages(String... basePackages); /** * Specify the base packages for CLASSPATH scanning. Packages are recursively scanned * * @param basePackages packages * @return this */ public LifecycleInjectorBuilder usingBasePackages(Collection<String> basePackages); /** * Normally, the classpath scanner is allocated internally. This method allows for a custom * scanner to be used. NOTE: Any packages specifies via {@link #usingBasePackages(String...)} will * be ignored if this method is called. * * @param scanner the scanner to use * @return this */ public LifecycleInjectorBuilder usingClasspathScanner(ClasspathScanner scanner); /** * Set the Guice stage - the default is Production * * @param stage new stage * @return this */ public LifecycleInjectorBuilder inStage(Stage stage); /** * Set the lifecycle injector mode - default is {@link LifecycleInjectorMode#REAL_CHILD_INJECTORS} * * @param mode new mode * @return this */ public LifecycleInjectorBuilder withMode(LifecycleInjectorMode mode); /** * Just before creating the injector all the modules will run through the transformer. * Transformers will be executed in the order in which withModuleTransformer * is called. Note that once the first filter is called subsequent calls will only be * given the previous set of filtered modules. * * @param transformer * @return this */ public LifecycleInjectorBuilder withModuleTransformer(ModuleTransformer transformer); /** * Just before creating the injector all the modules will run through the filter. * Transformers will be executed in the order in which withModuleTransformer * is called. Note that once the first filter is called subsequent calls will only be * given the previous set of filtered modules. * * @param transformer * @return this */ public LifecycleInjectorBuilder withModuleTransformer(Collection<? extends ModuleTransformer> transformer); /** * Just before creating the injector all the modules will run through the filter. * Transformers will be executed in the order in which withModuleTransformer * is called. Note that once the first filter is called subsequent calls will only be * given the previous set of filtered modules. * * @param transformer * @return this */ public LifecycleInjectorBuilder withModuleTransformer(ModuleTransformer... transformer); /** * Action to perform after the injector is created. Note that post injection actions * are performed in the same order as calls to withPostInjectorAction * @param action * @return */ public LifecycleInjectorBuilder withPostInjectorAction(PostInjectorAction action); /** * Actions to perform after the injector is created. Note that post injection actions * are performed in the same order as calls to withPostInjectorAction * @param action * @return */ public LifecycleInjectorBuilder withPostInjectorActions(Collection<? extends PostInjectorAction> action); /** * Actions to perform after the injector is created. Note that post injection actions * are performed in the same order as calls to withPostInjectorAction * @param action * @return */ public LifecycleInjectorBuilder withPostInjectorActions(PostInjectorAction... actions); /** * Build and return the injector * * @return LifecycleInjector */ public LifecycleInjector build(); /** * Internally build the LifecycleInjector and then return the result of calling * {@link LifecycleInjector#createInjector()} * * @return Guice injector * * @deprecated this API creates the "main" child injector. * but it has the side effect of calling build() method * that will create a new LifecycleInjector. * Instead, you should just build() LifecycleInjector object. * then call LifecycleInjector.createInjector() directly. */ @Deprecated public Injector createInjector(); }
5,760
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/PostInjectorAction.java
package com.netflix.governator.guice; import com.google.inject.Injector; /** * Action to perform after the injector is created. * * @author elandau */ public interface PostInjectorAction { public void call(Injector injector); }
5,761
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/ModuleTransformer.java
package com.netflix.governator.guice; import java.util.Collection; import com.google.inject.Module; /** * Before creating the injector the modules are passed through a collection * of filters that can filter out or modify bindings * * @author elandau * */ public interface ModuleTransformer { public Collection<Module> call(Collection<Module> modules); }
5,762
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/ModuleListBuilder.java
package com.netflix.governator.guice; import java.lang.reflect.Constructor; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.ProvisionException; import com.google.inject.spi.Dependency; import com.google.inject.spi.InjectionPoint; import com.netflix.governator.annotations.Modules; /** * The {@link ModuleListBuilder} keeps track of modules and their transitive dependencies * and provides a mechanism to replace or exclude modules. * * When {@link build()} is called a list of modules is created and modules will be ordered * in the order in which they were added while allowing for dependent modules to be listed * first. * * TODO: Provide exclude source * TODO: Provide include source * TODO: Force include * TODO: Guard against circular dependencies * * @author elandau */ public class ModuleListBuilder { private static final Logger LOG = LoggerFactory.getLogger(ModuleListBuilder.class); /** * Internal class to track either a module class or instance * @author elandau */ public class ModuleProvider { Class<? extends Module> type; Module instance; boolean isExcluded = false; public ModuleProvider(Class<? extends Module> type) { this.type = type; instance = null; } public ModuleProvider(Module instance) { this.instance = instance; if (instance instanceof AbstractModule) { type = null; } } public void setInstance(Module module) { Preconditions.checkState(instance == null, "Instance already exists"); this.instance = module; } public Module getInstance(Injector injector) throws Exception { try { // Already created if (instance != null) { return instance; } LOG.info("Getting instance of : " + type.getName()); if (excludes.contains(type)) { LOG.info("Module '" + type.getName() + "' is excluded"); return null; } // Create all of this modules dependencies. This includes both @Modules and injected // dependencies for (Class<? extends Module> dep : getIncludeList()) { ModuleProvider provider = includes.get(dep); provider.getInstance(injector); } // If @Inject is present then instantiate using that constructor and manually inject // the dependencies. Note that a null will be injected for excluded modules try { InjectionPoint ip = InjectionPoint.forConstructorOf(type); if (ip != null) { Constructor<?> c = (Constructor<?>) ip.getMember(); c.setAccessible(true); List<Dependency<?>> deps = ip.getDependencies(); if (!deps.isEmpty()) { Object[] args = new Object[deps.size()]; for (Dependency<?> dep : deps) { Class<?> type = dep.getKey().getTypeLiteral().getRawType(); if (Module.class.isAssignableFrom(type)) { args[dep.getParameterIndex()] = includes.get(dep.getKey().getTypeLiteral().getRawType()).getInstance(injector); } else { args[dep.getParameterIndex()] = injector.getInstance(dep.getKey()); } } c.setAccessible(true); instance = (Module) c.newInstance(args); } else { instance = (Module) c.newInstance(); } } else { // Empty constructor Constructor<?> c = type.getConstructor(); if (c != null) { c.setAccessible(true); instance = (Module) c.newInstance(); } // Default constructor else { instance = type.newInstance(); } } injector.injectMembers(instance); return instance; } catch (Exception e) { throw new ProvisionException("Failed to create module '" + type.getName() + "'", e); } } finally { if (instance != null) { registerModule(instance); } } } private List<Class<? extends Module>> getIncludeList() { // Look for @Modules(includes={..}) Builder<Class<? extends Module>> builder = ImmutableList.<Class<? extends Module>>builder(); if (type != null) { Modules annot = type.getAnnotation(Modules.class); if (annot != null && annot.include() != null) { builder.add(annot.include()); } // Look for injected modules for (Dependency<?> dep : InjectionPoint.forConstructorOf(type).getDependencies()) { Class<?> depType = dep.getKey().getTypeLiteral().getRawType(); if (Module.class.isAssignableFrom(depType)) { builder.add((Class<? extends Module>) depType); } } } return builder.build(); } private List<Class<? extends Module>> getExcludeList() { Builder<Class<? extends Module>> builder = ImmutableList.<Class<? extends Module>>builder(); if (type != null) { Modules annot = type.getAnnotation(Modules.class); if (annot != null && annot.exclude() != null) { builder.add(annot.exclude()); } } return builder.build(); } } // List of all identified Modules in the order in which they were added and identified private List<ModuleProvider> providers = Lists.newArrayList(); // Map of seen class to the provider. Note that this map will not include any module // that is a simple private Map<Class<? extends Module>, ModuleProvider> includes = Maps.newIdentityHashMap(); // Set of module classes to exclude private Set<Class<? extends Module>> excludes = Sets.newIdentityHashSet(); // Final list of modules to install private List<Module> resolvedModules = Lists.newArrayList(); // Lookup of resolved modules for duplicate check private Set<Class<? extends Module>> resolvedModuleLookup = Sets.newIdentityHashSet(); public ModuleListBuilder includeModules(Iterable<? extends Module> modules) { for (Module module : modules) { include (module); } return this; } public ModuleListBuilder include(Iterable<Class<? extends Module>> modules) { for (Class<? extends Module> module : modules) { include (module); } return this; } public ModuleListBuilder include(final Module m) { ModuleProvider provider = new ModuleProvider(m); if (!m.getClass().isAnonymousClass()) { // Do nothing if already exists if (includes.containsKey(m.getClass())) { return this; } includes.put(m.getClass(), provider); // Get all @Modules and injected dependencies of this module for (Class<? extends Module> dep : provider.getIncludeList()) { // Circular dependencies will be caught by includes.containsKey() above include(dep, false); } for (Class<? extends Module> dep : provider.getExcludeList()) { exclude(dep); } } // Add to list of known modules. We do this after all dependencies // have been added providers.add(provider); return this; } public ModuleListBuilder include(final Class<? extends Module> m) { include(m, true); return this; } private void include(final Class<? extends Module> m, boolean addToProviders) { ModuleProvider provider = new ModuleProvider(m); if (!m.getClass().isAnonymousClass()) { // Do nothing if already exists if (includes.containsKey(m.getClass())) { return; } includes.put(m, provider); // Get all @Modules and injected dependencies of this module for (Class<? extends Module> dep : provider.getIncludeList()) { // Circular dependencies will be caught by includes.containsKey() above include(dep, false); } for (Class<? extends Module> dep : provider.getExcludeList()) { exclude(dep); } } // Add to list of known modules. We do this after all dependencies // have been added if (addToProviders) { providers.add(provider); } } public ModuleListBuilder exclude(Class<? extends Module> m) { excludes.add(m); return this; } public ModuleListBuilder exclude(Iterable<Class<? extends Module>> modules) { for (Class<? extends Module> module : modules) { excludes.add(module); } return this; } private void registerModule(Module m) { if (m.getClass().isAnonymousClass()) { resolvedModules.add(m); } else { if (!resolvedModuleLookup.contains(m.getClass())) { LOG.info("Adding module '" + m.getClass().getName()); resolvedModules.add(m); resolvedModuleLookup.add(m.getClass()); } } } List<Module> build(Injector injector) throws Exception { for (ModuleProvider provider : providers) { provider.getInstance(injector); } return resolvedModules; } }
5,763
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/Grapher.java
/* * Copyright 2013, 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import com.google.common.collect.Sets; import com.google.common.io.Closeables; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.grapher.graphviz.GraphvizGrapher; import com.google.inject.grapher.graphviz.GraphvizModule; /** * An object that can generate a graph showing a Guice Dependency Injection graph. * * @see <a href="http://www.graphviz.org/">GraphViz</a> * @see <a href="http://code.google.com/p/google-guice/wiki/Grapher">Guice Grapher</a> * @see <a href="http://code.google.com/p/jrfonseca/wiki/XDot">XDot, an interactive viewer for Dot files</a> */ public class Grapher { private final Injector injector; private final Set<Key<?>> roots; /* * Constructors */ /** * Creates a new Grapher. * * @param injector the Injector whose dependency graph will be generated */ @Inject public Grapher(Injector injector) { this.injector = injector; this.roots = new HashSet<>(); } /** * Creates a new Grapher. * * @param injector the Injector whose dependency graph will be generated * @param keys {@code Key}s for the roots of the graph */ public Grapher(Injector injector, Key<?>... keys) { this.injector = injector; this.roots = Sets.newHashSet(keys); } /** * Creates a new Grapher. * * @param injector the Injector whose dependency graph will be generated * @param classes {@code Class}es for the roots of the graph */ public Grapher(Injector injector, Class<?>... classes) { this.injector = injector; this.roots = Sets.newHashSetWithExpectedSize(classes.length); for (Class<?> cls : classes) { roots.add(Key.get(cls)); } } /** * Creates a new Grapher. * * @param injector the Injector whose dependency graph will be generated * @param packages names of {@code Package}s for the roots of the graph */ public Grapher(Injector injector, String... packages) { this.injector = injector; // Scan all the injection bindings to find the root keys this.roots = new HashSet<Key<?>>(); for (Key<?> k : injector.getAllBindings().keySet()) { Package classPackage = k.getTypeLiteral().getRawType().getPackage(); if (classPackage == null) { continue; } String packageName = classPackage.getName(); for (String p : packages) { if (packageName.startsWith(p)) { roots.add(k); break; } } } } /* * Graphing methods */ /** * Writes the "Dot" graph to a new temp file. * * @return the name of the newly created file */ public String toFile() throws Exception { File file = File.createTempFile("GuiceDependencies_", ".dot"); toFile(file); return file.getCanonicalPath(); } /** * Writes the "Dot" graph to a given file. * * @param file file to write to */ public void toFile(File file) throws Exception { PrintWriter out = new PrintWriter(file, "UTF-8"); try { out.write(graph()); } finally { Closeables.close(out, true); } } /** * Returns a String containing the "Dot" graph definition. * * @return the "Dot" graph definition */ public String graph() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter out = new PrintWriter(baos); Injector localInjector = Guice.createInjector(new GraphvizModule()); GraphvizGrapher renderer = localInjector.getInstance(GraphvizGrapher.class); renderer.setOut(out); renderer.setRankdir("TB"); if (!roots.isEmpty()) { renderer.graph(injector, roots); } renderer.graph(injector); return fixupGraph(baos.toString("UTF-8")); } /* * Work-arounds for bugs in the Grapher package * See http://stackoverflow.com/questions/9301007/is-there-any-way-to-get-guice-grapher-to-work */ private String fixupGraph(String s) { s = fixGrapherBug(s); s = hideClassPaths(s); return s; } private String hideClassPaths(String s) { s = s.replaceAll("\\w[a-z\\d_\\.]+\\.([A-Z][A-Za-z\\d_\\$]*)", "$1"); s = s.replaceAll("value=[\\w-]+", "random"); return s; } private String fixGrapherBug(String s) { s = s.replaceAll("style=invis", "style=solid"); s = s.replaceAll("margin=(\\S+), ", "margin=\"$1\", "); return s; } } // Grapher
5,764
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/InternalAutoBindModuleBootstrapModule.java
package com.netflix.governator.guice; import java.util.Collection; import java.util.List; 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.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.inject.Module; import com.google.inject.util.Modules; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.lifecycle.ClasspathScanner; /** * Custom BootstrapModule that auto-installs guice modules annotated with AutoBindSingleton * @author elandau * */ @Singleton public class InternalAutoBindModuleBootstrapModule implements BootstrapModule { private static final Logger LOG = LoggerFactory.getLogger(InternalAutoBindModule.class); private final List<Class<?>> ignoreClasses; private final ClasspathScanner classpathScanner; @Inject InternalAutoBindModuleBootstrapModule(ClasspathScanner classpathScanner, Collection<Class<?>> ignoreClasses) { this.classpathScanner = classpathScanner; Preconditions.checkNotNull(ignoreClasses, "ignoreClasses cannot be null"); this.ignoreClasses = ImmutableList.copyOf(ignoreClasses); } @Override public void configure(BootstrapBinder binder) { bindAutoBindSingletons(binder); } @SuppressWarnings({ "rawtypes", "unchecked" }) private Module bindAutoBindSingletons(BootstrapBinder binder) { List<Module> modules = Lists.newArrayList(); for (final Class<?> clazz : classpathScanner.getClasses()) { if (ignoreClasses.contains(clazz) || !clazz.isAnnotationPresent(AutoBindSingleton.class)) { continue; } AutoBindSingleton annotation = clazz.getAnnotation(AutoBindSingleton.class); if (Module.class.isAssignableFrom(clazz)) { Preconditions.checkState( annotation.value() == Void.class, "@AutoBindSingleton value cannot be set for Modules"); Preconditions.checkState( annotation.baseClass() == Void.class, "@AutoBindSingleton value cannot be set for Modules"); Preconditions.checkState( !annotation.multiple(), "@AutoBindSingleton(multiple=true) value cannot be set for Modules"); LOG.info("Found @AutoBindSingleton annotated module : {} ", clazz.getName()); LOG.info("***** @AutoBindSingleton use for module {} is deprecated as of 2015-10-10. Modules should be added directly to the injector or via install({}.class). See https://github.com/Netflix/governator/wiki/Auto-Binding", clazz.getName(), clazz.getSimpleName()); binder.include((Class<? extends Module>) clazz); } } return Modules.combine(modules); } }
5,765
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/SingletonModule.java
package com.netflix.governator.guice; /** * 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(). * * @author elandau * * @deprecated Use com.netflix.governator.SingletonModule instead */ @Deprecated public abstract class SingletonModule extends com.netflix.governator.SingletonModule { }
5,766
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/InternalAutoBindModule.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.guice; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.ScopeAnnotation; import com.google.inject.Scopes; 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.google.inject.util.Types; import com.netflix.governator.annotations.AutoBind; import com.netflix.governator.annotations.AutoBindSingleton; import com.netflix.governator.guice.lazy.LazySingletonScope; import com.netflix.governator.lifecycle.ClasspathScanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.Set; import javax.inject.Singleton; class InternalAutoBindModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(InternalAutoBindModule.class); private final Set<Class<?>> ignoreClasses; private final Injector injector; private final ClasspathScanner classpathScanner; InternalAutoBindModule(Injector injector, ClasspathScanner classpathScanner, Collection<Class<?>> ignoreClasses) { this.injector = injector; this.classpathScanner = classpathScanner; Preconditions.checkNotNull(ignoreClasses, "ignoreClasses cannot be null"); this.ignoreClasses = ImmutableSet.copyOf(ignoreClasses); } @Override protected void configure() { bindAutoBindSingletons(); bindAutoBindConstructors(); bindAutoBindMethods(); bindAutoBindFields(); } private void bindAutoBindFields() { for ( Field field : classpathScanner.getFields() ) { if ( ignoreClasses.contains(field.getDeclaringClass()) ) { continue; } bindAnnotations(field.getDeclaredAnnotations()); } } private void bindAutoBindMethods() { for ( Method method : classpathScanner.getMethods() ) { if ( ignoreClasses.contains(method.getDeclaringClass()) ) { continue; } bindParameterAnnotations(method.getParameterAnnotations()); } } private void bindAutoBindConstructors() { for ( Constructor constructor : classpathScanner.getConstructors() ) { if ( ignoreClasses.contains(constructor.getDeclaringClass()) ) { continue; } bindParameterAnnotations(constructor.getParameterAnnotations()); } } private void bindParameterAnnotations(Annotation[][] parameterAnnotations) { for ( Annotation[] annotations : parameterAnnotations ) { bindAnnotations(annotations); } } private void bindAnnotations(Annotation[] annotations) { for ( Annotation annotation : annotations ) { AutoBindProvider autoBindProvider = getAutoBindProvider(annotation); if ( autoBindProvider != null ) { //noinspection unchecked autoBindProvider.configure(binder(), annotation); } } } private AutoBindProvider getAutoBindProvider(Annotation annotation) { AutoBindProvider autoBindProvider = null; if ( annotation.annotationType().isAnnotationPresent(AutoBind.class) ) { ParameterizedType parameterizedType = Types.newParameterizedType(AutoBindProvider.class, annotation.annotationType()); autoBindProvider = (AutoBindProvider<?>)injector.getInstance(Key.get(TypeLiteral.get(parameterizedType))); } else if ( annotation.annotationType().isAssignableFrom(AutoBind.class) ) { autoBindProvider = injector.getInstance(Key.get(new TypeLiteral<AutoBindProvider<AutoBind>>() { })); } return autoBindProvider; } @SuppressWarnings("unchecked") private void bindAutoBindSingletons() { for ( Class<?> clazz : classpathScanner.getClasses() ) { if ( ignoreClasses.contains(clazz) || !clazz.isAnnotationPresent(AutoBindSingleton.class) ) { continue; } AutoBindSingleton annotation = clazz.getAnnotation(AutoBindSingleton.class); if ( javax.inject.Provider.class.isAssignableFrom(clazz) ) { Preconditions.checkState(annotation.value() == Void.class, "@AutoBindSingleton value cannot be set for Providers"); Preconditions.checkState(annotation.baseClass() == Void.class, "@AutoBindSingleton value cannot be set for Providers"); Preconditions.checkState(!annotation.multiple(), "@AutoBindSingleton(multiple=true) value cannot be set for Providers"); LOG.info("Installing @AutoBindSingleton " + clazz.getName()); ProviderBinderUtil.bind(binder(), (Class<javax.inject.Provider>)clazz, Scopes.SINGLETON); } else if ( Module.class.isAssignableFrom(clazz) ) { // Modules are handled by {@link InteranlAutoBindModuleBootstrapModule} continue; } else { bindAutoBindSingleton(annotation, clazz); } } } private void bindAutoBindSingleton(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); if ( annotationBaseClass != Void.class ) // AutoBindSingleton.class is used as a marker to mean "default" because annotation defaults cannot be null { Object foundBindingClass = searchForBaseClass(clazz, annotationBaseClass, Sets.newHashSet()); if ( foundBindingClass == null ) { throw new IllegalArgumentException(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() ) { Multibinder<?> multibinder = Multibinder.newSetBinder(binder(), typeLiteral); //noinspection unchecked applyScope( multibinder .addBinding() .to((Class)clazz), clazz, annotation); } else { //noinspection unchecked applyScope( binder() .withSource(getCurrentStackElement()) .bind(typeLiteral).to(clazz), clazz, annotation); } } else { throw new RuntimeException("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)) { 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,767
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/bootstrap/ModulesBootstrap.java
package com.netflix.governator.guice.bootstrap; import javax.inject.Inject; import com.netflix.governator.annotations.Modules; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; public class ModulesBootstrap implements BootstrapModule { private final Modules modules; @Inject public ModulesBootstrap(Modules modules) { this.modules = modules; } @Override public void configure(BootstrapBinder binder) { binder.include(modules.include()); binder.exclude(modules.exclude()); } }
5,768
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/bootstrap/GovernatorBootstrap.java
package com.netflix.governator.guice.bootstrap; import com.google.inject.Inject; import com.google.inject.ProvisionException; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.ModuleTransformer; import com.netflix.governator.guice.PostInjectorAction; import com.netflix.governator.guice.annotations.GovernatorConfiguration; /** * Implementation for the @GovernatorConfiguration main bootstrap class annotation */ public class GovernatorBootstrap implements BootstrapModule { private final GovernatorConfiguration config; @Inject public GovernatorBootstrap(GovernatorConfiguration config) { this.config = config; } @Override public void configure(BootstrapBinder binder) { if (config.enableAutoBindSingleton() == false) binder.disableAutoBinding(); binder.inStage(config.stage()); binder.inMode(config.mode()); for (Class<? extends PostInjectorAction> action : config.actions()) { try { binder.bindPostInjectorAction().to(action); } catch (Exception e) { throw new ProvisionException("Error creating postInjectorAction '" + action.getName() + "'", e); } } for (Class<? extends ModuleTransformer> transformer : config.transformers()) { try { binder.bindModuleTransformer().to(transformer); } catch (Exception e) { throw new ProvisionException("Error creating postInjectorAction '" + transformer.getName() + "'", e); } } } }
5,769
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/transformer/StripStaticInjections.java
package com.netflix.governator.guice.transformer; import java.util.Collection; import java.util.List; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.inject.Module; import com.google.inject.Stage; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; import com.google.inject.spi.StaticInjectionRequest; import com.netflix.governator.guice.ModuleTransformer; public class StripStaticInjections implements ModuleTransformer { @Override public Collection<Module> call(Collection<Module> modules) { final List<Element> noStatics = Lists.newArrayList(); for(Element element : Elements.getElements(Stage.TOOL, modules)) { element.acceptVisitor(new DefaultElementVisitor<Void>() { @Override public Void visit(StaticInjectionRequest request) { // override to not call visitOther return null; } @Override public Void visitOther(Element element) { noStatics.add(element); return null; } }); } return ImmutableList.<Module>of(Elements.getModule(noStatics)); } }
5,770
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/transformer/OverrideAllDuplicateBindings.java
package com.netflix.governator.guice.transformer; import java.util.Collection; import com.google.common.collect.ImmutableList; import com.google.inject.AbstractModule; import com.google.inject.Module; import com.google.inject.util.Modules; import com.netflix.governator.guice.ModuleTransformer; /** * Treat any binding in list order as an override for previous bindings. * * @author elandau */ public class OverrideAllDuplicateBindings implements ModuleTransformer { @Override public Collection<Module> call(Collection<Module> modules) { // Starting point Module current = new AbstractModule() { @Override protected void configure() { } }; // Accumulate bindings while allowing for each to override all // previous bindings for (Module module : modules) { current = Modules.override(current).with(module); } return ImmutableList.of(current); } }
5,771
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/transformer/WarnAboutStaticInjections.java
package com.netflix.governator.guice.transformer; import java.util.Collection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Module; import com.google.inject.Stage; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Element; import com.google.inject.spi.Elements; import com.google.inject.spi.StaticInjectionRequest; import com.netflix.governator.guice.ModuleTransformer; public class WarnAboutStaticInjections implements ModuleTransformer { private static Logger LOG = LoggerFactory.getLogger(WarnAboutStaticInjections.class); @Override public Collection<Module> call(Collection<Module> modules) { for(Element element : Elements.getElements(Stage.TOOL, modules)) { element.acceptVisitor(new DefaultElementVisitor<Void>() { @Override public Void visit(StaticInjectionRequest request) { LOG.warn("You shouldn't be using static injection at: " + request.getSource()); return null; } }); } return modules; } }
5,772
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/runner/TerminationEvent.java
package com.netflix.governator.guice.runner; /** * Abstraction for an event that when fired should tell the LifecycleRunner * to terminate. A concrete TerminatEvent type is normally paired with a * specific runner implementation. * * @author elandau * * TODO: Add additional listeners of the termination event */ public interface TerminationEvent { /** * Block until the termination event is fired. * * @throws InterruptedException */ public void await() throws InterruptedException; /** * Fire the termination event. */ public void terminate(); /** * @return True if the termination event was set. */ public boolean isTerminated(); }
5,773
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/runner/LifecycleRunner.java
package com.netflix.governator.guice.runner; import com.netflix.governator.guice.runner.standalone.StandaloneRunnerModule; /** * Abstraction defining the application runtime framework for an application using * Governator. If a binding for ApplicationFramework exists Governator will * create the instance of the ApplicationFramework immediately after creating * the bootstrap module. It is the application framework's responsibility * to call {@link com.netflix.governator.lifecycle.LifecycleManager LifecycleManager} * start and stop as well as manage the application termination mechanism. * * A {@link StandaloneRunnerModule} is provided for simple command line * applications. * * Additional LifecycleRunner implementations may be provided for running * Jetty, Karyon, etc... * * @author elandau * */ public interface LifecycleRunner { }
5,774
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/runner
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/runner/standalone/StandaloneRunnerModule.java
package com.netflix.governator.guice.runner.standalone; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.annotation.PostConstruct; import javax.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.TypeLiteral; import com.netflix.governator.annotations.binding.Main; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.lazy.LazySingleton; import com.netflix.governator.guice.lazy.LazySingletonScope; import com.netflix.governator.guice.runner.LifecycleRunner; import com.netflix.governator.guice.runner.TerminationEvent; import com.netflix.governator.guice.runner.events.BlockingTerminationEvent; import com.netflix.governator.lifecycle.LifecycleManager; /** * Implementation of a Runner module that should be used for runtime applications. * * @author elandau */ public class StandaloneRunnerModule implements BootstrapModule { private static Logger LOG = LoggerFactory.getLogger(StandaloneRunnerModule.class); /** * This builder simplifies creation of the module in main() */ public static class Builder { private List<String> args = Lists.newArrayList(); private Class<?> main; private TerminationEvent terminateEvent; /** * Specify optional command line arguments to be injected. The arguments can be injected * as * * <code> * &#64;Main List<String> * </code> * @param args */ public Builder withArgs(String[] args) { this.args.addAll(Lists.newArrayList(args)); return this; } /** * Specify an optional main class to instantiate. Alternatively the * main class can be added as an eager singleton * @param main */ public Builder withMainClass(Class<?> main) { this.main = main; return this; } /** * Specify an externally provided {@link TerminationEvent}. If not specified * the default {@link BlockingTerminationEvent} will be used. * @param event */ public Builder withTerminateEvent(TerminationEvent event) { this.terminateEvent = event; return this; } public StandaloneRunnerModule build() { return new StandaloneRunnerModule(this); } } public static Builder builder() { return new Builder(); } @LazySingleton public static class StandaloneFramework implements LifecycleRunner { @Inject private Injector injector ; @Inject private LifecycleManager manager; @Inject(optional=true) private @Main Class<?> mainClass; @Inject(optional=true) private @Main List<String> args; @Inject private @Main TerminationEvent terminateEvent; /** * This is the application's main 'run' loop. which blocks on the termination event */ @PostConstruct public void init() { try { LOG.info("Starting application"); manager.start(); if (mainClass != null) injector.getInstance(mainClass); final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("GovernatorStandaloneTerminator-%d").build()); executor.execute(new Runnable() { @Override public void run() { LOG.info("Waiting for terminate event"); try { terminateEvent.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } LOG.info("Terminating application"); manager.close(); executor.shutdown(); } }); } catch (Exception e) { LOG.error("Error executing application ", e); } } } private final List<String> args; private final Class<?> main; private final TerminationEvent terminateEvent; public StandaloneRunnerModule(String[] args, Class<?> main) { this.args = ImmutableList.copyOf(args); this.main = main; this.terminateEvent = null; } private StandaloneRunnerModule(Builder builder) { this.args = builder.args; this.main = builder.main; this.terminateEvent = builder.terminateEvent; } @Singleton public static class MainInjectorModule extends AbstractModule { @Override protected void configure() { bind(LifecycleRunner.class).to(StandaloneFramework.class).asEagerSingleton(); } } @Override public void configure(BootstrapBinder binder) { binder.bind(MainInjectorModule.class); if (main != null) { binder.bind(main).in(LazySingletonScope.get()); binder.bind(new TypeLiteral<Class<?>>() {}).annotatedWith(Main.class).toInstance(main); } if (args != null) { binder.bind(new TypeLiteral<List<String>>() {}).annotatedWith(Main.class).toInstance(args); } if (terminateEvent == null) binder.bind(TerminationEvent.class).annotatedWith(Main.class).to(BlockingTerminationEvent.class); else binder.bind(TerminationEvent.class).annotatedWith(Main.class).toInstance(terminateEvent); } }
5,775
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/runner
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/runner/events/SelfDestructingTerminationEvent.java
package com.netflix.governator.guice.runner.events; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * Used mainly for testing the SelfDestructingTerminationEvent will fire the main TerminateEvent * after a specified amount of time has elapsed, causing the application to exit. * @author elandau */ public class SelfDestructingTerminationEvent extends BlockingTerminationEvent { public SelfDestructingTerminationEvent(final long timeout, final TimeUnit units) { Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setDaemon(true).build()) .schedule(new Runnable() { @Override public void run() { terminate(); } }, timeout, units); } }
5,776
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/runner
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/runner/events/BlockingTerminationEvent.java
package com.netflix.governator.guice.runner.events; import javax.inject.Singleton; import com.netflix.governator.guice.runner.TerminationEvent; /** * Simple TerminatEvent using a countdown latch as the termination signal. * * @author elandau */ @Singleton public class BlockingTerminationEvent implements TerminationEvent { private volatile boolean isTerminated = false; @Override public synchronized void await() throws InterruptedException { while (!isTerminated) { this.wait(); } } @Override public synchronized void terminate() { isTerminated = true; this.notifyAll(); } @Override public boolean isTerminated() { return isTerminated; } }
5,777
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/annotations/Bootstrap.java
package com.netflix.governator.guice.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; import com.google.inject.Binder; import com.google.inject.Module; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; import com.netflix.governator.guice.LifecycleInjectorBuilder; import com.netflix.governator.guice.LifecycleInjectorBuilderSuite; @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Bootstrap { /** * For most cases module() should suffice. LifecycleInjectorBuilderSuite is being * deprecated in favor of plain guice Module's or BootstrapMoudle where absolutely * necessary. * @deprecated */ Class<? extends LifecycleInjectorBuilderSuite> value() default NullLifecycleInjectorBuilderSuite.class; Class<? extends BootstrapModule> bootstrap() default NullBootstrapModule.class; Class<? extends Module> module() default NullModule.class; public static class NullBootstrapModule implements BootstrapModule { @Override public void configure(BootstrapBinder binder) { } } public static class NullLifecycleInjectorBuilderSuite implements LifecycleInjectorBuilderSuite { @Override public void configure(LifecycleInjectorBuilder builder) { } } public static class NullModule implements Module { @Override public void configure(Binder binder) { } } }
5,778
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/annotations/GovernatorConfiguration.java
package com.netflix.governator.guice.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; import com.google.inject.Stage; import com.netflix.governator.guice.LifecycleInjectorMode; import com.netflix.governator.guice.ModuleTransformer; import com.netflix.governator.guice.PostInjectorAction; import com.netflix.governator.guice.bootstrap.GovernatorBootstrap; /** * Governator configuration for the main bootstrap class with 'good' default */ @Documented @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Bootstrap(bootstrap=GovernatorBootstrap.class) public @interface GovernatorConfiguration { /** * Turn on class path scanning for @AutoBindSingleton * @return */ boolean enableAutoBindSingleton() default false; /** * Change the {@link Stage} for the main injector. By default we use DEVELOPMENT * stage is it provides the most deterministic behavior for transitive lazy * singleton instantiation. * @return */ Stage stage() default Stage.DEVELOPMENT; /** * Simulated child injectors is the prefered mode but can be changed here * back to REAL_CHILD_INJECTORS. * @return */ LifecycleInjectorMode mode() default LifecycleInjectorMode.SIMULATED_CHILD_INJECTORS; /** * Actions to perform after the injector is created * @return */ Class<? extends PostInjectorAction>[] actions() default {}; /** * {@link ModuleTransform} operations to perform on the final list of modules * @return */ Class<? extends ModuleTransformer>[] transformers() default {}; }
5,779
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/concurrent/ConcurrentProviders.java
package com.netflix.governator.guice.concurrent; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.ProvisionException; import com.google.inject.TypeLiteral; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.Dependency; import com.google.inject.spi.InjectionPoint; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderWithExtensionVisitor; import com.google.inject.spi.Toolable; import com.netflix.governator.annotations.NonConcurrent; import com.netflix.governator.lifecycle.LifecycleListener; /** * Utility class for creating Providers that allow for concurrent instantiation * of dependencies to a type. * * @author elandau * */ public class ConcurrentProviders { /** * Create a Provider that will construct all constructor arguments in parallel and wait * for all dependencies to be constructed before invoking the constructor of the type. * * For example, consider the following class that has 4 dependencies * * {@code * @Singleton * public class Foo { * @Inject * public Foo(@NonConcurrent NonConcurrentSingleton, DependencyA a, DependencyB b, Provider<DependencyC> c, NonSingletonD d) { * } * } * } * * and the following Guice binding to enable the concurrent behavior, * * {@code * public configure() { * bind(Foo.class).toProvider(ConcurrentProviders.of(Foo.class)).asEagerSingleton(); * } * } * * When Foo is created eagerly (by Guice) the provider will spawn 4 threads each creating * one of the above dependencies. Note that for Provider<DependencyC> the provider will * be created and not an instance of DependencyC. Also, note that NonConcurrentSingleton * will not be constructed in a separate thread. * * Note that a dedicated pool of N threads (where N is the number of dependencies) is created * when Foo is first constructed. Upon instantiation of Foo the pool is shut down and the * resulting instance of Foo cached for future retrieval. * * It's also important to note that ALL transitive dependencies of Foo MUST be in the * <b>FineGrainedLazySingleton</b> scope, otherwise there is a high risk of hitting the global Guice * Singleton scope deadlock issue. Any parameter that causes this deadlock can be annotated * with @NonConcurrent to force it to be created within the same thread as the injectee. * * @param type * @return */ public static <T> Provider<T> of(final Class<? extends T> type) { return new ProviderWithExtensionVisitor<T>() { private volatile T instance; private Injector injector; private Set<LifecycleListener> listeners = Collections.emptySet(); public T get() { if ( instance == null ) { synchronized (this) { if ( instance == null ) { instance = createAndInjectMember(); } } } return instance; } private T createAndInjectMember() { T instance = create(); injector.injectMembers(instance); return instance; } private T create() { // Look for an @Inject constructor or just create a new instance if not found InjectionPoint injectionPoint = InjectionPoint.forConstructorOf(type); final long startTime = System.nanoTime(); for (LifecycleListener listener : listeners) { listener.objectInjecting(TypeLiteral.get(type)); } if (injectionPoint != null) { List<Dependency<?>> deps = injectionPoint.getDependencies(); if (deps.size() > 0) { Constructor<?> constructor = (Constructor<?>)injectionPoint.getMember(); // One thread for each dependency ExecutorService executor = Executors.newCachedThreadPool( new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("ConcurrentProviders-" + type.getSimpleName() + "-%d") .build()); try { List<Supplier<?>> suppliers = Lists.newArrayListWithCapacity(deps.size()); // Iterate all constructor dependencies and get and instance from the Injector for (final Dependency<?> dep : deps) { if (!isConcurrent(constructor, dep.getParameterIndex())) { suppliers.add(getCreator(dep.getKey())); } else { final Future<?> future = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { return getCreator(dep.getKey()).get(); } }); suppliers.add(new Supplier() { @Override public Object get() { try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ProvisionException("interrupted during provision"); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } } }); } } // All dependencies are now being instantiated in parallel // Fetch the arguments from the futures and put in an array to pass to newInstance List<Object> params = Lists.newArrayListWithCapacity(deps.size()); for (Supplier<?> supplier: suppliers) { params.add(supplier.get()); } // All dependencies have been initialized // Look for the @Inject constructor and invoke it. try { T obj = (T)constructor.newInstance(params.toArray()); long duration = System.nanoTime() - startTime; for (LifecycleListener listener : listeners) { listener.objectInjected((TypeLiteral<T>)TypeLiteral.get(type), obj, duration, TimeUnit.NANOSECONDS); } return obj; } catch (Exception e) { throw new RuntimeException(e); } } finally { executor.shutdown(); } } } try { T obj = type.newInstance(); long duration = System.nanoTime() - startTime; for (LifecycleListener listener : listeners) { listener.objectInjected((TypeLiteral<T>)TypeLiteral.get(type), obj, duration, TimeUnit.NANOSECONDS); } return obj; } catch (Exception e) { e.printStackTrace(); throw new ProvisionException("Error constructing object of type " + type.getName(), e); } } private boolean isConcurrent(Constructor<?> constructor, int parameterIndex) { Annotation[] annots = constructor.getParameterAnnotations()[parameterIndex]; if (annots != null) { for (Annotation annot : annots) { if (annot.annotationType().equals(NonConcurrent.class)) { return false; } } } return true; } /** * Required to get the Injector in {@link initialize()} */ @Override public <B, V> V acceptExtensionVisitor( BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) { return visitor.visit(binding); } @Inject @Toolable void initialize(Injector injector) { this.injector = injector; } @Inject(optional = true) void setListeners(Set<LifecycleListener> listeners) { this.listeners = listeners; } public <S> Supplier<S> getCreator(final Key<S> key) { return new Supplier<S>() { @Override public S get() { final long startTime = System.nanoTime(); for (LifecycleListener listener : listeners) { listener.objectInjecting(key.getTypeLiteral()); } S obj = injector.getInstance(key); final long duration = System.nanoTime() - startTime; for (LifecycleListener listener : listeners) { listener.objectInjected(key.getTypeLiteral(), obj, duration, TimeUnit.NANOSECONDS); } return obj; } }; } }; } }
5,780
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/actions/CreateAllBoundSingletons.java
package com.netflix.governator.guice.actions; import java.lang.annotation.Annotation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Scope; import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.spi.DefaultBindingScopingVisitor; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.LinkedKeyBinding; import com.netflix.governator.guice.PostInjectorAction; /** * Explicit singleton bindings are not eagerly created when running in Stage.DEVELOPMENT. * This method iterates through all explicit bindings (those made though a guice module) for singletons * and creates them eagerly after the injector was created. */ public class CreateAllBoundSingletons implements PostInjectorAction { @Override public void call(Injector injector) { for (final Binding<?> binding : injector.getBindings().values()) { binding.acceptVisitor(new DefaultElementVisitor<Void>() { public <T> Void visit(final Binding<T> binding) { // This takes care of bindings to concrete classes binding.acceptScopingVisitor(new DefaultBindingScopingVisitor<Void>() { @Override public Void visitScope(Scope scope) { if (scope.equals(Scopes.SINGLETON)) { binding.getProvider().get(); } return null; } }); // This takes care of the interface .to() bindings binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, Void>() { public Void visit(LinkedKeyBinding<? extends T> linkedKeyBinding) { Key<?> key = linkedKeyBinding.getLinkedKey(); Class<?> type = key.getTypeLiteral().getRawType(); if (type.getAnnotation(Singleton.class) != null || type.getAnnotation(javax.inject.Singleton.class) != null) { binding.getProvider().get(); } return null; } }); return visitOther(binding); } }); } } }
5,781
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/actions/LifecycleManagerStarter.java
package com.netflix.governator.guice.actions; import com.google.inject.Injector; import com.netflix.governator.guice.PostInjectorAction; import com.netflix.governator.lifecycle.LifecycleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LifecycleManagerStarter implements PostInjectorAction { private static final Logger log = LoggerFactory.getLogger(LifecycleManagerStarter.class); @Override public void call(Injector injector) { LifecycleManager manager = injector.getInstance(LifecycleManager.class); try { manager.start(); } catch (Exception e) { log.error("Failed to start LifecycleManager", e); } } }
5,782
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/actions/GrapherAction.java
package com.netflix.governator.guice.actions; import com.google.inject.Injector; import com.netflix.governator.guice.Grapher; import com.netflix.governator.guice.PostInjectorAction; public class GrapherAction implements PostInjectorAction { private String text; @Override public void call(Injector injector) { Grapher grapher = injector.getInstance(Grapher.class); try { text = grapher.graph(); } catch (Exception e) { throw new RuntimeException(e); } } public String getText() { return text; } }
5,783
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/actions/BindingReport.java
package com.netflix.governator.guice.actions; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.spi.DefaultBindingTargetVisitor; import com.google.inject.spi.DefaultElementVisitor; import com.google.inject.spi.Dependency; import com.google.inject.spi.InjectionPoint; 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; import com.netflix.governator.guice.PostInjectorAction; public class BindingReport implements PostInjectorAction { private static final Logger LOG = LoggerFactory.getLogger(BindingReport.class); private final String label; public BindingReport(String label) { this.label = label; } public BindingReport() { this(">>>> GUICE BINDING REPORT <<<<"); } @Override public void call(Injector injector) { LOG.info("Bindings for " + label); LOG.info(describeBindings("Binding : ", injector.getBindings().entrySet())); Map<Key<?>, Binding<?>> jitBindings = Maps.difference(injector.getAllBindings(), injector.getBindings()).entriesOnlyOnLeft(); LOG.info(describeBindings("JIT : ", jitBindings.entrySet())); } private String describeBindings(final String label, Set<Entry<Key<?>, Binding<?>>> bindings) { final StringBuilder sb = new StringBuilder(); for (Entry<Key<?>, Binding<?>> binding : bindings) { binding.getValue().acceptVisitor(new DefaultElementVisitor<Void>() { @Override public <T> Void visit(Binding<T> binding) { sb.append("\n" + label + binding.getKey()).append("\n"); if (binding.getSource() != null) { sb.append(" where : " + binding.getSource()).append("\n");; } binding.acceptTargetVisitor(new DefaultBindingTargetVisitor<T, Void>() { public Void visit(UntargettedBinding<? extends T> untargettedBinding) { sb.append(describeInjectionPoints(untargettedBinding.getKey().getTypeLiteral())); return null; } @Override public Void visit(InstanceBinding<? extends T> binding) { sb.append(" to (I) : " + binding.getInstance().getClass()).append("\n"); sb.append(describeInjectionPoints(TypeLiteral.get(binding.getInstance().getClass()))); return null; } @Override public Void visit(ProviderInstanceBinding<? extends T> binding) { sb.append(" to (P) : " + binding.getProviderInstance().getClass()).append("\n"); sb.append(describeInjectionPoints(TypeLiteral.get(binding.getProviderInstance().getClass()))); return null; } @Override public Void visit(ProviderKeyBinding<? extends T> binding) { sb.append(" to (P) : " + binding.getProviderKey()).append("\n"); sb.append(describeInjectionPoints(binding.getProviderKey().getTypeLiteral())); return null; } @Override public Void visit(LinkedKeyBinding<? extends T> binding) { sb.append(" to (I) : " + binding.getLinkedKey()).append("\n"); sb.append(describeInjectionPoints(binding.getLinkedKey().getTypeLiteral())); return null; } @Override public Void visit(ProviderBinding<? extends T> binding) { sb.append(" to (P) : " + binding.getProvidedKey()).append("\n"); sb.append(describeInjectionPoints(binding.getProvidedKey().getTypeLiteral())); return null; } }); sb.append(describeInjectionPoints(binding.getKey().getTypeLiteral())); return null; } }); } return sb.toString(); } private String describeInjectionPoints(TypeLiteral<?> type) { StringBuilder sb = new StringBuilder(); try { InjectionPoint ip = InjectionPoint.forConstructorOf(type); List<Dependency<?>> deps = ip.getDependencies(); if (!deps.isEmpty()) { for (Dependency<?> dep : deps) { sb.append(" dep : " + dep.getKey()).append("\n"); } } } catch (Exception e) { } try { Set<InjectionPoint> ips = InjectionPoint.forInstanceMethodsAndFields(type); for (InjectionPoint ip2 : ips) { List<Dependency<?>> deps = ip2.getDependencies(); if (!deps.isEmpty()) { for (Dependency<?> dep : deps) { sb.append(" mem : " + dep.getKey()).append("\n"); } } } } catch (Exception e) { } return sb.toString(); } }
5,784
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/main/BootstrapMain.java
package com.netflix.governator.guice.main; import com.google.inject.AbstractModule; import com.google.inject.ProvisionException; import com.netflix.governator.guice.LifecycleInjector; /** * Main class for loading a bootstrap configuration via main(). When running an application set * this to the main class and set the first argument to the name of the bootstrap'd class. * * java BootstrapMain com.org.MyApplicationBootstrap ... * * Where, * * <pre> * {@code * @GovernatorConfiguration * public class MyApplicationBootstrap extends AbstractModule { * public void configure() { * // your application bindings here * } * } * } * </pre> * * Note that any component in your application can gain access to the command line arguments by injecting * Arguments. Also, it is the responsibility of your application to parse the command line and manage * the application lifecycle. In the future there may be governator subprojects for various cli parsing * and command line processing libraries (such as apache commons cli) * * <pre> * {@code * @Singleton * public class MyApplication { * @Inject * MyApplication(Arguments args) { * } * } * } * </pre> * @author elandau */ public class BootstrapMain { public static void main(final String args[]) { try { Class<?> mainClass = Class.forName(args[0]); LifecycleInjector.bootstrap(mainClass, new AbstractModule() { @Override protected void configure() { bind(Arguments.class).toInstance(new Arguments(args)); } }); } catch (Exception e) { throw new ProvisionException("Error instantiating main class", e); } } }
5,785
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/main/Arguments.java
package com.netflix.governator.guice.main; /** * Placeholder for command line arguments. For now the placeholder only contains the * command line arguments but may be extended to include additional application context. * * @author elandau * */ public class Arguments { private String[] args; public Arguments(String[] args) { this.args = args; } public String[] getArguments() { return args; } }
5,786
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/serviceloader/ServiceLoaderBootstrapModule.java
package com.netflix.governator.guice.serviceloader; import java.util.ServiceLoader; import com.google.common.collect.Lists; import com.google.inject.Module; import com.netflix.governator.guice.BootstrapBinder; import com.netflix.governator.guice.BootstrapModule; /** * BootstrapModule that loads guice modules via the ServiceLoader. * * @author elandau */ public class ServiceLoaderBootstrapModule implements BootstrapModule { private final Class<? extends Module> type; public ServiceLoaderBootstrapModule() { this(Module.class); } public ServiceLoaderBootstrapModule(Class<? extends Module> type) { this.type = type; } @Override public void configure(BootstrapBinder binder) { ServiceLoader<? extends Module> modules = ServiceLoader.load(type); binder.includeModules(Lists.newArrayList(modules.iterator())); } }
5,787
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/guice/serviceloader/ServiceLoaderModule.java
package com.netflix.governator.guice.serviceloader; import java.util.List; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.Callable; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.ProvisionException; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.multibindings.Multibinder; import com.google.inject.spi.BindingTargetVisitor; import com.google.inject.spi.ProviderInstanceBinding; import com.google.inject.spi.ProviderWithExtensionVisitor; import com.google.inject.spi.Toolable; import com.google.inject.util.Types; import com.netflix.governator.guice.lazy.LazySingletonScope; /** * Simple Guice module to integrate with the {@link ServiceLoader}. * * @author elandau */ public abstract class ServiceLoaderModule extends AbstractModule { public interface ServiceBinder<S> { public ServiceBinder<S> usingClassLoader(ClassLoader classLoader); public ServiceBinder<S> forInstalledServices(Boolean installed); public ServiceBinder<S> usingMultibinding(Boolean usingMultibinding); } static class ServiceBinderImpl<S> extends AbstractModule implements ServiceBinder<S> { private final Class<S> type; private ClassLoader classLoader; private boolean installed = false; private boolean asMultibinding = false; ServiceBinderImpl(Class<S> type) { this.type = type; } @Override public ServiceBinder<S> usingClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; } @Override public ServiceBinder<S> forInstalledServices(Boolean installed) { this.installed = installed; return this; } @Override public ServiceBinder<S> usingMultibinding(Boolean usingMultibinding) { this.asMultibinding = usingMultibinding; return this; } protected 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); } }; } if (asMultibinding) { Multibinder<S> binding = Multibinder.newSetBinder(binder(), type); ServiceLoader<S> services; try { for (S service : loader.call()) { System.out.println("Adding binding for service : " + service.getClass().getName()); ServiceProvider<S> provider = new ServiceProvider<S>(service); binding.addBinding().toProvider(provider).in(Scopes.SINGLETON); } } catch (Exception e) { throw new ProvisionException("Failed to load services for '" + type + "'", e); } } else { @SuppressWarnings("unchecked") TypeLiteral<Set<S>> typeLiteral = (TypeLiteral<Set<S>>) TypeLiteral.get(Types.setOf(type)); bind(typeLiteral) .toProvider(new ServiceSetProvider<S>(loader)) .in(LazySingletonScope.get()); } } } private final List<ServiceBinderImpl<?>> binders = Lists.newArrayList(); @Override public final void configure() { configureServices(); for (ServiceBinderImpl<?> binder : binders) { install(binder); } } protected abstract void configureServices(); /** * Load services and make them available via a Set<S> binding using * multi-binding. Note that this methods loads services lazily but also * allows for additional bindings to be done via Guice modules. * * @param type */ public <S> ServiceBinder<S> bindServices(final Class<S> type) { ServiceBinderImpl<S> binder = new ServiceBinderImpl<S>(type); binders.add(binder); return binder; } /** * Custom provider that enables member injection on services * * @author elandau * * @param <S> */ public static class ServiceSetProvider<S> implements ProviderWithExtensionVisitor<Set<S>> { private Injector injector; private Callable<ServiceLoader<S>> loader; public ServiceSetProvider(Callable<ServiceLoader<S>> loader) { this.loader = loader; } @Override public Set<S> get() { Set<S> services = Sets.newHashSet(); try { for (S obj : loader.call()) { injector.injectMembers(obj); services.add(obj); } } catch (Exception e) { throw new ProvisionException("Failed to laod services", e); } return services; } @Override public <B, V> V acceptExtensionVisitor( BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) { return visitor.visit(binding); } @Inject @Toolable void initialize(Injector injector) { this.injector = injector; } } /** * Custom provider that allows for member injection of a service. Note that while the * service was instantiated at binding time the members injection won't happen until the * set of services is injected. * * @author elandau * * @param <S> */ public static class ServiceProvider<S> implements ProviderWithExtensionVisitor<S> { private S service; public ServiceProvider(S service) { this.service = service; } @Override public S get() { System.out.println("Get : " + service.getClass().getName()); return service; } @Override public <B, V> V acceptExtensionVisitor( BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) { return visitor.visit(binding); } @Inject @Toolable void initialize(Injector injector) { injector.injectMembers(service); } } }
5,788
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/FilteredLifecycleListener.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import java.util.Arrays; import java.util.Collection; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.inject.TypeLiteral; /** * Wrapper listener that forwards to the provided listener only when the obj is in one of the * specified base packages. */ public class FilteredLifecycleListener extends DefaultLifecycleListener { private final ImmutableSet<String> packages; private final LifecycleListener listener; /** * @param listener actual listener * @param basePackages set of base packages */ public FilteredLifecycleListener(LifecycleListener listener, String... basePackages) { this(listener, Sets.newHashSet(Arrays.asList(basePackages))); } /** * @param listener actual listener * @param basePackages set of base packages */ public FilteredLifecycleListener(LifecycleListener listener, Collection<String> basePackages) { this.listener = listener; packages = ImmutableSet.copyOf(basePackages); } @Override public <T> void objectInjected(TypeLiteral<T> type, T obj) { if ( isInPackages(obj) ) { listener.objectInjected(type, obj); } } @Override public void stateChanged(Object obj, LifecycleState newState) { if ( isInPackages(obj) ) { listener.stateChanged(obj, newState); } } private boolean isInPackages(Object obj) { if ( obj != null ) { return isInPackages(obj.getClass()); } return false; } private boolean isInPackages(Class type) { if ( type != null ) { for ( String p : packages ) { if ( type.getPackage().getName().startsWith(p) ) { return true; } } } return false; } }
5,789
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/ValidationException.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; public class ValidationException extends Exception { public ValidationException(String message) { super(message); } public ValidationException(String message, Throwable cause) { super(message, cause); } }
5,790
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/LifecycleMethods.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import static com.netflix.governator.internal.BinaryConstant.I15_32768; import static com.netflix.governator.internal.BinaryConstant.I2_4; import static com.netflix.governator.internal.BinaryConstant.I3_8; import static com.netflix.governator.internal.BinaryConstant.I4_16; import static com.netflix.governator.internal.BinaryConstant.I5_32; 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.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.annotation.Resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.netflix.governator.annotations.Configuration; import com.netflix.governator.annotations.ConfigurationVariable; import com.netflix.governator.annotations.PreConfiguration; import com.netflix.governator.annotations.WarmUp; /** * Used internally to hold the methods important to the LifecycleManager */ public class LifecycleMethods { private static final Field[] EMPTY_FIELDS = new Field[0]; private static final Method[] EMPTY_METHODS = new Method[0]; private static final Lookup METHOD_HANDLE_LOOKUP = MethodHandles.lookup(); private static final Logger log = LoggerFactory.getLogger(LifecycleMethods.class); private boolean hasValidations = false; private final boolean hasResources; final static Map<Method, MethodHandle> methodHandlesMap = new ConcurrentHashMap<>(I15_32768); final static Map<Field, MethodHandle[]> fieldHandlesMap = new ConcurrentHashMap<>(I15_32768); static class LifecycleMethodsBuilder { private static final Logger log = LoggerFactory.getLogger(LifecycleMethodsBuilder.class); private static final Collection<Class<? extends Annotation>> fieldAnnotations; private static final Collection<Class<? extends Annotation>> methodAnnotations; private static final Collection<Class<? extends Annotation>> classAnnotations; static { ImmutableSet.Builder<Class<? extends Annotation>> methodAnnotationsBuilder = ImmutableSet.builder(); methodAnnotationsBuilder.add(PreConfiguration.class); methodAnnotationsBuilder.add(PostConstruct.class); methodAnnotationsBuilder.add(PreDestroy.class); methodAnnotationsBuilder.add(Resource.class); methodAnnotationsBuilder.add(Resources.class); methodAnnotationsBuilder.add(WarmUp.class); methodAnnotations = methodAnnotationsBuilder.build(); ImmutableSet.Builder<Class<? extends Annotation>> fieldAnnotationsBuilder = ImmutableSet.builder(); fieldAnnotationsBuilder.add(Configuration.class); fieldAnnotationsBuilder.add(Resource.class); fieldAnnotationsBuilder.add(Resources.class); fieldAnnotationsBuilder.add(ConfigurationVariable.class); fieldAnnotations = fieldAnnotationsBuilder.build(); ImmutableSet.Builder<Class<? extends Annotation>> classAnnotationsBuilder = ImmutableSet.builder(); classAnnotationsBuilder.add(Resource.class); classAnnotationsBuilder.add(Resources.class); classAnnotations = classAnnotationsBuilder.build(); } private boolean hasValidations = false; private boolean hasResources; private final Multimap<Class<? extends Annotation>, Field> fieldMap = ArrayListMultimap.create(I3_8, I5_32); private final Multimap<Class<? extends Annotation>, Method> methodMap = ArrayListMultimap.create(I4_16, I5_32); private final Multimap<Class<? extends Annotation>, Annotation> classMap = ArrayListMultimap.create(I2_4, I3_8); public LifecycleMethodsBuilder( Class<?> clazz, Multimap<Class<? extends Annotation>, String> usedNames) { addLifeCycleMethods(clazz, ArrayListMultimap.<Class<? extends Annotation>, String> create()); this.hasResources = fieldMap.containsKey(Resource.class) || fieldMap.containsKey(Resources.class) || methodMap.containsKey(Resource.class) || methodMap.containsKey(Resources.class) || classMap.containsKey(Resource.class) || classMap.containsKey(Resources.class); this.hasValidations = this.hasValidations || !methodMap.isEmpty() || !fieldMap.isEmpty(); } void addLifeCycleMethods(Class<?> clazz, Multimap<Class<? extends Annotation>, String> usedNames) { if (clazz == null) { return; } for (Class<? extends Annotation> annotationClass : classAnnotations) { if (clazz.isAnnotationPresent(annotationClass)) { classMap.put(annotationClass, clazz.getAnnotation(annotationClass)); } } for (Field field : getDeclaredFields(clazz)) { if (field.isSynthetic()) { continue; } for (Class<? extends Annotation> annotationClass : fieldAnnotations) { processField(field, annotationClass, usedNames); } } for (Method method : getDeclaredMethods(clazz)) { if (method.isSynthetic() || method.isBridge()) { continue; } for (Class<? extends Annotation> annotationClass : methodAnnotations) { processMethod(method, annotationClass, usedNames); } } addLifeCycleMethods(clazz.getSuperclass(), usedNames); for (Class<?> face : clazz.getInterfaces()) { addLifeCycleMethods(face, usedNames); } } private Method[] getDeclaredMethods(Class<?> clazz) { try { return clazz.getDeclaredMethods(); } catch (Throwable e) { handleReflectionError(clazz, e); } return EMPTY_METHODS; } private Field[] getDeclaredFields(Class<?> clazz) { try { return clazz.getDeclaredFields(); } catch (Throwable e) { handleReflectionError(clazz, e); } return EMPTY_FIELDS; } private void handleReflectionError(Class<?> clazz, Throwable e) { if (e != null) { if ((e instanceof NoClassDefFoundError) || (e instanceof ClassNotFoundException)) { log.debug(String.format( "Class %s could not be resolved because of a class path error. Governator cannot further process the class.", clazz.getName()), e); return; } handleReflectionError(clazz, e.getCause()); } } private void processField(Field field, Class<? extends Annotation> annotationClass, Multimap<Class<? extends Annotation>, String> usedNames) { if (field.isAnnotationPresent(annotationClass)) { String fieldName = field.getName(); if (!usedNames.get(annotationClass).contains(fieldName)) { field.setAccessible(true); usedNames.put(annotationClass, fieldName); fieldMap.put(annotationClass, field); try { fieldHandlesMap.put(field, new MethodHandle[] { METHOD_HANDLE_LOOKUP.unreflectGetter(field), METHOD_HANDLE_LOOKUP.unreflectSetter(field) }); } catch (IllegalAccessException e) { // that's ok, will use reflected method } } } } private void processMethod(Method method, Class<? extends Annotation> annotationClass, Multimap<Class<? extends Annotation>, String> usedNames) { if (method.isAnnotationPresent(annotationClass)) { String methodName = method.getName(); if (!usedNames.get(annotationClass).contains(methodName)) { method.setAccessible(true); usedNames.put(annotationClass, methodName); methodMap.put(annotationClass, method); try { methodHandlesMap.put(method, METHOD_HANDLE_LOOKUP.unreflect(method)); } catch (IllegalAccessException e) { // that's ok, will use reflected method } } } } } Map<Class<? extends Annotation>, Method[]> methodMap; Map<Class<? extends Annotation>, Field[]> fieldMap; Map<Class<? extends Annotation>, Annotation[]> classMap; public LifecycleMethods(Class<?> clazz) { LifecycleMethodsBuilder builder = new LifecycleMethodsBuilder(clazz, ArrayListMultimap.<Class<? extends Annotation>, String> create()); this.hasResources = builder.hasResources; this.hasValidations = builder.hasValidations; methodMap = new HashMap<>(); for (Map.Entry<Class<? extends Annotation>, Collection<Method>> entry : builder.methodMap.asMap().entrySet()) { methodMap.put(entry.getKey(), entry.getValue().toArray(EMPTY_METHODS)); } fieldMap = new HashMap<>(); for (Map.Entry<Class<? extends Annotation>, Collection<Field>> entry : builder.fieldMap.asMap().entrySet()) { fieldMap.put(entry.getKey(), entry.getValue().toArray(EMPTY_FIELDS)); } classMap = new HashMap<>(); for (Class<? extends Annotation> annotationClass : LifecycleMethodsBuilder.classAnnotations) { Annotation[] annotationsArray = (Annotation[])Array.newInstance(annotationClass, 0); Collection<Annotation> annotations = builder.classMap.get(annotationClass); if (annotations != null) { annotationsArray = annotations.toArray(annotationsArray); } classMap.put(annotationClass, annotationsArray); } } public boolean hasLifecycleAnnotations() { return hasValidations; } public boolean hasResources() { return hasResources; } @Deprecated public Collection<Method> methodsFor(Class<? extends Annotation> annotation) { return Arrays.asList(annotatedMethods(annotation)); } @Deprecated public Collection<Field> fieldsFor(Class<? extends Annotation> annotation) { return Arrays.asList(annotatedFields(annotation)); } @Deprecated public <T extends Annotation> Collection<T> classAnnotationsFor(Class<T> annotation) { return Arrays.asList(classAnnotations(annotation)); } public Method[] annotatedMethods(Class<? extends Annotation> annotation) { Method[] methods = methodMap.get(annotation); return (methods != null) ? methods : EMPTY_METHODS; } public Field[] annotatedFields(Class<? extends Annotation> annotation) { Field[] fields = fieldMap.get(annotation); return (fields != null) ? fields : EMPTY_FIELDS; } @SuppressWarnings("unchecked") public <T extends Annotation> T[] classAnnotations(Class<T> annotation) { Annotation[] annotations = classMap.get(annotation); return (annotations != null) ? (T[])annotations : (T[])Array.newInstance(annotation, 0); } public void methodInvoke(Class<? extends Annotation> annotation, Object obj) throws Exception { if (methodMap.containsKey(annotation)) { for (Method m : methodMap.get(annotation)) { methodInvoke(m, obj); } } } public static void methodInvoke(Method method, Object target) throws InvocationTargetException, IllegalAccessException { MethodHandle handler = methodHandlesMap.get(method); if (handler != null) { try { if (Modifier.isStatic(method.getModifiers())) { log.warn("static lifecycle method: {}, target={}", method, target); handler.invoke(); } else { handler.invoke(target); } } catch (Throwable e) { throw new InvocationTargetException(e, "invokedynamic: method=" + method + ", target=" + target); } } else { // fall through to reflected invocation method.invoke(target); } } public static <T> T fieldGet(Field field, Object obj) throws InvocationTargetException, IllegalAccessException { MethodHandle[] fieldHandler = fieldHandlesMap.get(field); if (fieldHandler == null) { fieldHandler = updateFieldHandles(field); } if (fieldHandler != EMPTY_FIELD_HANDLES) { try { return Modifier.isStatic(field.getModifiers()) ? (T)fieldHandler[0].invoke() : (T)fieldHandler[0].bindTo(obj).invoke(); } catch (Throwable e) { throw new InvocationTargetException(e, "invokedynamic: field=" + field + ", object=" + obj); } } else { return (T)field.get(obj); } } public static void fieldSet(Field field, Object object, Object value) throws InvocationTargetException, IllegalAccessException { MethodHandle[] fieldHandler = fieldHandlesMap.get(field); if (fieldHandler == null) { fieldHandler = updateFieldHandles(field); } if (fieldHandler != EMPTY_FIELD_HANDLES) { try { if (Modifier.isStatic(field.getModifiers())) { fieldHandler[1].invoke(value); } else { fieldHandler[1].bindTo(object).invoke(value); } } catch (Throwable e) { throw new InvocationTargetException(e, "invokedynamic: field=" + field + ", object=" + object); } } else { field.set(object, value); } } private final static MethodHandle[] EMPTY_FIELD_HANDLES = new MethodHandle[0]; private static MethodHandle[] updateFieldHandles(Field field) { synchronized(fieldHandlesMap) { MethodHandle[] handles = EMPTY_FIELD_HANDLES; try { handles = new MethodHandle[] { METHOD_HANDLE_LOOKUP.unreflectGetter(field), METHOD_HANDLE_LOOKUP.unreflectSetter(field) }; } catch (IllegalAccessException e) { // that's ok, will use reflected method } fieldHandlesMap.put(field, handles); return handles; } } }
5,791
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/LifecycleListener.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import java.util.concurrent.TimeUnit; import com.google.inject.TypeLiteral; /** * Callback for injected instances */ public interface LifecycleListener { /** * When Guice injects an object, this callback will be notified * * @param type object type being injected * @param obj object being injected */ public <T> void objectInjected(TypeLiteral<T> type, T obj); /** * Notification that an object has been injected and the amount of time it to either * construct or retrieve the object. This call is in addition to the objectInjected * above and is currently only called when constructing via ConcurrentProvider * * @param type * @param obj * @param duration * @param units */ public <T> void objectInjected(TypeLiteral<T> type, T obj, long duration, TimeUnit units); /** * Called when an object's lifecycle state changes * * @param obj the object * @param newState new state */ public void stateChanged(Object obj, LifecycleState newState); /** * Notification that an object is being injected. This call is only made when injecting * using ConcurrentProvider * @param type */ public <T> void objectInjecting(TypeLiteral<T> type); }
5,792
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/DefaultConfigurationMapper.java
package com.netflix.governator.lifecycle; import java.lang.reflect.Field; import java.util.Collections; import java.util.Map; import com.google.common.collect.Maps; import com.netflix.governator.annotations.Configuration; import com.netflix.governator.annotations.ConfigurationVariable; import com.netflix.governator.configuration.ConfigurationDocumentation; import com.netflix.governator.configuration.ConfigurationMapper; import com.netflix.governator.configuration.ConfigurationProvider; public class DefaultConfigurationMapper implements ConfigurationMapper { @Override public void mapConfiguration( ConfigurationProvider configurationProvider, ConfigurationDocumentation configurationDocumentation, Object obj, LifecycleMethods methods) throws Exception { /** * Map a configuration to any field with @Configuration annotation */ Field[] configurationFields = methods.annotatedFields(Configuration.class); if (configurationFields.length > 0) { /** * Any field annotated with @ConfigurationVariable will be available for replacement when generating * property names */ final Map<String, String> overrides; Field[] configurationVariableFields = methods.annotatedFields(ConfigurationVariable.class); if (configurationVariableFields.length > 0) { overrides = Maps.newHashMap(); for (Field variableField : configurationVariableFields) { ConfigurationVariable annot = variableField.getAnnotation(ConfigurationVariable.class); if (annot != null) { overrides.put(annot.name(), methods.fieldGet(variableField, obj).toString()); } } } else { overrides = Collections.emptyMap(); } ConfigurationProcessor configurationProcessor = new ConfigurationProcessor(configurationProvider, configurationDocumentation); for (Field configurationField : configurationFields) { try { configurationProcessor.assignConfiguration(obj, configurationField, overrides); } catch (Exception e) { throw new Exception(String.format("Failed to bind property '%s' for instance of '%s'", configurationField.getName(), obj.getClass().getCanonicalName()), e); } } } } }
5,793
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/ClasspathScanner.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import static org.objectweb.asm.ClassReader.SKIP_CODE; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.netflix.governator.internal.scanner.ClasspathUrlDecoder; import com.netflix.governator.internal.scanner.DirectoryClassFilter; import org.objectweb.asm.ClassReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URL; import java.util.Collection; import java.util.Enumeration; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Utility to find annotated classes */ public class ClasspathScanner { private static final Logger log = LoggerFactory.getLogger(ClasspathScanner.class); protected final ClassLoader classLoader; private final Set<Class<?>> classes; private final Set<Constructor> constructors; private final Set<Method> methods; private final Set<Field> fields; /** * @param basePackages list of packages to search (recursively) * @param annotations class annotations to search for */ public ClasspathScanner(Collection<String> basePackages, Collection<Class<? extends Annotation>> annotations) { this(basePackages, annotations, Thread.currentThread().getContextClassLoader()); } /** * @param basePackages list of packages to search (recursively) * @param annotations class annotations to search for * @param classLoader ClassLoader containing the classes to be scanned */ public ClasspathScanner(Collection<String> basePackages, Collection<Class<? extends Annotation>> annotations, final ClassLoader classLoader) { Preconditions.checkNotNull(annotations, "annotations cannot be null"); Preconditions.checkNotNull(classLoader, "classLoader cannot be null"); log.debug("Starting classpath scanning..."); this.classLoader = classLoader; Set<Class<?>> localClasses = Sets.newHashSet(); Set<Constructor> localConstructors = Sets.newHashSet(); Set<Method> localMethods = Sets.newHashSet(); Set<Field> localFields = Sets.newHashSet(); doScanning(basePackages, annotations, localClasses, localConstructors, localMethods, localFields); classes = ImmutableSet.copyOf(localClasses); constructors = ImmutableSet.copyOf(localConstructors); methods = ImmutableSet.copyOf(localMethods); fields = ImmutableSet.copyOf(localFields); log.debug("Classpath scanning done"); } /** * @return the found classes */ public Set<Class<?>> getClasses() { return classes; } public Set<Constructor> getConstructors() { return constructors; } public Set<Method> getMethods() { return methods; } public Set<Field> getFields() { return fields; } protected void doScanning(Collection<String> basePackages, Collection<Class<? extends Annotation>> annotations, Set<Class<?>> localClasses, Set<Constructor> localConstructors, Set<Method> localMethods, Set<Field> localFields) { if ( basePackages.isEmpty() ) { log.warn("No base packages specified - no classpath scanning will be done"); return; } log.info("Scanning packages : " + basePackages + " for annotations " + annotations); for ( String basePackage : basePackages ) { try { String basePackageWithSlashes = basePackage.replace(".", "/"); Enumeration<URL> resources = classLoader.getResources(basePackageWithSlashes); while ( resources.hasMoreElements() ) { URL url = resources.nextElement(); 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 ( Enumeration<JarEntry> list = jar.entries(); list.hasMoreElements(); ) { JarEntry entry = list.nextElement(); try { if ( entry.getName().endsWith(".class") && entry.getName().startsWith(basePackageWithSlashes)) { AnnotationFinder finder = new AnnotationFinder(classLoader, annotations); new ClassReader(jar.getInputStream(entry)).accept(finder, SKIP_CODE); applyFinderResults(localClasses, localConstructors, localMethods, localFields, finder); } } catch (Exception e) { log.debug("Unable to scan JarEntry '{}' in '{}'. {}", new Object[]{entry.getName(), file.getCanonicalPath(), e.getMessage()}); } } } catch (Exception e ) { log.debug("Unable to scan '{}'. {}", new Object[]{file.getCanonicalPath(), e.getMessage()}); } } else { DirectoryClassFilter filter = new DirectoryClassFilter(classLoader); for ( String className : filter.filesInPackage(url, basePackage) ) { AnnotationFinder finder = new AnnotationFinder(classLoader, annotations); new ClassReader(filter.bytecodeOf(className)).accept(finder, SKIP_CODE); applyFinderResults(localClasses, localConstructors, localMethods, localFields, finder); } } } catch (Exception e) { log.debug("Unable to scan jar '{}'. {} ", new Object[]{url, e.getMessage()}); } } } catch ( Exception e ) { throw new RuntimeException("Classpath scanning failed for package \'" + basePackage + "\'", e); } } } private void applyFinderResults(Set<Class<?>> localClasses, Set<Constructor> localConstructors, Set<Method> localMethods, Set<Field> localFields, AnnotationFinder finder) { for (Class<?> cls : finder.getAnnotatedClasses()) { if (localClasses.contains(cls)) { log.debug(String.format("Duplicate class found for '%s'", cls.getCanonicalName())); } else { localClasses.add(cls); } } for (Method method : finder.getAnnotatedMethods()) { if (localMethods.contains(method)) { log.debug(String.format("Duplicate method found for '%s:%s'", method.getClass().getCanonicalName(), method.getName())); } else { localMethods.add(method); } } for (Constructor<?> ctor : finder.getAnnotatedConstructors()) { if (localConstructors.contains(ctor)) { log.debug(String.format("Duplicate constructor found for '%s:%s'", ctor.getClass().getCanonicalName(), ctor.toString())); } else { localConstructors.add(ctor); } } for (Field field : finder.getAnnotatedFields()) { if (localFields.contains(field)) { log.debug(String.format("Duplicate field found for '%s:%s'", field.getClass().getCanonicalName(), field.toString())); } else { localFields.add(field); } } } private boolean isJarURL(URL url) { String protocol = url.getProtocol(); return "zip".equals(protocol) || "jar".equals(protocol) || ("file".equals(protocol) && url.getPath().endsWith(".jar")); } }
5,794
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/LifecycleManager.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import static com.netflix.governator.internal.BinaryConstant.I10_1024; import static com.netflix.governator.internal.BinaryConstant.I15_32768; import static com.netflix.governator.internal.BinaryConstant.I16_65536; import java.io.Closeable; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.MapMaker; import com.google.inject.Binding; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import com.netflix.governator.LifecycleAction; import com.netflix.governator.annotations.PreConfiguration; import com.netflix.governator.annotations.WarmUp; import com.netflix.governator.configuration.ConfigurationColumnWriter; import com.netflix.governator.configuration.ConfigurationDocumentation; import com.netflix.governator.configuration.ConfigurationMapper; import com.netflix.governator.configuration.ConfigurationProvider; import com.netflix.governator.guice.PostInjectorAction; import com.netflix.governator.internal.JSR250LifecycleAction.ValidationMode; import com.netflix.governator.internal.PreDestroyLifecycleFeature; import com.netflix.governator.internal.PreDestroyMonitor; /** * Main instance management container */ @Singleton public class LifecycleManager implements Closeable, PostInjectorAction { private enum State { LATENT, STARTING, STARTED, CLOSED } private final Logger log = LoggerFactory.getLogger(getClass()); private final ConcurrentMap<Object, LifecycleStateWrapper> objectStates = new MapMaker().weakKeys().initialCapacity(I16_65536).concurrencyLevel(I10_1024).makeMap(); private final PreDestroyLifecycleFeature preDestroyLifecycleFeature = new PreDestroyLifecycleFeature(ValidationMode.LAX); private final ConcurrentMap<Class<?>, List<LifecycleAction>> preDestroyActionCache = new ConcurrentHashMap<Class<?>, List<LifecycleAction>>(I15_32768); private final AtomicReference<State> state = new AtomicReference<State>(State.LATENT); private final ConfigurationDocumentation configurationDocumentation; private final ConfigurationProvider configurationProvider; private final ConfigurationMapper configurationMapper; private final ResourceMapper resourceMapper; final LifecycleListener[] listeners; private final PreDestroyMonitor preDestroyMonitor; private com.netflix.governator.LifecycleManager newLifecycleManager; public LifecycleManager() { this(new LifecycleManagerArguments(), null); } public LifecycleManager(LifecycleManagerArguments arguments) { this(arguments, null); } @Inject public LifecycleManager(LifecycleManagerArguments arguments, Injector injector) { if (injector != null) { preDestroyMonitor = new PreDestroyMonitor(injector.getScopeBindings()); } else { preDestroyMonitor = null; } configurationMapper = arguments.getConfigurationMapper(); newLifecycleManager = arguments.getLifecycleManager(); listeners = arguments.getLifecycleListeners().toArray(new LifecycleListener[0]); resourceMapper = new ResourceMapper(injector, ImmutableSet.copyOf(arguments.getResourceLocators())); configurationDocumentation = arguments.getConfigurationDocumentation(); configurationProvider = arguments.getConfigurationProvider(); } /** * Return the lifecycle listener if any * * @return listener or null */ public Collection<LifecycleListener> getListeners() { return Arrays.asList(listeners); } /** * Add the objects to the container. Their assets will be loaded, post construct methods called, etc. * * @param objects objects to add * @throws Exception errors */ @Deprecated public void add(Object... objects) throws Exception { for ( Object obj : objects ) { add(obj); } } /** * Add the object to the container. Its assets will be loaded, post construct methods called, etc. * * @param obj object to add * @throws Exception errors */ @Deprecated public void add(Object obj) throws Exception { add(obj, null, new LifecycleMethods(obj.getClass())); } /** * Add the object to the container. Its assets will be loaded, post construct methods called, etc. * This version helps performance when the lifecycle methods have already been calculated * * @param obj object to add * @param methods calculated lifecycle methods * @throws Exception errors */ @Deprecated public void add(Object obj, LifecycleMethods methods) throws Exception { add(obj, null, methods); } /** * Add the object to the container. Its assets will be loaded, post construct methods called, etc. * This version helps performance when the lifecycle methods have already been calculated * * @param obj object to add * @param methods calculated lifecycle methods * @throws Exception errors */ public <T> void add(T obj, Binding<T> binding, LifecycleMethods methods) throws Exception { State managerState = state.get(); if (managerState != State.CLOSED) { startInstance(obj, binding, methods); if ( managerState == State.STARTED ) { initializeObjectPostStart(obj); } } else { throw new IllegalStateException("LifecycleManager is closed"); } } /** * Returns true if the lifecycle has started (i.e. {@link #start()} has been called). * * @return true/false */ public boolean hasStarted() { return state.get() == State.STARTED; } /** * Return the current state of the given object or LATENT if unknown * * @param obj object to check * @return state */ public LifecycleState getState(Object obj) { LifecycleStateWrapper lifecycleState = objectStates.get(obj); if ( lifecycleState == null ) { return hasStarted() ? LifecycleState.ACTIVE : LifecycleState.LATENT; } else { synchronized(lifecycleState) { return lifecycleState.get(); } } } /** * The manager MUST be started. Note: this method * waits indefinitely for warm up methods to complete * * @throws Exception errors */ public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTING), "Already started"); new ConfigurationColumnWriter(configurationDocumentation).output(log); if (newLifecycleManager != null) { newLifecycleManager.notifyStarted(); } state.set(State.STARTED); } /** * The manager MUST be started. This version of start() has a maximum * wait period for warm up methods. * * @param maxWait maximum wait time for warm up methods - if the time elapses, the warm up methods are interrupted * @param unit time unit * @return true if warm up methods successfully executed, false if the time elapses * @throws Exception errors */ @Deprecated public boolean start(long maxWait, TimeUnit unit) throws Exception { start(); return true; } @SuppressWarnings("deprecation") private <T> void startInstance(T obj, Binding<T> binding, LifecycleMethods methods) throws Exception { final Class<?> instanceType = obj.getClass(); log.debug("Starting {}", instanceType.getName()); final LifecycleStateWrapper lifecycleState = initState(obj, LifecycleState.PRE_CONFIGURATION); methods.methodInvoke(PreConfiguration.class, obj); lifecycleState.set(obj, LifecycleState.SETTING_CONFIGURATION); configurationMapper.mapConfiguration(configurationProvider, configurationDocumentation, obj, methods); lifecycleState.set(obj, LifecycleState.SETTING_RESOURCES); resourceMapper.map(obj, methods); lifecycleState.set(obj, LifecycleState.POST_CONSTRUCTING); methods.methodInvoke(PostConstruct.class, obj); Method[] warmUpMethods = methods.annotatedMethods(WarmUp.class); if (warmUpMethods.length > 0) { Method[] postConstructMethods = methods.annotatedMethods(PostConstruct.class); for ( Method warmupMethod : warmUpMethods) { boolean skipWarmup = false; // assuming very few methods in both WarmUp and PostConstruct for (Method postConstruct : postConstructMethods) { if (postConstruct == warmupMethod) { skipWarmup = true; break; } } if (!skipWarmup) { log.debug("\t{}()", warmupMethod.getName()); LifecycleMethods.methodInvoke(warmupMethod, obj); } } } List<LifecycleAction> preDestroyActions; if (preDestroyActionCache.containsKey(instanceType)) { preDestroyActions = preDestroyActionCache.get(instanceType); } else { preDestroyActions = preDestroyLifecycleFeature.getActionsForType(instanceType); preDestroyActionCache.put(instanceType, preDestroyActions); } if ( !preDestroyActions.isEmpty() ) { if (binding != null) { preDestroyMonitor.register(obj, binding, preDestroyActions); } else { preDestroyMonitor.register(obj, "legacy", preDestroyActions); } } } class LifecycleStateWrapper { LifecycleState state; public void set(Object managedInstance, LifecycleState state) { this.state = state; for ( LifecycleListener listener : listeners ) { listener.stateChanged(managedInstance, state); } } public LifecycleState get() { return state; } } private LifecycleStateWrapper initState(Object obj, LifecycleState state) { LifecycleStateWrapper stateWrapper = new LifecycleStateWrapper(); objectStates.put(obj, stateWrapper); stateWrapper.set(obj, state); return stateWrapper; } @Override public synchronized void close() { if ( state.compareAndSet(State.STARTING, State.CLOSED) || state.compareAndSet(State.STARTED, State.CLOSED) ) { try { if (newLifecycleManager != null) { newLifecycleManager.notifyShutdown(); } preDestroyMonitor.close(); } catch ( Exception e ) { log.error("While stopping instances", e); } finally { objectStates.clear(); preDestroyActionCache.clear(); } } } private void initializeObjectPostStart(Object obj) { } @Override public void call(Injector injector) { this.resourceMapper.setInjector(injector); this.preDestroyMonitor.addScopeBindings(injector.getScopeBindings()); } }
5,795
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/LifecycleConfigurationProviders.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import com.netflix.governator.configuration.CompositeConfigurationProvider; import com.netflix.governator.configuration.ConfigurationProvider; import java.util.Collection; public class LifecycleConfigurationProviders extends CompositeConfigurationProvider { public LifecycleConfigurationProviders(ConfigurationProvider... providers) { super(providers); } public LifecycleConfigurationProviders(Collection<ConfigurationProvider> providers) { super(providers); } }
5,796
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/LifecycleState.java
/* * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; /** * Possible states for a managed object */ public enum LifecycleState { /** * Not managed, unknown, etc. */ LATENT, /** * Loading/assigning Resources */ SETTING_RESOURCES, /** * Calling PreConfiguration methods */ PRE_CONFIGURATION, /** * Assigning configuration values */ SETTING_CONFIGURATION, /** * Calling PostConstruct methods */ POST_CONSTRUCTING, /** * Preparing to call warm-up methods */ PRE_WARMING_UP, /** * Calling warm-up methods */ WARMING_UP, /** * Completely ready for use */ ACTIVE, /** * Calling PreDestroy methods (state will change to LATENT after this) */ PRE_DESTROYING, /** * There was an exception during warm-up/cool-down for this object */ ERROR }
5,797
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/LifecycleManagerArguments.java
/* * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.governator.lifecycle; import java.util.Collection; import java.util.Set; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import com.netflix.governator.LifecycleManager; import com.netflix.governator.configuration.ConfigurationDocumentation; import com.netflix.governator.configuration.ConfigurationMapper; import com.netflix.governator.configuration.ConfigurationProvider; public class LifecycleManagerArguments { private static final Logger log = LoggerFactory.getLogger(LifecycleManagerArguments.class); @VisibleForTesting public static final long DEFAULT_WARM_UP_PADDING_MS = TimeUnit.SECONDS.toMillis(3); @Inject private ConfigurationProvider configurationProvider; @Inject private ConfigurationMapper configurationMapper; @Inject private ConfigurationDocumentation configurationDocumentation; @Inject private LifecycleManager lifecycleManager; @Inject(optional = true) private Set<LifecycleListener> lifecycleListeners = ImmutableSet.of(); @Inject(optional = true) private Set<ResourceLocator> resourceLocators = ImmutableSet.of(); @Inject public LifecycleManagerArguments( ConfigurationDocumentation configurationDocumentation, ConfigurationMapper configurationMapper, ConfigurationProvider configurationProvider) { this.configurationDocumentation = configurationDocumentation; this.configurationMapper = configurationMapper; this.configurationProvider = configurationProvider; } public LifecycleManagerArguments() { this.configurationDocumentation = new ConfigurationDocumentation(); this.configurationProvider = new LifecycleConfigurationProviders(); this.configurationMapper = new DefaultConfigurationMapper(); } public ConfigurationMapper getConfigurationMapper() { return configurationMapper; } public void setConfigurationMapper(ConfigurationMapper configurationMapper) { this.configurationMapper = configurationMapper; } public ConfigurationProvider getConfigurationProvider() { return configurationProvider; } public Collection<LifecycleListener> getLifecycleListeners() { return lifecycleListeners; } public void setConfigurationProvider(ConfigurationProvider configurationProvider) { this.configurationProvider = configurationProvider; } public void setLifecycleListeners(Collection<LifecycleListener> lifecycleListeners) { this.lifecycleListeners = ImmutableSet.copyOf(lifecycleListeners); } public Set<ResourceLocator> getResourceLocators() { return resourceLocators; } public void setResourceLocators(Set<ResourceLocator> resourceLocators) { this.resourceLocators = ImmutableSet.copyOf(resourceLocators); } public void setConfigurationDocumentation(ConfigurationDocumentation configurationDocumentation) { this.configurationDocumentation = configurationDocumentation; } public ConfigurationDocumentation getConfigurationDocumentation() { return configurationDocumentation; } public LifecycleManager getLifecycleManager() { return lifecycleManager; } public void setLifecycleManager(LifecycleManager lifecycleManager) { this.lifecycleManager = lifecycleManager; } }
5,798
0
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator
Create_ds/governator/governator-legacy/src/main/java/com/netflix/governator/lifecycle/ResourceMapper.java
package com.netflix.governator.lifecycle; import java.beans.Introspector; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.Iterator; import javax.annotation.Resource; import javax.annotation.Resources; import javax.naming.NamingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Injector; class ResourceMapper { private final Logger log = LoggerFactory.getLogger(getClass()); private Injector injector; private final Collection<ResourceLocator> resourceLocators; ResourceMapper(Injector injector, Collection<ResourceLocator> resourceLocators) { this.injector = injector; this.resourceLocators = resourceLocators; } public void map(Object obj, LifecycleMethods methods) throws Exception { if (methods.hasResources()) { for (Field field : methods.annotatedFields(Resources.class)) { Resources resources = field.getAnnotation(Resources.class); for (Resource resource : resources.value()) { setFieldResource(obj, field, resource); } } for (Field field : methods.annotatedFields(Resource.class)) { Resource resource = field.getAnnotation(Resource.class); setFieldResource(obj, field, resource); } for (Method method : methods.annotatedMethods(Resources.class)) { Resources resources = method.getAnnotation(Resources.class); for (Resource resource : resources.value()) { setMethodResource(obj, method, resource); } } for (Method method : methods.annotatedMethods(Resource.class)) { Resource resource = method.getAnnotation(Resource.class); setMethodResource(obj, method, resource); } for (Resources resources : methods.classAnnotations(Resources.class)) { for (Resource resource : resources.value()) { loadClassResource(resource); } } for (Resource resource : methods.classAnnotations(Resource.class)) { loadClassResource(resource); } } } private void loadClassResource(Resource resource) throws Exception { if ((resource.name().isEmpty()) || (resource.type() == Object.class)) { throw new Exception("Class resources must have both name() and type(): " + resource); } findResource(resource); } private void setMethodResource(Object obj, Method method, Resource resource) throws Exception { if ((method.getParameterTypes().length != 1) || (method.getReturnType() != Void.TYPE)) { throw new Exception(String.format("%s.%s() is not a proper JavaBean setter.", obj.getClass().getName(), method.getName())); } String beanName = method.getName(); if (beanName.toLowerCase().startsWith("set")) { beanName = beanName.substring("set".length()); } beanName = Introspector.decapitalize(beanName); String siteName = obj.getClass().getName() + "/" + beanName; resource = adjustResource(resource, method.getParameterTypes()[0], siteName); Object resourceObj = findResource(resource); method.setAccessible(true); method.invoke(obj, resourceObj); } private void setFieldResource(Object obj, Field field, Resource resource) throws Exception { String siteName = obj.getClass().getName() + "/" + field.getName(); Object resourceObj = findResource(adjustResource(resource, field.getType(), siteName)); field.setAccessible(true); field.set(obj, resourceObj); } private Resource adjustResource(final Resource resource, final Class<?> siteType, final String siteName) { return new Resource() { @Override public String name() { return (resource.name().length() == 0) ? siteName : resource.name(); } /** * Method needed for eventual java7 compatibility */ public String lookup() { return name(); } @Override public Class<?> type() { return (resource.type() == Object.class) ? siteType : resource.type(); } @Override public AuthenticationType authenticationType() { return resource.authenticationType(); } @Override public boolean shareable() { return resource.shareable(); } @Override public String mappedName() { return resource.mappedName(); } @Override public String description() { return resource.description(); } @Override public Class<? extends Annotation> annotationType() { return resource.annotationType(); } }; } private Object findResource(Resource resource) throws Exception { if (!resourceLocators.isEmpty()) { final Iterator<ResourceLocator> iterator = resourceLocators.iterator(); ResourceLocator locator = iterator.next(); ResourceLocator nextInChain = new ResourceLocator() { @Override public Object locate(Resource resource, ResourceLocator nextInChain) throws Exception { if (iterator.hasNext()) { return iterator.next().locate(resource, this); } return defaultFindResource(resource); } }; return locator.locate(resource, nextInChain); } return defaultFindResource(resource); } private Object defaultFindResource(Resource resource) throws Exception { if (injector == null) { throw new NamingException("Could not find resource: " + resource); } // noinspection unchecked log.debug("defaultFindResource using injector {}", System.identityHashCode(injector)); return injector.getInstance(resource.type()); } public Injector getInjector() { return injector; } public void setInjector(Injector injector) { this.injector = injector; } }
5,799