use of com.google.inject.spi.Message 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.spi.Message in project guice by google.
the class BoundFieldModule method throwBoundFieldException.
private void throwBoundFieldException(Field field, String format, Object... args) {
Preconditions.checkNotNull(binder);
String source = String.format("%s field %s", field.getDeclaringClass().getName(), field.getName());
throw new BoundFieldException(new Message(source, String.format(format, args)));
}
use of com.google.inject.spi.Message in project guice by google.
the class Errors method format.
/** Returns the formatted message for an exception with the specified messages. */
public static String format(String heading, Collection<Message> errorMessages) {
Formatter fmt = new Formatter().format(heading).format(":%n%n");
int index = 1;
boolean displayCauses = getOnlyCause(errorMessages) == null;
Map<Equivalence.Wrapper<Throwable>, Integer> causes = Maps.newHashMap();
for (Message errorMessage : errorMessages) {
int thisIdx = index++;
fmt.format("%s) %s%n", thisIdx, errorMessage.getMessage());
List<Object> dependencies = errorMessage.getSources();
for (int i = dependencies.size() - 1; i >= 0; i--) {
Object source = dependencies.get(i);
formatSource(fmt, source);
}
Throwable cause = errorMessage.getCause();
if (displayCauses && cause != null) {
Equivalence.Wrapper<Throwable> causeEquivalence = ThrowableEquivalence.INSTANCE.wrap(cause);
if (!causes.containsKey(causeEquivalence)) {
causes.put(causeEquivalence, thisIdx);
fmt.format("Caused by: %s", Throwables.getStackTraceAsString(cause));
} else {
int causeIdx = causes.get(causeEquivalence);
fmt.format("Caused by: %s (same stack trace as error #%s)", cause.getClass().getName(), causeIdx);
}
}
fmt.format("%n");
}
if (errorMessages.size() == 1) {
fmt.format("1 error");
} else {
fmt.format("%s errors", errorMessages.size());
}
return fmt.toString();
}
use of com.google.inject.spi.Message in project guice by google.
the class Errors method getOnlyCause.
/**
* Returns the cause throwable if there is exactly one cause in {@code messages}. If there are
* zero or multiple messages with causes, null is returned.
*/
public static Throwable getOnlyCause(Collection<Message> messages) {
Throwable onlyCause = null;
for (Message message : messages) {
Throwable messageCause = message.getCause();
if (messageCause == null) {
continue;
}
if (onlyCause != null && !ThrowableEquivalence.INSTANCE.equivalent(onlyCause, messageCause)) {
return null;
}
onlyCause = messageCause;
}
return onlyCause;
}
use of com.google.inject.spi.Message in project shiro by apache.
the class BeanTypeListenerTest method testPropertySetting.
@Test
public void testPropertySetting() throws Exception {
IMocksControl control = createControl();
TypeEncounter<SomeInjectableBean> encounter = control.createMock(TypeEncounter.class);
Provider<Injector> injectorProvider = control.createMock(Provider.class);
Injector injector = control.createMock(Injector.class);
expect(encounter.getProvider(Injector.class)).andReturn(injectorProvider);
expect(injectorProvider.get()).andReturn(injector).anyTimes();
Capture<MembersInjector<SomeInjectableBean>> capture = new Capture<MembersInjector<SomeInjectableBean>>();
encounter.register(and(anyObject(MembersInjector.class), capture(capture)));
SecurityManager securityManager = control.createMock(SecurityManager.class);
String property = "myPropertyValue";
expect(injector.getInstance(Key.get(SecurityManager.class))).andReturn(securityManager);
expect(injector.getInstance(Key.get(String.class, Names.named("shiro.myProperty")))).andReturn(property);
expect(injector.getInstance(Key.get(String.class, Names.named("shiro.unavailableProperty")))).andThrow(new ConfigurationException(Collections.singleton(new Message("Not Available!"))));
expect((Map) injector.getInstance(BeanTypeListener.MAP_KEY)).andReturn(Collections.EMPTY_MAP).anyTimes();
control.replay();
BeanTypeListener underTest = new BeanTypeListener();
underTest.hear(TypeLiteral.get(SomeInjectableBean.class), encounter);
SomeInjectableBean bean = new SomeInjectableBean();
capture.getValue().injectMembers(bean);
assertSame(securityManager, bean.securityManager);
assertSame(property, bean.myProperty);
assertNull(bean.unavailableProperty);
control.verify();
}
Aggregations