Example usage for org.springframework.util ReflectionUtils getField

List of usage examples for org.springframework.util ReflectionUtils getField

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils getField.

Prototype

@Nullable
public static Object getField(Field field, @Nullable Object target) 

Source Link

Document

Get the field represented by the supplied Field field object on the specified Object target object .

Usage

From source file:fr.paris.lutece.plugins.suggest.utils.SuggestUtils.java

/**
 * Depopulate the suggest into a map of key - value
 * @param suggest the suggest// w ww .j a  va 2  s  .  com
 * @return a map of key - value
 */
public static Map<String, Object> depopulate(Suggest suggest) {
    Map<String, Object> mapAttributes = new HashMap<String, Object>();

    for (java.lang.reflect.Field field : Suggest.class.getDeclaredFields()) {
        SuggestAttribute attribute = field.getAnnotation(SuggestAttribute.class);

        if (attribute != null) {
            String strAttributeKey = attribute.value();

            try {
                field.setAccessible(true);

                Object attributeValue = ReflectionUtils.getField(field, suggest);
                mapAttributes.put(strAttributeKey, attributeValue);
            } catch (SecurityException e) {
                AppLogService.error(e);
            }
        }
    }

    return mapAttributes;
}

From source file:com.opendesign.utils.CmnUtil.java

/**
 * client to server: html enter  /*from w w w .  jav  a 2  s  .  c o  m*/
 * @param vo
 * @param fieldName
 */
public static void handleHtmlEnterRN2BR(Object vo, String fieldName) {
    if (vo == null) {
        return;
    }

    Class<?> clazz = vo.getClass();
    // 
    Field aField = ReflectionUtils.findField(clazz, fieldName);
    if (aField != null) {
        ReflectionUtils.makeAccessible(aField);
        String contents = (String) ReflectionUtils.getField(aField, vo);
        contents = handleHtmlEnterRN2BR(contents);
        ReflectionUtils.setField(aField, vo, contents);
    }
}

From source file:com.opendesign.utils.CmnUtil.java

/**
 * server to client: html enter  /*from   w w  w. j  a  v a 2s.  com*/
 * @param vo
 * @param fieldName
 */
public static void handleHtmlEnterBR2RN(Object vo, String fieldName) {
    if (vo == null) {
        return;
    }

    Class<?> clazz = vo.getClass();
    // 
    Field aField = ReflectionUtils.findField(clazz, fieldName);
    if (aField != null) {
        ReflectionUtils.makeAccessible(aField);
        String contents = (String) ReflectionUtils.getField(aField, vo);
        contents = handleHtmlEnterBR2RN(contents);
        ReflectionUtils.setField(aField, vo, contents);
    }
}

From source file:de.hybris.platform.core.TenantRestartTest.java

private List<InvalidationListener> getListenersViaReflection(final InvalidationTopic topic) {
    final Field listeners = ReflectionUtils.findField(InvalidationTopic.class, "listeners");
    Assertions.assertThat(listeners).isNotNull();
    listeners.setAccessible(true);/*from  w  w w  .j av  a 2 s  .co  m*/
    return (List<InvalidationListener>) ReflectionUtils.getField(listeners, topic);
}

From source file:hello.MetricsActivator.java

private static Object getField(Object target, String name) {
    Assert.notNull(target, "Target object must not be null");
    Field field = ReflectionUtils.findField(target.getClass(), name);
    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + name + "] on target [" + target + "]");
    }/*from  ww w  .  j a  v a  2  s. c  o m*/

    if (logger.isDebugEnabled()) {
        logger.debug("Getting field [" + name + "] from target [" + target + "]");
    }
    ReflectionUtils.makeAccessible(field);
    return ReflectionUtils.getField(field, target);
}

From source file:org.alfresco.repo.invitation.AbstractInvitationServiceImplTest.java

/**
 * Test nominated user - new user//from ww  w.j a v  a  2 s  . c o m
 * 
 * @throws Exception
 */
