Example usage for org.springframework.util ReflectionUtils setField

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

Introduction

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

Prototype

public static void setField(Field field, @Nullable Object target, @Nullable Object value) 

Source Link

Document

Set the field represented by the supplied Field field object on the specified Object target object to the specified value .

Usage

From source file:com.ciphertool.zodiacengine.fitness.AbstractSolutionEvaluatorBaseTest.java

@Test
public void testCalculateAdjacentMatches_NullPlaintextCharacters() {
    ConcreteSolutionEvaluatorBase abstractSolutionEvaluatorBase = new ConcreteSolutionEvaluatorBase();

    Field logField = ReflectionUtils.findField(ConcreteSolutionEvaluatorBase.class, "log");
    Logger mockLogger = mock(Logger.class);
    ReflectionUtils.makeAccessible(logField);
    ReflectionUtils.setField(logField, abstractSolutionEvaluatorBase, mockLogger);

    abstractSolutionEvaluatorBase.calculateAdjacentMatches(null);

    verify(mockLogger, times(1)).warn(/* www  . j  a  va 2  s  .  c  o  m*/
            "Attempted to calculate adjacent matches, but the List of plaintextCharacters was null or empty.  Returning -1.");
}

From source file:org.bahmni.test.builder.DrugOrderBuilder.java

public DrugOrderBuilder withOrderNumber(String orderNum) {
    java.lang.reflect.Field orderNumberField = ReflectionUtils.findField(DrugOrder.class, "orderNumber");
    orderNumberField.setAccessible(true);
    ReflectionUtils.setField(orderNumberField, order, orderNum);
    return this;
}

From source file:org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java

