Search in sources :

Example 1 with Field

use of java.lang.reflect.Field in project che by eclipse.

the class RecipeServiceTest method setUpUriInfo.

@BeforeMethod
public void setUpUriInfo() throws NoSuchFieldException, IllegalAccessException {
    when(uriInfo.getBaseUriBuilder()).thenReturn(new UriBuilderImpl());
    final Field uriField = service.getClass().getSuperclass().getDeclaredField("uriInfo");
    uriField.setAccessible(true);
    uriField.set(service, uriInfo);
}
Also used : Field(java.lang.reflect.Field) UriBuilderImpl(org.everrest.core.impl.uri.UriBuilderImpl) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 2 with Field

use of java.lang.reflect.Field in project jetty.project by eclipse.

the class TestResourceAnnotations method testResourceAnnotations.

@Test
public void testResourceAnnotations() throws Exception {
    new org.eclipse.jetty.plus.jndi.EnvEntry(server, "resA", objA, false);
    new org.eclipse.jetty.plus.jndi.EnvEntry(server, "resB", objB, false);
    AnnotationIntrospector parser = new AnnotationIntrospector();
    ResourceAnnotationHandler handler = new ResourceAnnotationHandler(wac);
    parser.registerHandler(handler);
    parser.introspect(ResourceA.class);
    parser.introspect(ResourceB.class);
    //processing classA should give us these jndi name bindings:
    // java:comp/env/myf
    // java:comp/env/org.eclipse.jetty.annotations.resources.ResourceA/g
    // java:comp/env/mye
    // java:comp/env/org.eclipse.jetty.annotations.resources.ResourceA/h
    // java:comp/env/resA
    // java:comp/env/org.eclipse.jetty.annotations.resources.ResourceB/f
    // java:comp/env/org.eclipse.jetty.annotations.resources.ResourceA/n
    //
    assertEquals(objB, env.lookup("myf"));
    assertEquals(objA, env.lookup("mye"));
    assertEquals(objA, env.lookup("resA"));
    assertEquals(objA, env.lookup("org.eclipse.jetty.annotations.resources.ResourceA/g"));
    assertEquals(objA, env.lookup("org.eclipse.jetty.annotations.resources.ResourceA/h"));
    assertEquals(objB, env.lookup("org.eclipse.jetty.annotations.resources.ResourceB/f"));
    assertEquals(objB, env.lookup("org.eclipse.jetty.annotations.resources.ResourceA/n"));
    //we should have Injections
    assertNotNull(injections);
    List<Injection> resBInjections = injections.getInjections(ResourceB.class.getCanonicalName());
    assertNotNull(resBInjections);
    //only 1 field injection because the other has no Resource mapping
    assertEquals(1, resBInjections.size());
    Injection fi = resBInjections.get(0);
    assertEquals("f", fi.getTarget().getName());
    //3 method injections on class ResourceA, 4 field injections
    List<Injection> resAInjections = injections.getInjections(ResourceA.class.getCanonicalName());
    assertNotNull(resAInjections);
    assertEquals(7, resAInjections.size());
    int fieldCount = 0;
    int methodCount = 0;
    for (Injection x : resAInjections) {
        if (x.isField())
            fieldCount++;
        else
            methodCount++;
    }
    assertEquals(4, fieldCount);
    assertEquals(3, methodCount);
    //test injection
    ResourceB binst = new ResourceB();
    injections.inject(binst);
    //check injected values
    Field f = ResourceB.class.getDeclaredField("f");
    f.setAccessible(true);
    assertEquals(objB, f.get(binst));
    //@Resource(mappedName="resA") //test the default naming scheme but using a mapped name from the environment
    f = ResourceA.class.getDeclaredField("g");
    f.setAccessible(true);
    assertEquals(objA, f.get(binst));
    //@Resource(name="resA") //test using the given name as the name from the environment
    f = ResourceA.class.getDeclaredField("j");
    f.setAccessible(true);
    assertEquals(objA, f.get(binst));
    //@Resource(mappedName="resB") //test using the default name on an inherited field
    f = ResourceA.class.getDeclaredField("n");
    f.setAccessible(true);
    assertEquals(objB, f.get(binst));
}
Also used : Field(java.lang.reflect.Field) AnnotationIntrospector(org.eclipse.jetty.annotations.AnnotationIntrospector) ResourceAnnotationHandler(org.eclipse.jetty.annotations.ResourceAnnotationHandler) Injection(org.eclipse.jetty.plus.annotation.Injection) Test(org.junit.Test)

Example 3 with Field

use of java.lang.reflect.Field in project buck by facebook.

the class Reflect method setField.

static void setField(Object object, Class<?> clazz, String fieldName, Object fieldValue) throws NoSuchFieldException, IllegalAccessException {
    Field field = clazz.getDeclaredField(fieldName);
    field.setAccessible(true);
    field.set(object, fieldValue);
}
Also used : Field(java.lang.reflect.Field)

Example 4 with Field

use of java.lang.reflect.Field 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 5 with Field

use of java.lang.reflect.Field in project elastic-job by dangdangdotcom.

the class AopTargetUtils method getTargetObject.

private static Object getTargetObject(final Object object) {
    try {
        Field advised = object.getClass().getDeclaredField("advised");
        advised.setAccessible(true);
        return ((AdvisedSupport) advised.get(object)).getTargetSource().getTarget();
    // CHECKSTYLE:OFF
    } catch (final Exception ex) {
        // CHECKSTYLE:ON
        throw new JobSystemException(ex);
    }
}
Also used : Field(java.lang.reflect.Field) JobSystemException(com.dangdang.ddframe.job.exception.JobSystemException) JobSystemException(com.dangdang.ddframe.job.exception.JobSystemException)

Aggregations

Field (java.lang.reflect.Field)10402 Test (org.junit.Test)1216 Method (java.lang.reflect.Method)1201 ArrayList (java.util.ArrayList)910 HashMap (java.util.HashMap)680 Map (java.util.Map)656 IOException (java.io.IOException)585 List (java.util.List)405 InvocationTargetException (java.lang.reflect.InvocationTargetException)378 HashSet (java.util.HashSet)258 File (java.io.File)240 Test (org.testng.annotations.Test)197 Annotation (java.lang.annotation.Annotation)168 Collection (java.util.Collection)167 Type (java.lang.reflect.Type)153 Before (org.junit.Before)151 Test (org.junit.jupiter.api.Test)146 Set (java.util.Set)142 ParameterizedType (java.lang.reflect.ParameterizedType)137 LinkedHashMap (java.util.LinkedHashMap)135