1 /** 2 * Copyright (C) 2011 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.inject.internal; 18 19 import static com.google.common.base.Preconditions.checkNotNull; 20 21 import com.google.inject.spi.Dependency; 22 import com.google.inject.spi.ProviderInstanceBinding; 23 24 /** 25 * Adapts {@link ProviderInstanceBinding} providers, ensuring circular proxies 26 * fail (or proxy) properly. 27 * 28 * @author sameb (at) google.com (Sam Berlin) 29 */ 30 final class InternalFactoryToInitializableAdapter<T> extends ProviderInternalFactory<T> { 31 32 private final ProvisionListenerStackCallback<T> provisionCallback; 33 private final Initializable<? extends javax.inject.Provider<? extends T>> initializable; 34 35 public InternalFactoryToInitializableAdapter( 36 Initializable<? extends javax.inject.Provider<? extends T>> initializable, 37 Object source, ProvisionListenerStackCallback<T> provisionCallback) { 38 super(source); 39 this.provisionCallback = checkNotNull(provisionCallback, "provisionCallback"); 40 this.initializable = checkNotNull(initializable, "provider"); 41 } 42 43 public T get(Errors errors, InternalContext context, Dependency<?> dependency, boolean linked) 44 throws ErrorsException { 45 return circularGet(initializable.get(errors), errors, context, dependency, 46 provisionCallback); 47 } 48 49 @Override 50 protected T provision(javax.inject.Provider<? extends T> provider, Errors errors, 51 Dependency<?> dependency, ConstructionContext<T> constructionContext) throws ErrorsException { 52 try { 53 return super.provision(provider, errors, dependency, constructionContext); 54 } catch(RuntimeException userException) { 55 throw errors.withSource(source).errorInProvider(userException).toException(); 56 } 57 } 58 59 @Override public String toString() { 60 return initializable.toString(); 61 } 62 } 63