Example usage for org.springframework.util ReflectionUtils findField

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

Introduction

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

Prototype

@Nullable
public static Field findField(Class<?> clazz, String name) 

Source Link

Document

Attempt to find a Field field on the supplied Class with the supplied name .

Usage

From source file:com.ciphertool.genetics.algorithms.ConcurrentMultigenerationalGeneticAlgorithmTest.java

@SuppressWarnings("unchecked")
@Test/*from  www .  j  a  v  a 2 s  .  com*/
public void testCrossover_SmallPopulation() {
    ConcurrentMultigenerationalGeneticAlgorithm concurrentMultigenerationalGeneticAlgorithm = new ConcurrentMultigenerationalGeneticAlgorithm();

    Population population = new Population();

    Chromosome chromosome = new MockKeylessChromosome();
    population.addIndividual(chromosome);
    concurrentMultigenerationalGeneticAlgorithm.setPopulation(population);

    CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class);

    Field crossoverAlgorithmField = ReflectionUtils.findField(ConcurrentMultigenerationalGeneticAlgorithm.class,
            "crossoverAlgorithm");
    ReflectionUtils.makeAccessible(crossoverAlgorithmField);
    ReflectionUtils.setField(crossoverAlgorithmField, concurrentMultigenerationalGeneticAlgorithm,
            crossoverAlgorithmMock);

    Field ineligibleForReproductionField = ReflectionUtils.findField(Population.class,
            "ineligibleForReproduction");
    ReflectionUtils.makeAccessible(ineligibleForReproductionField);
    List<Chromosome> ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);

    assertEquals(0, ineligibleForReproductionFromObject.size());

    int childrenProduced = concurrentMultigenerationalGeneticAlgorithm.crossover(10);

    ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);

    assertEquals(1, population.size());

    assertEquals(0, ineligibleForReproductionFromObject.size());

    assertEquals(0, childrenProduced);

    verifyZeroInteractions(crossoverAlgorithmMock);
}

From source file:com.ciphertool.genetics.PopulationTest.java

@Test
public void testSetCompareToKnownSolutionDefault() {
    Population population = new Population();

    Field compareToKnownSolutionField = ReflectionUtils.findField(Population.class, "compareToKnownSolution");
    ReflectionUtils.makeAccessible(compareToKnownSolutionField);
    Boolean compareToKnownSolutionFromObject = (Boolean) ReflectionUtils.getField(compareToKnownSolutionField,
            population);/*  w  w  w .ja v  a 2  s .  c  o m*/

    assertEquals(false, compareToKnownSolutionFromObject);
}

From source file:com.github.gavlyukovskiy.boot.jdbc.decorator.flexypool.FlexyPoolConfigurationTests.java

@SuppressWarnings("unchecked")
private <T extends ConnectionAcquiringStrategy> T findStrategy(FlexyPoolDataSource<?> flexyPoolDataSource,
        Class<T> factoryClass) {
    Field field = ReflectionUtils.findField(FlexyPoolDataSource.class, "connectionAcquiringStrategies");
    ReflectionUtils.makeAccessible(field);
    Set<ConnectionAcquiringStrategy> strategies = (Set<ConnectionAcquiringStrategy>) ReflectionUtils
            .getField(field, flexyPoolDataSource);
    return (T) strategies.stream().filter(factoryClass::isInstance).findFirst().orElse(null);
}

From source file:com.iisigroup.cap.utils.CapBeanUtil.java

public static <T> T setField(T entry, String fieldId, Object value) {
    Field field = ReflectionUtils.findField(entry.getClass(), fieldId);
    if (field != null) {
        String setter = new StringBuffer("set").append(String.valueOf(field.getName().charAt(0)).toUpperCase())
                .append(field.getName().substring(1)).toString();
        Method method = ReflectionUtils.findMethod(entry.getClass(), setter, new Class[] { field.getType() });
        if (method != null) {
            try {
                if (field.getType() != String.class && "".equals(value)) {
                    value = null;// w  ww.  j  av  a  2  s  .c  om
                } else if (field.getType() == BigDecimal.class) {
                    value = CapMath.getBigDecimal(String.valueOf(value));
                } else if (value instanceof String) {
                    if (field.getType() == java.util.Date.class || field.getType() == java.sql.Date.class) {
                        value = CapDate.parseDate((String) value);
                    } else if (field.getType() == Timestamp.class) {
                        value = CapDate.convertStringToTimestamp1((String) value);
                    }
                }
                if (value == null) {
                    method.invoke(entry, new Object[] { null });
                } else {
                    method.invoke(entry, ConvertUtils.convert(value, field.getType()));
                }
            } catch (Exception e) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(e.getMessage());
                } else {
                    LOGGER.warn(e.getMessage(), e);
                }
            }
        }
    }
    return entry;
}

