Search in sources :

Example 1 with ProvisionException

use of com.google.inject.ProvisionException in project druid by druid-io.

the class JettyServerModule method initializeServer.

static void initializeServer(Injector injector, Lifecycle lifecycle, final Server server) {
    JettyServerInitializer initializer = injector.getInstance(JettyServerInitializer.class);
    try {
        initializer.initialize(server, injector);
    } catch (ConfigurationException e) {
        throw new ProvisionException(Iterables.getFirst(e.getErrorMessages(), null).getMessage());
    }
    lifecycle.addHandler(new Lifecycle.Handler() {

        @Override
        public void start() throws Exception {
            server.start();
        }

        @Override
        public void stop() {
            try {
                server.stop();
            } catch (Exception e) {
                log.warn(e, "Unable to stop Jetty server.");
            }
        }
    });
}
Also used : ProvisionException(com.google.inject.ProvisionException) ConfigurationException(com.google.inject.ConfigurationException) Lifecycle(io.druid.java.util.common.lifecycle.Lifecycle) ServletException(javax.servlet.ServletException) ProvisionException(com.google.inject.ProvisionException) ConfigurationException(com.google.inject.ConfigurationException)

Example 2 with ProvisionException

use of com.google.inject.ProvisionException in project druid by druid-io.

the class PolyBindTest method testSanity.

