Search in sources :

Example 1 with Message

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;
}
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 2 with Message

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)));
}
Also used : Message(com.google.inject.spi.Message)

Example 3 with Message

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();
}
Also used : Message(com.google.inject.spi.Message) Equivalence(com.google.common.base.Equivalence) Formatter(java.util.Formatter) InjectionPoint(com.google.inject.spi.InjectionPoint)

Example 4 with Message

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;
}
Also used : Message(com.google.inject.spi.Message)

Example 5 with Message

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();
}
Also used : Message(com.google.inject.spi.Message) Capture(org.easymock.Capture) IMocksControl(org.easymock.IMocksControl) Test(org.junit.Test)

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