Search in sources :

Example 16 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 17 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 18 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 19 with ProvisionException

use of com.google.inject.ProvisionException in project graylog2-server by Graylog2.

the class ServerBootstrap method startCommand.

@Override
protected void startCommand() {
    final AuditEventSender auditEventSender = injector.getInstance(AuditEventSender.class);
    final NodeId nodeId = injector.getInstance(NodeId.class);
    final String systemInformation = Tools.getSystemInformation();
    final Map<String, Object> auditEventContext = ImmutableMap.of("version", version.toString(), "java", systemInformation, "node_id", nodeId.toString());
    auditEventSender.success(AuditActor.system(nodeId), NODE_STARTUP_INITIATE, auditEventContext);
    final OS os = OS.getOs();
    LOG.info("Graylog {} {} starting up", commandName, version);
    LOG.info("JRE: {}", systemInformation);
    LOG.info("Deployment: {}", configuration.getInstallationSource());
    LOG.info("OS: {}", os.getPlatformName());
    LOG.info("Arch: {}", os.getArch());
    final ServerStatus serverStatus = injector.getInstance(ServerStatus.class);
    serverStatus.initialize();
    startNodeRegistration(injector);
    final ActivityWriter activityWriter;
    final ServiceManager serviceManager;
    try {
        activityWriter = injector.getInstance(ActivityWriter.class);
        serviceManager = injector.getInstance(ServiceManager.class);
    } catch (ProvisionException e) {
        LOG.error("Guice error", e);
        annotateProvisionException(e);
        auditEventSender.failure(AuditActor.system(nodeId), NODE_STARTUP_INITIATE, auditEventContext);
        System.exit(-1);
        return;
    } catch (Exception e) {
        LOG.error("Unexpected exception", e);
        auditEventSender.failure(AuditActor.system(nodeId), NODE_STARTUP_INITIATE, auditEventContext);
        System.exit(-1);
        return;
    }
    Runtime.getRuntime().addShutdownHook(new Thread(injector.getInstance(shutdownHook())));
    // propagate default size to input plugins
    MessageInput.setDefaultRecvBufferSize(configuration.getUdpRecvBufferSizes());
    // Start services.
    final ServiceManagerListener serviceManagerListener = injector.getInstance(ServiceManagerListener.class);
    serviceManager.addListener(serviceManagerListener);
    try {
        serviceManager.startAsync().awaitHealthy();
    } catch (Exception e) {
        try {
            serviceManager.stopAsync().awaitStopped(configuration.getShutdownTimeout(), TimeUnit.MILLISECONDS);
        } catch (TimeoutException timeoutException) {
            LOG.error("Unable to shutdown properly on time. {}", serviceManager.servicesByState());
        }
        LOG.error("Graylog startup failed. Exiting. Exception was:", e);
        auditEventSender.failure(AuditActor.system(nodeId), NODE_STARTUP_INITIATE, auditEventContext);
        System.exit(-1);
    }
    LOG.info("Services started, startup times in ms: {}", serviceManager.startupTimes());
    activityWriter.write(new Activity("Started up.", Main.class));
    LOG.info("Graylog " + commandName + " up and running.");
    auditEventSender.success(AuditActor.system(nodeId), NODE_STARTUP_COMPLETE, auditEventContext);
    // Block forever.
    try {
        Thread.currentThread().join();
    } catch (InterruptedException e) {
        return;
    }
}
Also used : OS(org.jsoftbiz.utils.OS) Activity(org.graylog2.shared.system.activities.Activity) TimeoutException(java.util.concurrent.TimeoutException) ProvisionException(com.google.inject.ProvisionException) ProvisionException(com.google.inject.ProvisionException) AuditEventSender(org.graylog2.audit.AuditEventSender) ServiceManager(com.google.common.util.concurrent.ServiceManager) ServerStatus(org.graylog2.plugin.ServerStatus) NodeId(org.graylog2.plugin.system.NodeId) ServiceManagerListener(org.graylog2.shared.initializers.ServiceManagerListener) ActivityWriter(org.graylog2.shared.system.activities.ActivityWriter) TimeoutException(java.util.concurrent.TimeoutException)

Example 20 with ProvisionException

use of com.google.inject.ProvisionException in project gerrit by GerritCodeReview.

the class RequestScopedReviewDbProvider method get.

@SuppressWarnings("resource")
@Override
public ReviewDb get() {
    if (db == null) {
        ReviewDb c;
        try {
            c = schema.open();
        } catch (OrmException e) {
            throw new ProvisionException("Cannot open ReviewDb", e);
        }
        try {
            cleanup.get().add(() -> {
                c.close();
                db = null;
            });
        } catch (Throwable e) {
            c.close();
            throw new ProvisionException("Cannot defer cleanup of ReviewDb", e);
        }
        db = c;
    }
    return db;
}
Also used : ProvisionException(com.google.inject.ProvisionException) OrmException(com.google.gwtorm.server.OrmException) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

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