Search in sources :

Example 11 with Message

use of com.google.inject.spi.Message in project guice by google.

the class MessagesTest method customErrorMessage.

@Test
public void customErrorMessage() {
    List<Message> messages = new ArrayList<>();
    Throwable cause = null;
    messages.add(new Message("example", cause));
    messages.add(exampleError("a"));
    messages.add(exampleError("b"));
    messages.add(exampleError("a"));
    String result = Messages.formatMessages("Example", messages);
    assertThat(result).isEqualTo("Example:\n\n" + "1) example\n\n" + "2) a\n" + "Duplicate count: 2\n\n" + "3) b\n" + "Duplicate count: 1\n\n" + "3 errors");
}
Also used : Message(com.google.inject.spi.Message) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 12 with Message

use of com.google.inject.spi.Message in project guice by google.

the class CheckedProviderTest method testProvisionExceptionOnDependenciesOfCxtor.

public void testProvisionExceptionOnDependenciesOfCxtor() throws Exception {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            ThrowingProviderBinder.create(binder()).bind(RemoteProvider.class, Foo.class).providing(ProvisionExceptionFoo.class);
            bindScope(BadScope.class, new Scope() {

                @Override
                public <T> Provider<T> scope(final Key<T> key, Provider<T> unscoped) {
                    return new Provider<T>() {

                        @Override
                        public T get() {
                            throw new OutOfScopeException("failure: " + key.toString());
                        }
                    };
                }
            });
        }
    });
    try {
        injector.getInstance(Key.get(remoteProviderOfFoo)).get();
        fail();
    } catch (ProvisionException pe) {
        Message message = Iterables.getOnlyElement(pe.getErrorMessages());
        assertEquals("com.google.inject.OutOfScopeException: failure: " + Key.get(Unscoped1.class), message.getMessage());
    }
}
Also used : Message(com.google.inject.spi.Message) OutOfScopeException(com.google.inject.OutOfScopeException) AbstractModule(com.google.inject.AbstractModule) Provider(com.google.inject.Provider) ProvisionException(com.google.inject.ProvisionException) Scope(com.google.inject.Scope) Injector(com.google.inject.Injector) Key(com.google.inject.Key)

Example 13 with Message

use of com.google.inject.spi.Message in project guice by google.

the class FactoryProvider2 method initialize.

/**
 * At injector-creation time, we initialize the invocation handler. At this time we make sure all
 * factory methods will be able to build the target types.
 */
@Inject
@Toolable
void initialize(Injector injector) {
    if (this.injector != null) {
        throw new ConfigurationException(ImmutableList.of(new Message(FactoryProvider2.class, "Factories.create() factories may only be used in one Injector!")));
    }
    this.injector = injector;
    for (Map.Entry<Method, AssistData> entry : assistDataByMethod.entrySet()) {
        Method method = entry.getKey();
        AssistData data = entry.getValue();
        Object[] args;
        if (!data.optimized) {
            args = new Object[method.getParameterTypes().length];
            Arrays.fill(args, "dummy object for validating Factories");
        } else {
            // won't be used -- instead will bind to data.providers.
            args = null;
        }
        getBindingFromNewInjector(method, args, // throws if the binding isn't properly configured
        data);
    }
}
Also used : Message(com.google.inject.spi.Message) ConfigurationException(com.google.inject.ConfigurationException) Method(java.lang.reflect.Method) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Inject(com.google.inject.Inject) Toolable(com.google.inject.spi.Toolable)

Example 14 with Message

use of com.google.inject.spi.Message in project guice by google.

the class FactoryProvider2 method invoke.

/**
 * When a factory method is invoked, we create a child injector that binds all parameters, then
 * use that to get an instance of the return type.
 */
@Override
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
    // can call the default method implementation (and not our proxied version of it).
    if (methodHandleByMethod.containsKey(method)) {
        return methodHandleByMethod.get(method).invokeWithArguments(args);
    }
    if (method.getDeclaringClass().equals(Object.class)) {
        if ("equals".equals(method.getName())) {
            return proxy == args[0];
        } else if ("hashCode".equals(method.getName())) {
            return System.identityHashCode(proxy);
        } else {
            return method.invoke(this, args);
        }
    }
    AssistData data = assistDataByMethod.get(method);
    checkState(data != null, "No data for method: %s", method);
    Provider<?> provider;
    if (data.cachedBinding != null) {
        // Try to get optimized form...
        provider = data.cachedBinding.getProvider();
    } else {
        provider = getBindingFromNewInjector(method, args, data).getProvider();
    }
    try {
        int p = 0;
        for (ThreadLocalProvider tlp : data.providers) {
            tlp.set(args[p++]);
        }
        return provider.get();
    } catch (ProvisionException e) {
        // if this is an exception declared by the factory method, throw it as-is
        if (e.getErrorMessages().size() == 1) {
            Message onlyError = getOnlyElement(e.getErrorMessages());
            Throwable cause = onlyError.getCause();
            if (cause != null && canRethrow(method, cause)) {
                throw cause;
            }
        }
        throw e;
    } finally {
        for (ThreadLocalProvider tlp : data.providers) {
            tlp.remove();
        }
    }
}
Also used : ProvisionException(com.google.inject.ProvisionException) Message(com.google.inject.spi.Message) InjectionPoint(com.google.inject.spi.InjectionPoint)

