Example usage for org.springframework.util ReflectionUtils makeAccessible

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

Introduction

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

Prototype

@SuppressWarnings("deprecation") 
public static void makeAccessible(Field field) 

Source Link

Document

Make the given field accessible, explicitly setting it accessible if necessary.

Usage

From source file:de.zib.gndms.infra.system.PluggableTaskFlowProvider.java

@PreDestroy
public void destroyPlugins() {

    final Map<String, TaskFlowFactory> factories = getFactories();

    for (TaskFlowFactory factory : factories.values()) {
        for (Method method : factory.getClass().getDeclaredMethods()) {
            if (method.getAnnotation(PreDestroy.class) != null) {
                ReflectionUtils.makeAccessible(method);
                try {
                    method.invoke(factory, (Object[]) null);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(
                            "THIS IS NOT HAPPENING!!! Method had been made accessible but is not accessible anyway",
                            e);//from  w w  w  .jav a2s. co m
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(
                            "Could not call PreDestroy method (" + method.toGenericString() + ")", e);
                }
            }
        }
    }
}

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

@Test
@SuppressWarnings("unchecked")
public void testSetFileParser() {
    FileParser<Word> fileParserToSet = mock(FileParser.class);
    WordListImporterImpl wordListImporterImpl = new WordListImporterImpl();
    wordListImporterImpl.setFileParser(fileParserToSet);

    Field fileParserField = ReflectionUtils.findField(WordListImporterImpl.class, "partOfSpeechFileParser");
    ReflectionUtils.makeAccessible(fileParserField);
    FileParser<Word> fileParserFromObject = (FileParser<Word>) ReflectionUtils.getField(fileParserField,
            wordListImporterImpl);/*w ww  .j a  va2  s .c om*/

    assertSame(fileParserToSet, fileParserFromObject);
}

From source file:co.paralleluniverse.springframework.web.method.support.FiberInvocableHandlerMethod.java

protected Object fiberDispatchInvoke(final Object... args) {
    final Object b = getBean();
    final Method m = getBridgedMethod();
    ReflectionUtils.makeAccessible(m);

    // Returning deferred even for normal return values, Spring return handlers will take care dynamically based on the actual returned value
    final DeferredResult ret = new DeferredResult();

    // The actual method execution and deferred completion is dispatched to a new fiber
    new Fiber(new SuspendableRunnable() {
        private Object deAsync(final Object o) throws SuspendExecution, Exception {
            if (o instanceof Callable)
                return deAsync(((Callable) o).call());
            else/* ww w  .j  a va  2  s. c  o  m*/
                return o;
        }

        @Override
        public void run() throws SuspendExecution, InterruptedException {
            try {
                Object originalRet = m.invoke(b, args);
                ret.setResult(deAsync(originalRet));
            } catch (IllegalArgumentException ex) {
                assertTargetBean(m, b, args);
                ret.setErrorResult(
                        new IllegalStateException(getInvocationErrorMessage(ex.getMessage(), args), ex));
            } catch (InvocationTargetException ex) {
                // Unwrap for HandlerExceptionResolvers ...
                Throwable targetException = ex.getTargetException();
                if (targetException instanceof RuntimeException || targetException instanceof Error
                        || targetException instanceof Exception) {
                    ret.setErrorResult(targetException);
                } else {
                    String msg = getInvocationErrorMessage("Failed to invoke controller method", args);
                    ret.setErrorResult(new IllegalStateException(msg, targetException));
                }
            } catch (Exception ex) {
                ret.setErrorResult(ex);
            }
        }
    }).start();

    return ret;
}

From source file:org.grails.datastore.mapping.query.order.ManualEntityOrdering.java

public List applyOrder(List results, Query.Order order) {
    final String name = order.getProperty();

    @SuppressWarnings("hiding")
    final PersistentEntity entity = getEntity();
    PersistentProperty property = entity.getPropertyByName(name);
    if (property == null) {
        final PersistentProperty identity = entity.getIdentity();
        if (name.equals(identity.getName())) {
            property = identity;/*  ww  w.  ja v  a  2s. c o m*/
        }
    }

    if (property != null) {
        final PersistentProperty finalProperty = property;
        Collections.sort(results, new Comparator() {

            public int compare(Object o1, Object o2) {

                if (entity.isInstance(o1) && entity.isInstance(o2)) {
                    final String propertyName = finalProperty.getName();
                    Method readMethod = cachedReadMethods.get(propertyName);
                    if (readMethod == null) {
                        BeanWrapper b = PropertyAccessorFactory.forBeanPropertyAccess(o1);
                        final PropertyDescriptor pd = b.getPropertyDescriptor(propertyName);
                        if (pd != null) {
                            readMethod = pd.getReadMethod();
                            if (readMethod != null) {
                                ReflectionUtils.makeAccessible(readMethod);
                                cachedReadMethods.put(propertyName, readMethod);
                            }
                        }
                    }

                    if (readMethod != null) {
                        final Class<?> declaringClass = readMethod.getDeclaringClass();
                        if (declaringClass.isInstance(o1) && declaringClass.isInstance(o2)) {
                            Object left = ReflectionUtils.invokeMethod(readMethod, o1);
                            Object right = ReflectionUtils.invokeMethod(readMethod, o2);

                            if (left == null && right == null)
                                return 0;
                            if (left != null && right == null)
                                return 1;
                            if (left == null)
                                return -1;
                            if ((left instanceof Comparable) && (right instanceof Comparable)) {
                                return ((Comparable) left).compareTo(right);
                            }
                        }
                    }
                }
                return 0;
            }
        });
    }

    if (order.getDirection() == Query.Order.Direction.DESC) {
        results = reverse(results);
    }

    return results;
}

