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.ryantenney.metrics.spring.InjectMetricAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) {
    final Class<?> targetClass = AopUtils.getTargetClass(bean);

    ReflectionUtils.doWithFields(targetClass, new FieldCallback() {
        @Override//w w w . ja va 2  s.  c o  m
        public void doWith(Field field) throws IllegalAccessException {
            final InjectMetric annotation = field.getAnnotation(InjectMetric.class);
            final String metricName = Util.forInjectMetricField(targetClass, field, annotation);

            final Class<?> type = field.getType();
            Metric metric = null;
            if (Meter.class == type) {
                metric = metrics.meter(metricName);
            } else if (Timer.class == type) {
                metric = metrics.timer(metricName);
            } else if (Counter.class == type) {
                metric = metrics.counter(metricName);
            } else if (Histogram.class == type) {
                metric = metrics.histogram(metricName);
            } else {
                throw new IllegalStateException("Cannot inject a metric of type " + type.getCanonicalName());
            }

            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, bean, metric);

            LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                    field.getName());
        }
    }, FILTER);

    return bean;
}

From source file:com.ciphertool.sentencebuilder.etl.parsers.FrequencyFileParserTest.java

@Test
public void testParseFile_InvalidFileName() {
    FrequencyFileParser frequencyFileParser = new FrequencyFileParser();
    frequencyFileParser.setFileName("arbitraryFileName");

    Logger logMock = mock(Logger.class);

    Field logField = ReflectionUtils.findField(FrequencyFileParser.class, "log");
    ReflectionUtils.makeAccessible(logField);
    ReflectionUtils.setField(logField, frequencyFileParser, logMock);

    List<Word> wordsFromFile = frequencyFileParser.parseFile();

    assertTrue(wordsFromFile.isEmpty());
    verify(logMock, times(1)).error(anyString(), any(FileNotFoundException.class));
}

From source file:dwalldorf.jadecr.converter.PropertyConverter.java

/**
 * Sets the value of {@code destField} in object {@code dest} to {@code value}.
 *
 * @param value     the value to set//from  ww w  . java  2s  .c om
 * @param destField the field to assign
 * @param dest      the object to manipulate
 */
private void setValue(Object value, Field destField, Object dest) {
    if (value != null) {
        if (ConvertUtil.isConvertibleObject(value)) {
            value = convert(value);
        }

        String valueTypeName = value.getClass().getName();
        String destTypeName = destField.getType().getName();

        if (valueTypeName.equals(destTypeName)) {
            ReflectionUtils.setField(destField, dest, value);
        }
    }
}

From source file:com.ciphertool.sentencebuilder.etl.parsers.PartOfSpeechFileParserTest.java

@Test
public void testParseFile_InvalidFileName() {
    PartOfSpeechFileParser partOfSpeechFileParser = new PartOfSpeechFileParser();
    partOfSpeechFileParser.setFileName("arbitraryFileName");

    Logger logMock = mock(Logger.class);

    Field logField = ReflectionUtils.findField(PartOfSpeechFileParser.class, "log");
    ReflectionUtils.makeAccessible(logField);
    ReflectionUtils.setField(logField, partOfSpeechFileParser, logMock);

    List<Word> wordsFromFile = partOfSpeechFileParser.parseFile();

    assertTrue(wordsFromFile.isEmpty());
    verify(logMock, times(1)).error(anyString(), any(FileNotFoundException.class));
}

From source file:springobjectmapper.AbstractRepository.java

private void insertWithSequence(T entity) {
    Object id = template.queryForObject(dialect.getNextSequenceValue(properties.getTableName() + "_SEQ"),
            properties.idField().getType());
    template.update(properties.parse(dialect.insertWithId()), properties.valuesOf(entity), id);
    ReflectionUtils.setField(properties.idField(), entity, id);
}

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

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

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

    simpleSolution.getPlaintextCharacters().get(0).setHasMatch(true);
    simpleSolution.getPlaintextCharacters().get(1).setHasMatch(true);
    simpleSolution.getPlaintextCharacters().get(4).setHasMatch(true);
    simpleSolution.getPlaintextCharacters().get(5).setHasMatch(true);
    simpleSolution.getPlaintextCharacters().get(6).setHasMatch(true);
    simpleSolution.getPlaintextCharacters().get(8).setHasMatch(true);
    simpleSolution.getPlaintextCharacters().get(9).setHasMatch(true);

    assertEquals(0, simpleSolution.getAdjacentMatches());

    abstractSolutionEvaluatorBase.setGeneticStructure(simpleCipher);
    int adjacentMatches = abstractSolutionEvaluatorBase
            .calculateAdjacentMatches(simpleSolution.getPlaintextCharacters());

    /*// w  w w . j av a2 s .  c o m
     * The adjacent match count should not be updated on the solution. It
     * should only be returned by the method.
     */
    assertEquals(0, simpleSolution.getAdjacentMatches());
    assertEquals(4, adjacentMatches);

    verifyZeroInteractions(mockLogger);
}