public T getHashKeyPropotypeEntityForHashKey(Object hashKey) {

    try {/*from   w w  w.  ja  v a 2s  .  c  o m*/
        T entity = getJavaType().newInstance();
        if (hashKeySetterMethod != null) {
            ReflectionUtils.invokeMethod(hashKeySetterMethod, entity, hashKey);
        } else {
            ReflectionUtils.setField(hashKeyField, entity, hashKey);
        }

        return entity;
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:ru.anr.base.BaseParent.java

/**
 * Injection of a private field into the given object. Of course, we are
 * against such a technique :-). But still in tests this is a very
 * convenient approach.//from w  w w.  j  a v  a2 s . c  o m
 *
 * @param target
 *            The target object
 * @param fieldName
 *            The name of the field to inject
 * @param field
 *            The field's value
 */
public static void inject(Object target, String fieldName, Object field) {

    Field f = ReflectionUtils.findField(target.getClass(), fieldName);
    Assert.notNull(f);

    ReflectionUtils.makeAccessible(f);
    ReflectionUtils.setField(f, target, field);
}

From source file:edu.mayo.cts2.framework.webapp.rest.controller.AbstractMessageWrappingController.java

private void setDirectoryEntries(Directory directory, List<?> entries) {
    try {/*from w ww.j ava  2  s  .c o  m*/
        final Field field = ReflectionUtils.findField(directory.getClass(), "_entryList");

        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                field.setAccessible(true);

                return null;
            }
        });

        ReflectionUtils.setField(field, directory, entries);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.cleverbus.test.AbstractTest.java

/**
 * Sets value of private field./*from   w ww . j ava2s .com*/
 *
 * @param target the target object
 * @param name   the field name
 * @param value  the value for setting to the field
 */
public static void setPrivateField(Object target, String name, Object value) {
    Field countField = ReflectionUtils.findField(target.getClass(), name);
    ReflectionUtils.makeAccessible(countField);
    ReflectionUtils.setField(countField, target, value);
}

From source file:com.ciphertool.zodiacengine.fitness.AbstractSolutionEvaluatorBaseTest.java

@Test
public void testClearHasMatchValues() {
    ConcreteSolutionEvaluatorBase abstractSolutionEvaluatorBase = new ConcreteSolutionEvaluatorBase();

    Field logField = ReflectionUtils.findField(ConcreteSolutionEvaluatorBase.class, "log");
    Logger mockLogger = mock(Logger.class);
    ReflectionUtils.makeAccessible(logField);
    ReflectionUtils.setField(logField, abstractSolutionEvaluatorBase, mockLogger);

    for (PlaintextSequence plaintextSequence : simpleSolution.getPlaintextCharacters()) {
        plaintextSequence.setHasMatch(true);
        assertTrue(plaintextSequence.getHasMatch());
    }//from www  .  j ava 2 s.  co m

    abstractSolutionEvaluatorBase.clearHasMatchValues(simpleSolution);

    for (PlaintextSequence plaintextSequence : simpleSolution.getPlaintextCharacters()) {
        assertFalse(plaintextSequence.getHasMatch());
    }

    verifyZeroInteractions(mockLogger);
}

From source file:org.openinfinity.core.aspect.MultiTenantAspect.java

/**
 * Injection of tenant id will be done based on the <code>org.openinfinity.core.annotation.MultiTenant</code> annotation on method level. After injection of the tenant id 
 * <code>org.openinfinity.core.domain.entity.MultiTenantBaseEntity</code> can be used to retrieve the actual tenant id. <code>org.openinfinity.core.domain.entity.MultiTenantBaseEntity</code> 
 * can be extended by <code>org.openinfinity.core.domain.entity.MultiTenantBaseEntity</code>. 
 * /*from www . j av  a2  s  . c om*/
 * @param method Represents the method to be executed when exposing <code>org.openinfinity.core.annotation.MultiTenant</code> metadata to it.
 * @param multiTenant Represents the annotation which executed by the aspect.
 * @return Object Represents the original arguments for the method with injected tenant id.
 * @throws Throwable Represents the occurred exception during the execution of the aspect.
 */
@Around("multiTenantMethod() && @annotation(multiTenant)")
public Object populateTenantIdToMultiTenantEntity(ProceedingJoinPoint method, MultiTenant multiTenant)
        throws Throwable {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("MultiTenantAspect.populateTenantIdToMultiTenantEntity initialized.");
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication instanceof Identity) {
        Identity identity = (Identity) authentication;
        Object[] arguments = method.getArgs();
        for (Object object : arguments) {
            if (object instanceof MultiTenantBaseEntity) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(
                            "MultiTenantAspect.populateTenantIdToMultiTenantEntity arguments is istance of MultiTenantBaseEntity.");
                MultiTenantBaseEntity<?, ?, ?> multiTenantBaseEntity = (MultiTenantBaseEntity<?, ?, ?>) object;
                Object tenantId = identity.getTenantPrincipal().getId();
                Field tenantIdField = multiTenantBaseEntity.getClass().getField(TENANT_ID_FIELD);
                if (!tenantIdField.isAccessible()) {
                    tenantIdField.setAccessible(true);
                }
                Object convertedTenantId = typeConverter.convert(tenantId);
                if (tenantIdField.getType().isAssignableFrom(convertedTenantId.getClass())) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug(
                                "MultiTenantAspect.populateTenantIdToMultiTenantEntity tenant id is assignable from ["
                                        + convertedTenantId.getClass().getName() + ".");
                    ReflectionUtils.setField(tenantIdField, multiTenantBaseEntity, convertedTenantId);
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("MultiTenantAspect.populateTenantIdToMultiTenantEntity injected tenant id ["
                                + convertedTenantId.toString() + "] to the entity.");
                } else {
                    ExceptionUtil.throwSystemException("Field [" + tenantIdField.getType().getName()
                            + "] is not assignable from [" + convertedTenantId.getClass().getName());
                }
            }
        }
    }
    return method.proceed();
}

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

