Example usage for org.apache.commons.lang3.reflect FieldUtils writeField

List of usage examples for org.apache.commons.lang3.reflect FieldUtils writeField

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect FieldUtils writeField.

Prototype

public static void writeField(final Object target, final String fieldName, final Object value,
        final boolean forceAccess) throws IllegalAccessException 

Source Link

Document

Writes a Field .

Usage

From source file:com.taobao.android.builder.tasks.awo.AwoPackageConfigAction.java

/**
 * ??task/*  w  w  w  .j av a2 s  .  co  m*/
 *
 * @param packageApp
 * @param fieldName
 * @param value
 */
private void setFieldValueByReflection(PackageApplication packageApp, String fieldName, Object value) {
    Field field = FieldUtils.getField(packageApp.getClass(), fieldName, true);
    if (null == field) {
        throw new StopExecutionException("The field with name:" + fieldName + " does not existed in class:"
                + packageApp.getClass().getName());
    }
    try {
        FieldUtils.writeField(field, packageApp, value, true);
    } catch (IllegalAccessException e) {
        throw new StopExecutionException(e.getMessage());
    }
}

From source file:com.holonplatform.core.internal.beans.DefaultBeanPropertySet.java

/**
 * Write the <code>property</code> value into given instance using given value, using BeanProperty configuration
 * write method or field, if available./* w  ww . j a v  a2 s . c  o m*/
 * @param property Property to write
 * @param value Value to write
 * @param instance Instance to write
 * @return Written value
 */
private static Object writeValue(BeanProperty<?> property, Object value, Object instance) {
    ObjectUtils.argumentNotNull(property, "Property must be not null");

    if (property.getWriteMethod().isPresent()) {
        try {
            property.getWriteMethod().get().invoke(instance, new Object[] {
                    getValueToWrite(property.getWriteMethod().get().getParameters()[0].getType(), value) });

            LOGGER.debug(() -> "BeanPropertySet: written property [" + property + "] value [" + value
                    + "] from instance [" + instance + "] using method [" + property.getWriteMethod() + "]");

        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new PropertyWriteException(property,
                    "Cannot write property [" + property + "] value of type ["
                            + ((value != null) ? value.getClass().getName() : "null") + "] on bean instance ["
                            + instance + "]",
                    e);
        }
    } else {
        Field field = property.getField()
                .orElseThrow(() -> new PropertyReadException(property,
                        "No write method and no accessible field available to write property [" + property
                                + "] on bean class [" + instance.getClass().getName() + "]"));
        try {
            FieldUtils.writeField(field, instance, getValueToWrite(field.getType(), value), true);

            LOGGER.debug(() -> "BeanPropertySet: read property [" + property + "] value [" + value
                    + "] from instance [" + instance + "] using field [" + field + "]");

        } catch (IllegalAccessException e) {
            throw new PropertyWriteException(property, e);
        }
    }

    return value;
}

From source file:com.thoughtworks.go.domain.AgentInstanceTest.java

@Test
public void shouldChangeAgentStatusToLostContactWhenLostAgentTimeoutHasExceeded()
        throws IllegalAccessException {
    AgentInstance agentInstance = AgentInstanceMother.missing();
    int agentConnectionTimeoutInMillis = systemEnvironment.getAgentConnectionTimeout() * 1000;
    Date timeLoggedForMissingStatus = new Date(new Date().getTime() - agentConnectionTimeoutInMillis);
    FieldUtils.writeField(agentInstance, "lastHeardTime", timeLoggedForMissingStatus, true);
    agentInstance.refresh();/* w w  w  .j a v  a  2s  . c  o m*/
    assertThat(agentInstance.getRuntimeStatus(), is(AgentRuntimeStatus.LostContact));
}

From source file:nl.xs4all.home.freekdb.b52reader.browsers.BackgroundBrowsersTest.java

@Test
public void testCloseAllBackgroundBrowsersFilled() throws IllegalAccessException {
    // todo: Use prepareMockObjects here as well?

    final JWebBrowser mockBrowser = Mockito.mock(JWebBrowser.class);

    // Initialize the private Container.component field to prevent a null pointer exception later.
    FieldUtils.writeField(mockBrowser, "component", new ArrayList<>(), true);

    Mockito.when(mockBrowser.navigate(Mockito.anyString())).thenAnswer(invocationOnMock -> {
        Awaitility.await().atLeast(10000, TimeUnit.MILLISECONDS)
                .until(() -> testCloseAllBackgroundBrowsersFinished);

        return false;
    });//from   ww w. j a  va 2  s  .  co m

    final BrowserFactory mockBrowserFactory = Mockito.mock(BrowserFactory.class);
    Mockito.when(mockBrowserFactory.createBrowser(Mockito.any(BrowserListener.class))).thenReturn(mockBrowser);

    final BackgroundBrowsers backgroundBrowsers = new BackgroundBrowsers(mockBrowserFactory, new JPanel());

    final Thread getHtmlThread = new Thread(() -> backgroundBrowsers.getHtmlContent("", 10000));
    getHtmlThread.start();

    Awaitility.await().atMost(10000, TimeUnit.MILLISECONDS).until(backgroundBrowsers::webBrowsersActive);

    assertTrue(backgroundBrowsers.webBrowsersActive());
    backgroundBrowsers.closeAllBackgroundBrowsers();
    assertFalse(backgroundBrowsers.webBrowsersActive());

    testCloseAllBackgroundBrowsersFinished = true;
}

