summaryrefslogtreecommitdiffstats
path: root/sangria-lazy/src/main/java/com/tavianator/sangria/lazy/LazyBinder.java
blob: baad5daa8b429a0d7d292c828f384b97be89eb3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/****************************************************************************
 * Sangria                                                                  *
 * Copyright (C) 2014 Tavian Barnes <tavianator@tavianator.com>             *
 *                                                                          *
 * 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.tavianator.sangria.lazy;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;

import javax.inject.Provider;

import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.Scope;
import com.google.inject.TypeLiteral;
import com.google.inject.binder.AnnotatedBindingBuilder;
import com.google.inject.binder.LinkedBindingBuilder;
import com.google.inject.binder.ScopedBindingBuilder;
import com.google.inject.spi.BindingTargetVisitor;
import com.google.inject.spi.ProviderInstanceBinding;
import com.google.inject.spi.ProviderWithExtensionVisitor;
import com.google.inject.util.Types;

import com.tavianator.sangria.core.PotentialAnnotation;

/**
 * Binder for {@link Lazy} instances.
 *
 * @author Tavian Barnes (tavianator@tavianator.com)
 * @version 1.2
 * @since 1.2
 */
public class LazyBinder {
    private static final Class<?>[] SKIPPED_SOURCES = {
            LazyBinder.class,
            BindingAnnotator.class,
            LazyBindingBuilder.class,
    };

    private final Binder binder;

    private LazyBinder(Binder binder) {
        this.binder = binder;
    }

    /**
     * Create a {@link LazyBinder}.
     *
     * @param binder The {@link Binder} to use.
     * @return A {@link LazyBinder} instance.
     */
    public static LazyBinder create(Binder binder) {
        return new LazyBinder(binder.skipSources(SKIPPED_SOURCES));
    }

    @SuppressWarnings("unchecked")
    private static <T> TypeLiteral<Lazy<T>> lazyOf(TypeLiteral<T> type) {
        return (TypeLiteral<Lazy<T>>)TypeLiteral.get(Types.newParameterizedType(Lazy.class, type.getType()));
    }

    /**
     * See the EDSL examples at {@link Lazy}.
     */
    public <T> AnnotatedBindingBuilder<T> bind(Class<T> type) {
        return bind(TypeLiteral.get(type));
    }