@SuppressWarnings("unchecked")
@Test//from   www  .j  a  v  a 2s .c  o  m
public void testCrossover() {
    ConcurrentMultigenerationalGeneticAlgorithm concurrentMultigenerationalGeneticAlgorithm = new ConcurrentMultigenerationalGeneticAlgorithm();
    concurrentMultigenerationalGeneticAlgorithm.setTaskExecutor(taskExecutor);

    Population population = new Population();
    FitnessEvaluator fitnessEvaluatorMock = mock(FitnessEvaluator.class);
    when(fitnessEvaluatorMock.evaluate(any(Chromosome.class))).thenReturn(DEFAULT_FITNESS_VALUE);
    population.setFitnessEvaluator(fitnessEvaluatorMock);

    Selector selectorMock = mock(Selector.class);
    population.setSelector(selectorMock);
    when(selectorMock.getNextIndex(anyListOf(Chromosome.class), any(Double.class))).thenReturn(0, 1, 2, 3, 4);

    int initialPopulationSize = 50;

    for (int i = 0; i < initialPopulationSize; i++) {
        population.addIndividual(new MockKeylessChromosome());
    }

    concurrentMultigenerationalGeneticAlgorithm.setPopulation(population);

    CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class);

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

    Chromosome chromosomeToReturn = new MockKeylessChromosome();
    when(crossoverAlgorithmMock.crossover(any(Chromosome.class), any(Chromosome.class)))
            .thenReturn(Arrays.asList(chromosomeToReturn));

    GeneticAlgorithmStrategy strategy = new GeneticAlgorithmStrategy();
    strategy.setCrossoverRate(0.1);

    Field strategyField = ReflectionUtils.findField(ConcurrentMultigenerationalGeneticAlgorithm.class,
            "strategy");
    ReflectionUtils.makeAccessible(strategyField);
    ReflectionUtils.setField(strategyField, concurrentMultigenerationalGeneticAlgorithm, strategy);

    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(initialPopulationSize);

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

    /*
     * The population size should be reduced by the number of parents used
     * during crossover.
     */
    assertEquals(40, population.size());

    assertEquals(5, childrenProduced);

    // There should be 10 ineligible parents, along with the 5 children
    assertEquals(15, ineligibleForReproductionFromObject.size());

    verify(selectorMock, times(10)).getNextIndex(anyListOf(Chromosome.class), any(Double.class));

    verify(crossoverAlgorithmMock, times(5)).crossover(any(Chromosome.class), any(Chromosome.class));
}

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

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

    GeneticAlgorithm geneticAlgorithm = mock(GeneticAlgorithm.class);

    Population population = new Population();
    SolutionChromosome solutionChromosome = new SolutionChromosome();
    solutionChromosome.setEvaluationNeeded(false);
    population.addIndividual(solutionChromosome);
    when(geneticAlgorithm.getPopulation()).thenReturn(population);

    geneticCipherSolutionService.setGeneticAlgorithm(geneticAlgorithm);

    SolutionDao solutionDaoMock = mock(SolutionDao.class);
    geneticCipherSolutionService.setSolutionDao(solutionDaoMock);

    GenericCallback genericCallbackMock = mock(GenericCallback.class);

    Runtime runtimeMock = mock(Runtime.class);

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

    String[] commandsAfter = { "command1", "command2" };
    geneticCipherSolutionService.setCommandsAfter(commandsAfter);

    String[] commandsBefore = { "command3", "command4" };
    geneticCipherSolutionService.setCommandsBefore(commandsBefore);

    GeneticAlgorithmStrategy geneticAlgorithmStrategy = new GeneticAlgorithmStrategy();

    // Before the algorithm begins, this will be false
    assertFalse(geneticCipherSolutionService.isRunning());
    geneticCipherSolutionService.begin(geneticAlgorithmStrategy, genericCallbackMock, false);
    /*//from  w ww.j a  v  a2 s  .  c o  m
     * After the algorithm ends, this will again be false. It is only true
     * actually during the algorithm.
     */
    assertFalse(geneticCipherSolutionService.isRunning());

    verify(solutionDaoMock, times(1)).insert(same(solutionChromosome));

    verify(genericCallbackMock, times(1)).doCallback();

    /*
     * These commands should still get called even though an exception was
     * caught
     */
    verify(runtimeMock, times(1)).exec(eq("command1"));
    verify(runtimeMock, times(1)).exec(eq("command2"));
    verify(runtimeMock, times(1)).exec(eq("command3"));
    verify(runtimeMock, times(1)).exec(eq("command4"));
    verifyNoMoreInteractions(runtimeMock);

    verify(geneticAlgorithm, times(1)).evolveAutonomously();

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