From source file:fragment.web.TasksControllerTest.java

@Test
public void testActOnPendingAction() {
    Tenant tenant = tenantService.get("dfc84388-d44d-4d8e-9d6a-a62c1c16b7e4");
    BusinessTransaction bt = new TenantStateChangeTransaction();
    bt.setUuid(UUID.randomUUID().toString());
    bt.setWorkflowId("1e42822b-cad6-4dc0-bb77-99abb9395f1a");

    Field field = ReflectionUtils.findField(BusinessTransaction.class, "id");
    field.setAccessible(true);// w  w w .j  a v  a  2  s .  c om
    ReflectionUtils.setField(field, bt, 1l);

    Task task = new Task();
    task.setActorRole(authorityService.findByAuthority("ROLE_FINANCE_CRUD"));
    task.setCreatedAt(new Date());
    task.setState(com.citrix.cpbm.core.workflow.model.Task.State.PENDING);
    task.setTenant(tenant);
    task.setUser(tenant.getOwner());
    task.setUpdatedBy(getRootUser());
    task.setBusinessTransaction(bt);
    task.setType("FINANCE_APPROVAL");
    task.setDisplayMode(DisplayMode.POPUP);
    task = taskService.save(task);
    String memo = "Approved";
    String actedAction = tasksController.actOnApprovalTask(task.getUuid(), Task.State.SUCCESS.toString(), memo,
            request);
    Assert.assertEquals("ui.task.state.SUCCESS", actedAction);
}

From source file:org.terasoluna.gfw.web.token.transaction.TransactionTokenContextImplTest.java

@Test
public void TestCancelReservation01() throws IllegalArgumentException, IllegalAccessException {
    // setup parameters
    TransactionTokenInfo beginTransactionToken = new TransactionTokenInfo("testTokenAttribute1",
            TransactionTokenType.BEGIN);
    TransactionToken receivedToken = new TransactionToken("aaa");

    // setup target
    TransactionTokenContextImpl contextImpl = new TransactionTokenContextImpl(beginTransactionToken,
            receivedToken);/*ww  w.  ja  v  a 2s. c  om*/

    // setup up expected result
    ReserveCommand expectedCommand = ReserveCommand.CREATE_TOKEN;

    // run
    contextImpl.cancelReservation();

    // test
    Field field = ReflectionUtils.findField(TransactionTokenContextImpl.class, "defaultCommand");
    ReflectionUtils.makeAccessible(field);
    ReserveCommand resultCommand = (ReserveCommand) field.get(contextImpl);
    assertThat(resultCommand, is(expectedCommand));

}

From source file:com.ciphertool.zodiacengine.service.GeneticCipherSolutionServiceTest.java

@Test
public void testSetUp() throws IOException {
    GeneticCipherSolutionService geneticCipherSolutionService = new GeneticCipherSolutionService();

    GeneticAlgorithm geneticAlgorithm = mock(GeneticAlgorithm.class);
    geneticCipherSolutionService.setGeneticAlgorithm(geneticAlgorithm);

    Runtime runtimeMock = mock(Runtime.class);

    Field runtimeField = ReflectionUtils.findField(GeneticCipherSolutionService.class, "runtime");
    ReflectionUtils.makeAccessible(runtimeField);
    ReflectionUtils.setField(runtimeField, geneticCipherSolutionService, runtimeMock);

    String[] commandsBefore = { "command1", "command2" };
    geneticCipherSolutionService.setCommandsBefore(commandsBefore);

    GeneticAlgorithmStrategy geneticAlgorithmStrategy = new GeneticAlgorithmStrategy();
    geneticCipherSolutionService.setUp(geneticAlgorithmStrategy);

    verify(runtimeMock, times(1)).exec(eq("command1"));
    verify(runtimeMock, times(1)).exec(eq("command2"));
    verifyNoMoreInteractions(runtimeMock);

    verify(geneticAlgorithm, times(1)).setStrategy(same(geneticAlgorithmStrategy));
}