public void testNominatedInvitationNewUser() throws Exception {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, -1);
    Date startDate = calendar.getTime();

    String inviteeFirstName = PERSON_FIRSTNAME;
    String inviteeLastName = PERSON_LASTNAME;
    String inviteeEmail = "123@alfrescotesting.com";
    String inviteeUserName = null;
    Invitation.ResourceType resourceType = Invitation.ResourceType.WEB_SITE;
    String resourceName = SITE_SHORT_NAME_INVITE;
    String inviteeRole = SiteModel.SITE_COLLABORATOR;
    String serverPath = "wibble";
    String acceptUrl = "froob";
    String rejectUrl = "marshmallow";

    this.authenticationComponent.setCurrentUser(USER_MANAGER);

    NominatedInvitation nominatedInvitation = invitationService.inviteNominated(inviteeFirstName,
            inviteeLastName, inviteeEmail, resourceType, resourceName, inviteeRole, serverPath, acceptUrl,
            rejectUrl);

    assertNotNull("nominated invitation is null", nominatedInvitation);
    String inviteId = nominatedInvitation.getInviteId();
    assertEquals("first name wrong", inviteeFirstName, nominatedInvitation.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, nominatedInvitation.getInviteeLastName());
    assertEquals("email name wrong", inviteeEmail, nominatedInvitation.getInviteeEmail());

    // Generated User Name should be returned
    inviteeUserName = nominatedInvitation.getInviteeUserName();
    assertNotNull("generated user name is null", inviteeUserName);
    // sentInviteDate should be set to today
    {
        Date sentDate = nominatedInvitation.getSentInviteDate();
        assertTrue("sentDate wrong - too early. Start Date: " + startDate + "\nSent Date: " + sentDate,
                sentDate.after(startDate));
        assertTrue("sentDate wrong - too lateStart Date: " + startDate + "\nSent Date: " + sentDate,
                sentDate.before(new Date(new Date().getTime() + 1)));
    }

    assertEquals("resource type name wrong", resourceType, nominatedInvitation.getResourceType());
    assertEquals("resource name wrong", resourceName, nominatedInvitation.getResourceName());
    assertEquals("role  name wrong", inviteeRole, nominatedInvitation.getRoleName());
    assertEquals("server path wrong", serverPath, nominatedInvitation.getServerPath());
    assertEquals("accept URL wrong", acceptUrl, nominatedInvitation.getAcceptUrl());
    assertEquals("reject URL wrong", rejectUrl, nominatedInvitation.getRejectUrl());

    /**
     * Now we have an invitation get it and check the details have been
     * returned correctly.
     */
    {
        NominatedInvitation invitation = (NominatedInvitation) invitationService.getInvitation(inviteId);

        assertNotNull("invitation is null", invitation);
        assertEquals("invite id wrong", inviteId, invitation.getInviteId());
        assertEquals("first name wrong", inviteeFirstName, invitation.getInviteeFirstName());
        assertEquals("last name wrong", inviteeLastName, invitation.getInviteeLastName());
        assertEquals("user name wrong", inviteeUserName, invitation.getInviteeUserName());
        assertEquals("resource type name wrong", resourceType, invitation.getResourceType());
        assertEquals("resource name wrong", resourceName, invitation.getResourceName());
        assertEquals("role  name wrong", inviteeRole, invitation.getRoleName());
        assertEquals("server path wrong", serverPath, invitation.getServerPath());
        assertEquals("accept URL wrong", acceptUrl, invitation.getAcceptUrl());
        assertEquals("reject URL wrong", rejectUrl, invitation.getRejectUrl());

        Date sentDate = invitation.getSentInviteDate();
        // sentInviteDate should be set to today
        assertTrue("sentDate wrong too early", sentDate.after(startDate));
        assertTrue("sentDate wrong - too late", sentDate.before(new Date(new Date().getTime() + 1)));
    }

    /**
     * Check the email itself, and check it
     *  is as we would expect it to be
     */
    {
        MimeMessage msg = mailService.retrieveLastTestMessage();

        assertEquals(1, msg.getAllRecipients().length);
        assertEquals(inviteeEmail, msg.getAllRecipients()[0].toString());

        assertEquals(1, msg.getFrom().length);
        assertEquals(USER_MANAGER + "@alfrescotesting.com", msg.getFrom()[0].toString());

        // Hasn't been sent, so no sent or received date
        assertNull("Not been sent yet", msg.getSentDate());
        assertNull("Not been sent yet", msg.getReceivedDate());

        // TODO - check some more details of the email
        assertTrue((msg.getSubject().indexOf("You have been invited to join the") != -1));
    }

    /**
     * Search for the new invitation
     */
    List<Invitation> invitations = invitationService.listPendingInvitationsForResource(resourceType,
            resourceName);
    assertTrue("invitations is empty", !invitations.isEmpty());

    NominatedInvitation firstInvite = (NominatedInvitation) invitations.get(0);
    assertEquals("invite id wrong", inviteId, firstInvite.getInviteId());
    assertEquals("first name wrong", inviteeFirstName, firstInvite.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, firstInvite.getInviteeLastName());
    assertEquals("user name wrong", inviteeUserName, firstInvite.getInviteeUserName());

    /**
     * Now accept the invitation
     */
    NominatedInvitation acceptedInvitation = (NominatedInvitation) invitationService
            .accept(firstInvite.getInviteId(), firstInvite.getTicket());
    assertEquals("invite id wrong", firstInvite.getInviteId(), acceptedInvitation.getInviteId());
    assertEquals("first name wrong", inviteeFirstName, acceptedInvitation.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, acceptedInvitation.getInviteeLastName());
    assertEquals("user name wrong", inviteeUserName, acceptedInvitation.getInviteeUserName());

    List<Invitation> it4 = invitationService.listPendingInvitationsForResource(resourceType, resourceName);
    assertTrue("invitations is not empty", it4.isEmpty());

    /**
     * Now get the invitation that we accepted
     */
    NominatedInvitation acceptedInvitation2 = (NominatedInvitation) invitationService
            .getInvitation(firstInvite.getInviteId());
    assertNotNull("get after accept does not return", acceptedInvitation2);

    /**
     * Now verify access control list
     */
    String roleName = siteService.getMembersRole(resourceName, inviteeUserName);
    assertEquals("role name wrong", roleName, inviteeRole);
    siteService.removeMembership(resourceName, inviteeUserName);

    /**
     * Check that system generated invitations can work as well
     */
    {
        Field faf = mailService.getClass().getDeclaredField("fromAddress");
        faf.setAccessible(true);
        String defaultFromAddress = (String) ReflectionUtils.getField(faf, mailService);

        AuthenticationUtil.setFullyAuthenticatedUser(USER_NOEMAIL);

        // Check invitiation
        NominatedInvitation nominatedInvitation2 = invitationService.inviteNominated(inviteeFirstName,
                inviteeLastName, USER_TWO_EMAIL, resourceType, resourceName, inviteeRole, serverPath, acceptUrl,
                rejectUrl);

        assertNotNull("nominated invitation is null", nominatedInvitation2);
        inviteId = nominatedInvitation.getInviteId();
        assertEquals("first name wrong", inviteeFirstName, nominatedInvitation2.getInviteeFirstName());
        assertEquals("last name wrong", inviteeLastName, nominatedInvitation2.getInviteeLastName());
        assertEquals("email name wrong", USER_TWO_EMAIL, nominatedInvitation2.getInviteeEmail());

        // Check the email
        MimeMessage msg = mailService.retrieveLastTestMessage();

        assertEquals(1, msg.getAllRecipients().length);
        assertEquals(USER_TWO_EMAIL, msg.getAllRecipients()[0].toString());

        assertEquals(1, msg.getFrom().length);
        assertEquals(defaultFromAddress, msg.getFrom()[0].toString());
    }
}