Example 15 with Message

use of com.google.inject.spi.Message in project gerrit by GerritCodeReview.

the class BaseInit method createSiteInit.

private SiteInit createSiteInit() {
    final ConsoleUI ui = getConsoleUI();
    final Path sitePath = getSitePath();
    final List<Module> m = new ArrayList<>();
    final SecureStoreInitData secureStoreInitData = discoverSecureStoreClass();
    final String currentSecureStoreClassName = getConfiguredSecureStoreClass();
    if (secureStoreInitData != null && currentSecureStoreClassName != null && !currentSecureStoreClassName.equals(secureStoreInitData.className)) {
        String err = String.format("Different secure store was previously configured: %s. " + "Use SwitchSecureStore program to switch between implementations.", currentSecureStoreClassName);
        throw die(err);
    }
    m.add(new GerritServerConfigModule());
    m.add(new InitModule(standalone));
    m.add(new AbstractModule() {

        @Override
        protected void configure() {
            bind(ConsoleUI.class).toInstance(ui);
            bind(Path.class).annotatedWith(SitePath.class).toInstance(sitePath);
            List<String> plugins = MoreObjects.firstNonNull(getInstallPlugins(), new ArrayList<>());
            bind(new TypeLiteral<List<String>>() {
            }).annotatedWith(InstallPlugins.class).toInstance(plugins);
            bind(new TypeLiteral<Boolean>() {
            }).annotatedWith(InstallAllPlugins.class).toInstance(installAllPlugins());
            bind(PluginsDistribution.class).toInstance(pluginsDistribution);
            String secureStoreClassName;
            if (secureStoreInitData != null) {
                secureStoreClassName = secureStoreInitData.className;
            } else {
                secureStoreClassName = currentSecureStoreClassName;
            }
            if (secureStoreClassName != null) {
                ui.message("Using secure store: %s\n", secureStoreClassName);
            }
            bind(SecureStoreInitData.class).toProvider(Providers.of(secureStoreInitData));
            bind(String.class).annotatedWith(SecureStoreClassName.class).toProvider(Providers.of(secureStoreClassName));
            bind(SecureStore.class).toProvider(SecureStoreProvider.class).in(SINGLETON);
            bind(new TypeLiteral<List<String>>() {
            }).annotatedWith(LibraryDownload.class).toInstance(getSkippedDownloads());
            bind(Boolean.class).annotatedWith(LibraryDownload.class).toInstance(skipAllDownloads());
            bind(MetricMaker.class).to(DisabledMetricMaker.class);
        }
    });
    try {
        return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class);
    } catch (CreationException ce) {
        final Message first = ce.getErrorMessages().iterator().next();
        Throwable why = first.getCause();
        if (why instanceof Die) {
            throw (Die) why;
        }
        final StringBuilder buf = new StringBuilder(ce.getMessage());
        while (why != null) {
            buf.append("\n");
            buf.append(why.getMessage());
            why = why.getCause();
            if (why != null) {
                buf.append("\n  caused by ");
            }
        }
        throw die(buf.toString(), new RuntimeException("InitInjector failed", ce));
    }
}
Also used : Path(java.nio.file.Path) SitePath(com.google.gerrit.server.config.SitePath) Die(com.google.gerrit.common.Die) Message(com.google.inject.spi.Message) ArrayList(java.util.ArrayList) CreationException(com.google.inject.CreationException) SecureStore(com.google.gerrit.server.securestore.SecureStore) ConsoleUI(com.google.gerrit.pgm.init.api.ConsoleUI) AbstractModule(com.google.inject.AbstractModule) GerritServerConfigModule(com.google.gerrit.server.config.GerritServerConfigModule) TypeLiteral(com.google.inject.TypeLiteral) List(java.util.List) ArrayList(java.util.ArrayList) Module(com.google.inject.Module) GerritServerConfigModule(com.google.gerrit.server.config.GerritServerConfigModule) IndexModule(com.google.gerrit.server.index.IndexModule) AbstractModule(com.google.inject.AbstractModule) DisabledMetricMaker(com.google.gerrit.metrics.DisabledMetricMaker)

Aggregations

Message (com.google.inject.spi.Message)49 ProvisionException (com.google.inject.ProvisionException)9 CreationException (com.google.inject.CreationException)7 ArrayList (java.util.ArrayList)7 AbstractModule (com.google.inject.AbstractModule)6 Provider (com.google.inject.Provider)5 TypeLiteral (com.google.inject.TypeLiteral)5 Injector (com.google.inject.Injector)4 Module (com.google.inject.Module)4 Errors (com.google.inject.internal.Errors)4 InjectionPoint (com.google.inject.spi.InjectionPoint)4 DisabledMetricMaker (com.google.gerrit.metrics.DisabledMetricMaker)3 GerritServerConfigModule (com.google.gerrit.server.config.GerritServerConfigModule)3 SitePath (com.google.gerrit.server.config.SitePath)3 Test (org.junit.Test)3 JacksonInject (com.fasterxml.jackson.annotation.JacksonInject)2 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)2 AnnotatedField (com.fasterxml.jackson.databind.introspect.AnnotatedField)2 Function (com.google.common.base.Function)2 ImmutableList (com.google.common.collect.ImmutableList)2