    /**
     * See the EDSL examples at {@link Lazy}.
     */
    public <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> type) {
        AnnotatedBindingBuilder<Lazy<T>> lazyBinding = binder.bind(lazyOf(type));
        return new LazyBindingBuilder<>(binder, type, lazyBinding, PotentialAnnotation.none());
    }

    /**
     * Applies an annotation to an {@link AnnotatedBindingBuilder}.
     */
    private static class BindingAnnotator<T> implements PotentialAnnotation.Visitor<LinkedBindingBuilder<T>> {
        private final AnnotatedBindingBuilder<T> builder;

        BindingAnnotator(AnnotatedBindingBuilder<T> builder) {
            this.builder = builder;
        }

        @Override
        public LinkedBindingBuilder<T> visitNoAnnotation() {
            return builder;
        }

        @Override
        public LinkedBindingBuilder<T> visitAnnotationType(Class<? extends Annotation> annotationType) {
            return builder.annotatedWith(annotationType);
        }

        @Override
        public LinkedBindingBuilder<T> visitAnnotationInstance(Annotation annotation) {
            return builder.annotatedWith(annotation);
        }
    }

    /**
     * See the EDSL examples at {@link Lazy}.
     */
    public <T> LinkedBindingBuilder<T> bind(Key<T> key) {
        TypeLiteral<T> type = key.getTypeLiteral();
        PotentialAnnotation potentialAnnotation = PotentialAnnotation.from(key);
        return potentialAnnotation.accept(new BindingAnnotator<>(bind(type)));
    }

    /**
     * Actual binder implementation.
     */
    private static class LazyBindingBuilder<T> implements AnnotatedBindingBuilder<T> {
        private final Binder binder;
        private final TypeLiteral<T> type;
        private final AnnotatedBindingBuilder<Lazy<T>> lazyBinding;
        private final PotentialAnnotation potentialAnnotation;

        LazyBindingBuilder(
                Binder binder,
                TypeLiteral<T> type,
                AnnotatedBindingBuilder<Lazy<T>> lazyBinding,
                PotentialAnnotation potentialAnnotation) {
            this.binder = binder;
            this.type = type;
            this.lazyBinding = lazyBinding;
            this.potentialAnnotation = potentialAnnotation;
        }

        @Override
        public LinkedBindingBuilder<T> annotatedWith(Class<? extends Annotation> annotationType) {
            PotentialAnnotation newAnnotation = potentialAnnotation.annotatedWith(annotationType);
            Key<T> key = newAnnotation.getKey(type);

            lazyBinding.annotatedWith(annotationType)
                    .toProvider(new LazyProvider<>(binder.getProvider(key), key));

            return new LazyBindingBuilder<>(binder, type, null, newAnnotation);
        }

        @Override
        public LinkedBindingBuilder<T> annotatedWith(Annotation annotation) {
            PotentialAnnotation newAnnotation = potentialAnnotation.annotatedWith(annotation);
            Key<T> key = newAnnotation.getKey(type);

            lazyBinding.annotatedWith(annotation)
                    .toProvider(new LazyProvider<>(binder.getProvider(key), key));

            return new LazyBindingBuilder<>(binder, type, null, newAnnotation);
        }

        /**
         * @return A binding builder for the underlying binding.
         */
        private LinkedBindingBuilder<T> makeBinder() {
            return binder.bind(potentialAnnotation.getKey(type));
        }

        @Override
        public ScopedBindingBuilder to(Class<? extends T> implementation) {
            return makeBinder().to(implementation);
        }

        @Override
        public ScopedBindingBuilder to(TypeLiteral<? extends T> implementation) {
            return makeBinder().to(implementation);
        }

        @Override
        public ScopedBindingBuilder to(Key<? extends T> targetKey) {
            return makeBinder().to(targetKey);
        }

        @Override
        public void toInstance(T instance) {
            makeBinder().toInstance(instance);
        }

        @Override
        public ScopedBindingBuilder toProvider(com.google.inject.Provider<? extends T> provider) {
            return makeBinder().toProvider(provider);
        }

        @Override
        public ScopedBindingBuilder toProvider(Provider<? extends T> provider) {
            return makeBinder().toProvider(provider);
        }

        @Override
        public ScopedBindingBuilder toProvider(Class<? extends Provider<? extends T>> providerType) {
            return makeBinder().toProvider(providerType);
        }

        @Override
        public ScopedBindingBuilder toProvider(TypeLiteral<? extends Provider<? extends T>> providerType) {
            return makeBinder().toProvider(providerType);
        }

        @Override
        public ScopedBindingBuilder toProvider(Key<? extends Provider<? extends T>> providerKey) {
            return makeBinder().toProvider(providerKey);
        }

        @Override
        public <S extends T> ScopedBindingBuilder toConstructor(Constructor<S> constructor) {
            return makeBinder().toConstructor(constructor);
        }

        @Override
        public <S extends T> ScopedBindingBuilder toConstructor(Constructor<S> constructor, TypeLiteral<? extends S> type) {
            return makeBinder().toConstructor(constructor, type);
        }

        @Override
        public void in(Class<? extends Annotation> scopeAnnotation) {
            makeBinder().in(scopeAnnotation);
        }

        @Override
        public void in(Scope scope) {
            makeBinder().in(scope);
        }

        @Override
        public void asEagerSingleton() {
            makeBinder().asEagerSingleton();
        }
    }

    private static class LazyProvider<T> implements LazyBinding<T>, ProviderWithExtensionVisitor<Lazy<T>> {
        private final Provider<T> provider;
        private final Key<T> key;

        LazyProvider(Provider<T> provider, Key<T> key) {
            this.provider = provider;
            this.key = key;
        }

        @Override
        public Lazy<T> get() {
            return new Lazy<>(provider);
        }

        @Override
        public Key<T> getTargetKey() {
            return key;
        }

        @SuppressWarnings("unchecked") // B must be Lazy<T>
        @Override
        public <B, V> V acceptExtensionVisitor(BindingTargetVisitor<B, V> visitor, ProviderInstanceBinding<? extends B> binding) {
            if (visitor instanceof LazyBindingVisitor) {
                return ((LazyBindingVisitor<T, V>)visitor).visit(this);
            } else {
                return visitor.visit(binding);
            }
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            } else if (!(obj instanceof LazyProvider)) {
                return false;
            }

            LazyProvider<?> other = (LazyProvider<?>) obj;
            return key.equals(other.key);
        }

        @Override
        public int hashCode() {
            return key.hashCode();
        }
    }
}