From source file:org.alfresco.util.test.junitrules.TemporaryMockOverride.java

public void setTemporaryField(Object objectContainingField, String fieldName, Object fieldValue) {
    if (log.isDebugEnabled()) {
        log.debug("Overriding field '" + fieldName + "' on object " + objectContainingField + " to new value '"
                + fieldValue + "'");
    }/* w ww . j a  v  a 2 s .  c o m*/

    // Extract the pristine value of the field we're going to mock.
    Field f = ReflectionUtils.findField(objectContainingField.getClass(), fieldName);

    if (f == null) {
        final String msg = "Object of type '" + objectContainingField.getClass().getSimpleName()
                + "' has no field named '" + fieldName + "'";
        if (log.isDebugEnabled()) {
            log.debug(msg);
        }
        throw new IllegalArgumentException(msg);
    }

    ReflectionUtils.makeAccessible(f);
    Object pristineValue = ReflectionUtils.getField(f, objectContainingField);

    // and add it to the list.
    pristineFieldValues.add(new FieldValueOverride(objectContainingField, fieldName, pristineValue));

    // and set it on the object
    ReflectionUtils.setField(f, objectContainingField, fieldValue);
}

From source file:org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleReferenceAnnotationBeanPostProcessor.java

private <T> T getFieldValue(Object object, String fieldName, Class<T> fieldType) {

    Field field = ReflectionUtils.findField(object.getClass(), fieldName, fieldType);

    ReflectionUtils.makeAccessible(field);

    return (T) ReflectionUtils.getField(field, object);

}