From source file:com.ciphertool.genetics.algorithms.mutation.cipherkey.RandomValueMutationAlgorithmTest.java

@Test
public void testSetMaxMutationsPerChromosome() {
    Integer maxMutationsPerChromosomeToSet = 3;

    RandomValueMutationAlgorithm randomValueMutationAlgorithm = new RandomValueMutationAlgorithm();
    randomValueMutationAlgorithm.setMaxMutationsPerChromosome(maxMutationsPerChromosomeToSet);

    Field maxMutationsPerChromosomeField = ReflectionUtils.findField(RandomValueMutationAlgorithm.class,
            "maxMutationsPerChromosome");
    ReflectionUtils.makeAccessible(maxMutationsPerChromosomeField);
    Integer maxMutationsPerChromosomeFromObject = (Integer) ReflectionUtils
            .getField(maxMutationsPerChromosomeField, randomValueMutationAlgorithm);

    assertSame(maxMutationsPerChromosomeToSet, maxMutationsPerChromosomeFromObject);
}

From source file:de.tudarmstadt.ukp.clarin.webanno.brat.message.BeanAsArraySerializer.java

@Override
public void serializeContents(Object value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {
    JsonPropertyOrder order = value.getClass().getAnnotation(JsonPropertyOrder.class);
    String[] propOrder = (order == null) ? null : order.value();

    if (propOrder == null) {
        throw new IllegalStateException("Bean must declare JsonPropertyOrder!");
    }//from   www. j  av a2s  .c o  m

    if (propOrder.length == 0) {
        return;
    }

    int i = 0;
    try {
        do {
            Field field = value.getClass().getDeclaredField(propOrder[i]);
            ReflectionUtils.makeAccessible(field);
            Object elem = field.get(value);
            if (elem == null) {
                provider.defaultSerializeNull(jgen);
            } else {
                Class<?> cc = elem.getClass();
                JsonSerializer<Object> serializer = provider.findValueSerializer(cc, null);
                serializer.serialize(elem, jgen, provider);
            }
            ++i;
        } while (i < propOrder.length);
    } catch (Exception e) {
        // [JACKSON-55] Need to add reference information
        wrapAndThrow(provider, e, value, i);
    }
}

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);/*ww w .  j a v  a2s  .co m*/

    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:com.ciphertool.genetics.algorithms.crossover.LowestCommonGroupUnevaluatedCrossoverAlgorithmTest.java

@Test
public void testSetMutateDuringCrossover() {
    boolean mutateDuringCrossoverToSet = true;

    LowestCommonGroupUnevaluatedCrossoverAlgorithm lowestCommonGroupUnevaluatedCrossoverAlgorithm = new LowestCommonGroupUnevaluatedCrossoverAlgorithm();
    lowestCommonGroupUnevaluatedCrossoverAlgorithm.setMutateDuringCrossover(mutateDuringCrossoverToSet);

    Field mutateDuringCrossoverField = ReflectionUtils
            .findField(LowestCommonGroupUnevaluatedCrossoverAlgorithm.class, "mutateDuringCrossover");
    ReflectionUtils.makeAccessible(mutateDuringCrossoverField);
    boolean mutateDuringCrossoverFromObject = (boolean) ReflectionUtils.getField(mutateDuringCrossoverField,
            lowestCommonGroupUnevaluatedCrossoverAlgorithm);

    assertEquals(mutateDuringCrossoverToSet, mutateDuringCrossoverFromObject);
}

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

@Test
public void testSetExecutionStatisticsDao() {
    ExecutionStatisticsDao executionStatisticsDaoToSet = mock(ExecutionStatisticsDao.class);

    MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm();
    multigenerationalGeneticAlgorithm.setExecutionStatisticsDao(executionStatisticsDaoToSet);

    Field executionStatisticsDaoField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "executionStatisticsDao");
    ReflectionUtils.makeAccessible(executionStatisticsDaoField);
    ExecutionStatisticsDao executionStatisticsDaoFromObject = (ExecutionStatisticsDao) ReflectionUtils
            .getField(executionStatisticsDaoField, multigenerationalGeneticAlgorithm);

    assertSame(executionStatisticsDaoToSet, executionStatisticsDaoFromObject);
}

From source file:com.ciphertool.genetics.algorithms.crossover.ConservativeCrossoverAlgorithmTest.java

@Test
public void testSetMutateDuringCrossover() {
    boolean mutateDuringCrossoverToSet = true;

    ConservativeCrossoverAlgorithm conservativeCrossoverAlgorithm = new ConservativeCrossoverAlgorithm();
    conservativeCrossoverAlgorithm.setMutateDuringCrossover(mutateDuringCrossoverToSet);

    Field mutateDuringCrossoverField = ReflectionUtils.findField(ConservativeCrossoverAlgorithm.class,
            "mutateDuringCrossover");
    ReflectionUtils.makeAccessible(mutateDuringCrossoverField);
    boolean mutateDuringCrossoverFromObject = (boolean) ReflectionUtils.getField(mutateDuringCrossoverField,
            conservativeCrossoverAlgorithm);

    assertEquals(mutateDuringCrossoverToSet, mutateDuringCrossoverFromObject);
}