From source file:nl.xs4all.home.freekdb.b52reader.browsers.BackgroundBrowsersTest.java

private void prepareMockObjects(String inProgressHtmlContent, String expectedHtmlContent)
        throws IllegalAccessException {
    mockJWebBrowser = Mockito.mock(JWebBrowser.class);
    Mockito.when(mockJWebBrowser.getHTMLContent()).thenReturn(inProgressHtmlContent, expectedHtmlContent);

    // Initialize the private Container.component field to prevent a null pointer exception later.
    FieldUtils.writeField(mockJWebBrowser, "component", new ArrayList<>(), true);

    mockBrowserFactory = Mockito.mock(BrowserFactory.class);

    Mockito.when(mockBrowserFactory.createBrowser(Mockito.any(BrowserListener.class)))
            .thenAnswer(invocationOnMock -> {
                browserListener = invocationOnMock.getArgument(0);

                return mockJWebBrowser;
            });//w ww  .j  a va2 s  .  c om
}

From source file:nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.java

@Before
public void setUp() throws IllegalAccessException {
    Set<String> urlsWithBrowsers = ImmutableSet.of("u2", "u4", "u6");

    mockFrame = Mockito.mock(JFrame.class);
    mockContentPane = new Container();
    mockManyBrowsersPanel = Mockito.mock(ManyBrowsersPanel.class);
    mockMainCallbacks = Mockito.mock(MainCallbacks.class);
    mockConfiguration = Mockito.mock(Configuration.class);

    Mockito.when(mockFrame.getContentPane()).thenReturn(mockContentPane);

    Mockito.doAnswer(invocationOnMock -> windowListener = invocationOnMock.getArgument(0)).when(mockFrame)
            .addWindowListener(Mockito.any(WindowListener.class));

    Mockito.when(mockManyBrowsersPanel.hasBrowserForUrl(Mockito.anyString()))
            .thenAnswer(invocationOnMock -> urlsWithBrowsers.contains(invocationOnMock.<String>getArgument(0)));

    // Initialize the private Container.component field to prevent a null pointer exception later.
    FieldUtils.writeField(mockManyBrowsersPanel, "component", new ArrayList<>(), true);

    Mockito.when(mockMainCallbacks.shutdownApplication(Mockito.anyInt(), Mockito.any()))
            .thenAnswer(invocationOnMock -> {
                shutdownApplicationWasCalled = true;

                return true;
            });// w w w.  j  a  v a 2  s. co  m

    Mockito.when(mockConfiguration.getBackgroundBrowserMaxCount()).thenReturn(2);
    Mockito.when(mockConfiguration.getBackgroundTimerInitialDelay()).thenReturn(2000);
    Mockito.when(mockConfiguration.getBackgroundTimerDelay()).thenReturn(600);
    Mockito.when(mockConfiguration.getFetchedValue()).thenReturn("fetched");
}

From source file:nl.xs4all.home.freekdb.b52reader.gui.ManyBrowsersPanelTest.java

private JWebBrowser createMockBrowser() throws IllegalAccessException {
    JWebBrowser mockWebBrowser = Mockito.mock(JWebBrowser.class);

    // Initialize the private Container.component field to prevent a null pointer exception later.
    FieldUtils.writeField(mockWebBrowser, "component", new ArrayList<>(), true);

    Mockito.when(mockWebBrowser.navigate(Mockito.anyString())).then(invocationOnMock -> {
        if (browserToListener.containsKey(mockWebBrowser)) {
            browserToListener.get(mockWebBrowser).pageLoaded(mockWebBrowser);
        }// w w w.ja  v  a  2s .  c om

        return null;
    });

    return mockWebBrowser;
}

From source file:org.apache.drill.exec.udf.dynamic.TestDynamicUDFSupport.java

private RemoteFunctionRegistry spyRemoteFunctionRegistry() throws IllegalAccessException {
    FunctionImplementationRegistry functionImplementationRegistry = getDrillbitContext()
            .getFunctionImplementationRegistry();
    RemoteFunctionRegistry remoteFunctionRegistry = functionImplementationRegistry.getRemoteFunctionRegistry();
    RemoteFunctionRegistry spy = spy(remoteFunctionRegistry);
    FieldUtils.writeField(functionImplementationRegistry, "remoteFunctionRegistry", spy, true);
    return spy;/*from  ww  w  .  j a v a2  s .  c om*/
}

From source file:org.apache.drill.exec.udf.dynamic.TestDynamicUDFSupport.java

private FunctionImplementationRegistry spyFunctionImplementationRegistry() throws IllegalAccessException {
    DrillbitContext drillbitContext = getDrillbitContext();
    FunctionImplementationRegistry spy = spy(drillbitContext.getFunctionImplementationRegistry());
    FieldUtils.writeField(drillbitContext, "functionRegistry", spy, true);
    return spy;/*from  ww  w .j  av  a  2s. com*/
}

From source file:org.apache.usergrid.persistence.model.util.EntityUtils.java

/**
 * Set the version into the entity//from   www . jav  a 2  s  .co  m
 */
public static void setVersion(Entity entity, UUID version) {

    try {
        FieldUtils.writeField(VERSION, entity, version, true);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Unable to set the field " + VERSION + " into the entity", e);
    }
}