From source file:springobjectmapper.AbstractRepository.java

private void insertWithIdentity(T entity) {
    template.update(properties.parse(dialect.insert()), properties.valuesOf(entity));
    Object id = template.queryForObject(dialect.getInsertedId(), properties.idField().getType());
    ReflectionUtils.setField(properties.idField(), entity, id);
}

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

@Test
public void testCrossoverTask() {
    Chromosome mom = new MockKeylessChromosome();
    Chromosome dad = new MockKeylessChromosome();

    ConcurrentMultigenerationalGeneticAlgorithm concurrentMultigenerationalGeneticAlgorithm = new ConcurrentMultigenerationalGeneticAlgorithm();
    ConcurrentMultigenerationalGeneticAlgorithm.CrossoverTask generatorTask = concurrentMultigenerationalGeneticAlgorithm.new CrossoverTask(
            mom, dad);//from w  ww.  j ava2  s. c  om

    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(same(mom), same(dad))).thenReturn(Arrays.asList(chromosomeToReturn));

    List<Chromosome> chromosomesReturned = null;
    try {
        chromosomesReturned = generatorTask.call();
    } catch (Exception e) {
        fail(e.getMessage());
    }

    assertEquals(1, chromosomesReturned.size());
    assertSame(chromosomeToReturn, chromosomesReturned.get(0));
    verify(crossoverAlgorithmMock, times(1)).crossover(same(mom), same(dad));
}

From source file:io.pivotal.poc.gateway.filters.pre.FileClaimCheckFilter.java

@Override
public void filter(RequestContext ctx) {
    StandardMultipartHttpServletRequest multipartRequest = this.extractMultipartRequest(ctx.getRequest());
    Map<String, String> uploadedFileMap = new HashMap<>();
    for (Map.Entry<String, MultipartFile> entry : multipartRequest.getFileMap().entrySet()) {
        String fileKey = entry.getKey();
        String claimCheck = store.save(new MultipartFileResource(entry.getValue()));
        uploadedFileMap.put(fileKey, claimCheck);
    }/*from  w w  w  . j av a2 s . c  om*/
    try {
        String json = this.mapper.writeValueAsString(uploadedFileMap);
        FileClaimCheckRequestWrapper wrapper = null;
        HttpServletRequest request = ctx.getRequest();
        if (request instanceof HttpServletRequestWrapper) {
            HttpServletRequest wrapped = (HttpServletRequest) ReflectionUtils.getField(this.requestField,
                    request);
            if (wrapped instanceof HttpServletRequestWrapper) {
                wrapped = ((HttpServletRequestWrapper) wrapped).getRequest();
            }
            wrapper = new FileClaimCheckRequestWrapper(json, wrapped);
            ReflectionUtils.setField(this.requestField, request, wrapper);
            ReflectionUtils.setField(this.contentDataField, request, json.getBytes());
            if (request instanceof ServletRequestWrapper) {
                ReflectionUtils.setField(this.servletRequestField, request, wrapper);
            }
        } else {
            wrapper = new FileClaimCheckRequestWrapper(json, request);
            ctx.setRequest(wrapper);
        }
        if (wrapper != null) {
            ctx.getZuulRequestHeaders().put("content-type", wrapper.getContentType());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    log.info(String.format("%s request to %s", multipartRequest.getMethod(),
            multipartRequest.getRequestURL().toString()));
}

From source file:sample.jsp.SampleJspApplication.java

private void clearJspSystemUris() {
    Field systemUris = ReflectionUtils.findField(TldScanner.class, "systemUris");
    systemUris.setAccessible(true);/*from  w w w . ja v a 2 s.c om*/
    ReflectionUtils.setField(systemUris, null, new HashSet<String>());
}