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"));
}
}
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;
}
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.");
}
}
});
}
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;
}
}
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;
}
Aggregations