From source file:org.artifactory.util.HttpClientUtils.java

private static RequestConfig getDefaultConfig(HttpClient client) {
    if (client == null) {
        return null;
    }//from w w w  .jav a2 s . c  o  m
    try {
        HttpClient httpClient = extractCloseableHttpClient(client);
        Field requestConfigField = httpClient.getClass().getDeclaredField("defaultConfig");
        requestConfigField.setAccessible(true);
        return (RequestConfig) ReflectionUtils.getField(requestConfigField, httpClient);
    } catch (NoSuchFieldException e) {
        throw new IllegalStateException("Failed to get default request config", e);
    }
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageMetaInfo.java

@SuppressWarnings("rawtypes")
public GroovyPageMetaInfo(Class<?> pageClass) {
    this();/*from   w w  w . j a  v a  2 s . co  m*/
    precompiledMode = true;
    this.pageClass = pageClass;
    contentType = (String) ReflectionUtils
            .getField(ReflectionUtils.findField(pageClass, GroovyPageParser.CONSTANT_NAME_CONTENT_TYPE), null);
    jspTags = (Map) ReflectionUtils
            .getField(ReflectionUtils.findField(pageClass, GroovyPageParser.CONSTANT_NAME_JSP_TAGS), null);
    lastModified = (Long) ReflectionUtils
            .getField(ReflectionUtils.findField(pageClass, GroovyPageParser.CONSTANT_NAME_LAST_MODIFIED), null);
    expressionCodecName = (String) ReflectionUtils.getField(
            ReflectionUtils.findField(pageClass, GroovyPageParser.CONSTANT_NAME_EXPRESSION_CODEC), null);
    staticCodecName = (String) ReflectionUtils
            .getField(ReflectionUtils.findField(pageClass, GroovyPageParser.CONSTANT_NAME_STATIC_CODEC), null);
    outCodecName = (String) ReflectionUtils
            .getField(ReflectionUtils.findField(pageClass, GroovyPageParser.CONSTANT_NAME_OUT_CODEC), null);
    taglibCodecName = (String) ReflectionUtils
            .getField(ReflectionUtils.findField(pageClass, GroovyPageParser.CONSTANT_NAME_TAGLIB_CODEC), null);

    try {
        readHtmlData();
    } catch (IOException e) {
        throw new RuntimeException("Problem reading html data for page class " + pageClass, e);
    }
}