@Test
public void testSanity() throws Exception {
    setUp(new Module() {

        @Override
        public void configure(Binder binder) {
            final MapBinder<String, Gogo> gogoBinder = PolyBind.optionBinder(binder, Key.get(Gogo.class));
            gogoBinder.addBinding("a").to(GoA.class);
            gogoBinder.addBinding("b").to(GoB.class);
            final MapBinder<String, GogoSally> gogoSallyBinder = PolyBind.optionBinder(binder, Key.get(GogoSally.class));
            gogoSallyBinder.addBinding("a").to(GoA.class);
            gogoSallyBinder.addBinding("b").to(GoB.class);
            PolyBind.createChoice(binder, "billy", Key.get(Gogo.class, Names.named("reverse")), Key.get(GoB.class));
            final MapBinder<String, Gogo> annotatedGogoBinder = PolyBind.optionBinder(binder, Key.get(Gogo.class, Names.named("reverse")));
            annotatedGogoBinder.addBinding("a").to(GoB.class);
            annotatedGogoBinder.addBinding("b").to(GoA.class);
        }
    });
    Assert.assertEquals("A", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("B", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    props.setProperty("billy", "b");
    Assert.assertEquals("B", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("A", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    props.setProperty("billy", "a");
    Assert.assertEquals("A", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("B", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    props.setProperty("billy", "b");
    Assert.assertEquals("B", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("A", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    props.setProperty("billy", "c");
    Assert.assertEquals("A", injector.getInstance(Gogo.class).go());
    Assert.assertEquals("B", injector.getInstance(Key.get(Gogo.class, Names.named("reverse"))).go());
    // test default property value
    Assert.assertEquals("B", injector.getInstance(GogoSally.class).go());
    props.setProperty("sally", "a");
    Assert.assertEquals("A", injector.getInstance(GogoSally.class).go());
    props.setProperty("sally", "b");
    Assert.assertEquals("B", injector.getInstance(GogoSally.class).go());
    props.setProperty("sally", "c");
    try {
        injector.getInstance(GogoSally.class).go();
        // should never be reached
        Assert.fail();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof ProvisionException);
        Assert.assertTrue(e.getMessage().contains("Unknown provider[c] of Key[type=io.druid.guice.PolyBindTest$GogoSally"));
    }
}
Also used : Binder(com.google.inject.Binder) MapBinder(com.google.inject.multibindings.MapBinder) ProvisionException(com.google.inject.ProvisionException) MapBinder(com.google.inject.multibindings.MapBinder) Module(com.google.inject.Module) ProvisionException(com.google.inject.ProvisionException) Test(org.junit.Test)

Example 3 with ProvisionException

use of com.google.inject.ProvisionException in project druid by druid-io.

the class JsonConfigurator method configurate.

public <T> T configurate(Properties props, String propertyPrefix, Class<T> clazz) throws ProvisionException {
    verifyClazzIsConfigurable(jsonMapper, clazz);
    // Make it end with a period so we only include properties with sub-object thingies.
    final String propertyBase = propertyPrefix.endsWith(".") ? propertyPrefix : propertyPrefix + ".";
    Map<String, Object> jsonMap = Maps.newHashMap();
    for (String prop : props.stringPropertyNames()) {
        if (prop.startsWith(propertyBase)) {
            final String propValue = props.getProperty(prop);
            Object value;
            try {
                // If it's a String Jackson wants it to be quoted, so check if it's not an object or array and quote.
                String modifiedPropValue = propValue;
                if (!(modifiedPropValue.startsWith("[") || modifiedPropValue.startsWith("{"))) {
                    modifiedPropValue = jsonMapper.writeValueAsString(propValue);
                }
                value = jsonMapper.readValue(modifiedPropValue, Object.class);
            } catch (IOException e) {
                log.info(e, "Unable to parse [%s]=[%s] as a json object, using as is.", prop, propValue);
                value = propValue;
            }
            jsonMap.put(prop.substring(propertyBase.length()), value);
        }
    }
    final T config;
    try {
        config = jsonMapper.convertValue(jsonMap, clazz);
    } catch (IllegalArgumentException e) {
        throw new ProvisionException(String.format("Problem parsing object at prefix[%s]: %s.", propertyPrefix, e.getMessage()), e);
    }
    final Set<ConstraintViolation<T>> violations = validator.validate(config);
    if (!violations.isEmpty()) {
        List<String> messages = Lists.newArrayList();
        for (ConstraintViolation<T> violation : violations) {
            String path = "";
            try {
                Class<?> beanClazz = violation.getRootBeanClass();
                final Iterator<Path.Node> iter = violation.getPropertyPath().iterator();
                while (iter.hasNext()) {
                    Path.Node next = iter.next();
                    if (next.getKind() == ElementKind.PROPERTY) {
                        final String fieldName = next.getName();
                        final Field theField = beanClazz.getDeclaredField(fieldName);
                        if (theField.getAnnotation(JacksonInject.class) != null) {
                            path = String.format(" -- Injected field[%s] not bound!?", fieldName);
                            break;
                        }
                        JsonProperty annotation = theField.getAnnotation(JsonProperty.class);
                        final boolean noAnnotationValue = annotation == null || Strings.isNullOrEmpty(annotation.value());
                        final String pathPart = noAnnotationValue ? fieldName : annotation.value();
                        if (path.isEmpty()) {
                            path += pathPart;
                        } else {
                            path += "." + pathPart;
                        }
                    }
                }
            } catch (NoSuchFieldException e) {
                throw Throwables.propagate(e);
            }
            messages.add(String.format("%s - %s", path, violation.getMessage()));
        }
        throw new ProvisionException(Iterables.transform(messages, new Function<String, Message>() {

            @Override
            public Message apply(String input) {
                return new Message(String.format("%s%s", propertyBase, input));
            }
        }));
    }
    log.info("Loaded class[%s] from props[%s] as [%s]", clazz, propertyBase, config);
    return config;
}
Also used : Path(javax.validation.Path) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Message(com.google.inject.spi.Message) IOException(java.io.IOException) AnnotatedField(com.fasterxml.jackson.databind.introspect.AnnotatedField) Field(java.lang.reflect.Field) Function(com.google.common.base.Function) ProvisionException(com.google.inject.ProvisionException) JacksonInject(com.fasterxml.jackson.annotation.JacksonInject) ConstraintViolation(javax.validation.ConstraintViolation)

Example 4 with ProvisionException

use of com.google.inject.ProvisionException in project roboguice by roboguice.

the class MultibinderTest method testMultibinderSetShowsBothElementsIfToStringDifferent.

public void testMultibinderSetShowsBothElementsIfToStringDifferent() {
    // considers.
    class ValueType {

        int a;

        int b;

        ValueType(int a, int b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public boolean equals(Object obj) {
            return (obj instanceof ValueType) && (((ValueType) obj).a == a);
        }

        @Override
        public int hashCode() {
            return a;
        }

        @Override
        public String toString() {
            return String.format("ValueType(%d,%d)", a, b);
        }
    }
    Module module1 = new AbstractModule() {

        protected void configure() {
            final Multibinder<ValueType> multibinder = Multibinder.newSetBinder(binder(), ValueType.class);
            multibinder.addBinding().toProvider(Providers.of(new ValueType(1, 2)));
        }
    };
    Module module2 = new AbstractModule() {

        protected void configure() {
            final Multibinder<ValueType> multibinder = Multibinder.newSetBinder(binder(), ValueType.class);
            multibinder.addBinding().toInstance(new ValueType(1, 3));
        }
    };
    Injector injector = Guice.createInjector(module1, module2);
    TypeLiteral<ValueType> valueType = TypeLiteral.get(ValueType.class);
    TypeLiteral<Set<ValueType>> setOfValueType = new TypeLiteral<Set<ValueType>>() {
    };
    TypeLiteral<Collection<Provider<ValueType>>> collectionOfProvidersOfValueType = new TypeLiteral<Collection<Provider<ValueType>>>() {
    };
    try {
        injector.getInstance(Key.get(setOfValueType));
        fail();
    } catch (ProvisionException expected) {
        assertContains(expected.getMessage(), "1) Set injection failed due to multiple elements comparing equal:", "\"ValueType(1,2)\"", "bound at " + module1.getClass().getName(), "\"ValueType(1,3)\"", "bound at " + module2.getClass().getName());
    }
    // But we can still visit the module!
    assertSetVisitor(Key.get(setOfValueType), Key.get(collectionOfProvidersOfValueType), valueType, setOf(module1, module2), MODULE, false, 0, instance(new ValueType(1, 2)), instance(new ValueType(1, 3)));
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) HashSet(java.util.HashSet) AbstractModule(com.google.inject.AbstractModule) Provider(com.google.inject.Provider) ProvisionException(com.google.inject.ProvisionException) TypeLiteral(com.google.inject.TypeLiteral) Injector(com.google.inject.Injector) Collection(java.util.Collection) Module(com.google.inject.Module) AbstractModule(com.google.inject.AbstractModule)

Example 5 with ProvisionException

use of com.google.inject.ProvisionException in project roboguice by roboguice.

the class MapBinderTest method testMapBinderMapForbidsNullValues.

public void testMapBinderMapForbidsNullValues() {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            MapBinder.newMapBinder(binder(), String.class, String.class).addBinding("null").toProvider(Providers.<String>of(null));
        }
    });
    try {
        injector.getInstance(Key.get(mapOfString));
        fail();
    } catch (ProvisionException expected) {
        assertContains(expected.getMessage(), "1) Map injection failed due to null value for key \"null\"");
    }
}
Also used : ProvisionException(com.google.inject.ProvisionException) Injector(com.google.inject.Injector) AbstractModule(com.google.inject.AbstractModule)

Aggregations

ProvisionException (com.google.inject.ProvisionException)57 Injector (com.google.inject.Injector)22 AbstractModule (com.google.inject.AbstractModule)20 Module (com.google.inject.Module)11 Provider (com.google.inject.Provider)9 OutOfScopeException (com.google.inject.OutOfScopeException)6 TypeLiteral (com.google.inject.TypeLiteral)6 Key (com.google.inject.Key)5 Message (com.google.inject.spi.Message)5 ImmutableList (com.google.common.collect.ImmutableList)4 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)4 OrmException (com.google.gwtorm.server.OrmException)4 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Provides (com.google.inject.Provides)3 Dependency (com.google.inject.spi.Dependency)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 Method (java.lang.reflect.Method)3 Path (java.nio.file.Path)3