From source file:com.ciphertool.sentencebuilder.etl.importers.WordListImporterImplTest.java

@Test
public void testImportWord() {
    WordListImporterImpl wordListImporterImpl = new WordListImporterImpl();

    Field rowCountField = ReflectionUtils.findField(WordListImporterImpl.class, "rowCount");
    ReflectionUtils.makeAccessible(rowCountField);
    AtomicInteger rowCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowCountField,
            wordListImporterImpl);/*  ww  w  .  j  a  v  a 2 s  .co  m*/

    assertEquals(0, rowCountFromObject.intValue());

    WordDao wordDaoMock = mock(WordDao.class);
    when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true);

    wordListImporterImpl.setWordDao(wordDaoMock);
    wordListImporterImpl.setPersistenceBatchSize(3);

    List<Word> wordBatch = new ArrayList<Word>();

    Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN));
    wordListImporterImpl.importWord(word1, wordBatch);

    verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class));
    assertEquals(1, wordBatch.size());

    Word word2 = new Word(new WordId("elmer", PartOfSpeechType.NOUN));
    wordListImporterImpl.importWord(word2, wordBatch);

    verify(wordDaoMock, never()).insertBatch(anyListOf(Word.class));
    assertEquals(2, wordBatch.size());

    Word word3 = new Word(new WordId("belden", PartOfSpeechType.NOUN));
    wordListImporterImpl.importWord(word3, wordBatch);

    rowCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowCountField, wordListImporterImpl);

    assertEquals(3, rowCountFromObject.intValue());
    verify(wordDaoMock, times(1)).insertBatch(same(wordBatch));
    assertTrue(wordBatch.isEmpty());
}

From source file:org.terasoluna.gfw.web.token.transaction.TransactionTokenContextImplTest.java

@Test
public void TestCancelReservation02() throws IllegalArgumentException, IllegalAccessException {

    // setup parameters
    TransactionTokenInfo beginTransactionToken = new TransactionTokenInfo("testTokenAttribute1",
            TransactionTokenType.BEGIN);
    TransactionToken receivedToken = new TransactionToken("aaa", "key", "value");

    // setup up expected result
    ReserveCommand expectedCommand = ReserveCommand.UPDATE_TOKEN;

    // run/*w  w  w  . j  av a  2s  . c  o  m*/
    TransactionTokenContextImpl contextImpl = new TransactionTokenContextImpl(beginTransactionToken,
            receivedToken);

    contextImpl.cancelReservation();

    // test
    Field field = ReflectionUtils.findField(TransactionTokenContextImpl.class, "defaultCommand");
    ReflectionUtils.makeAccessible(field);
    ReserveCommand resultCommand = (ReserveCommand) field.get(contextImpl);
    assertThat(resultCommand, is(expectedCommand));
}

From source file:it.geosolutions.httpproxy.service.impl.ProxyConfigImpl.java

/**
 * Override this fields with a location properties
 * /*from w ww .  j  a v a  2s.com*/
 * @param location
 * 
 * @throws IOException if read properties throw an error
 */
private void overrideProperties(Resource location) throws IOException {
    Properties props = new Properties();
    props.load(location.getInputStream());
    Enumeration<Object> keys = props.keys();
    while (keys.hasMoreElements()) {
        try {
            String key = (String) keys.nextElement();
            if (key.startsWith(beanName + ".")) {
                String parameter = key.replace(beanName + ".", "");
                Field field = ReflectionUtils.findField(this.getClass(), parameter);
                ReflectionUtils.makeAccessible(field);
                ReflectionUtils.setField(field, this, props.getProperty(key));
                LOGGER.log(Level.INFO, "[override]: " + key + "=" + props.getProperty(key));
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error overriding the proxy configuration ", e);
        }
    }
}