Example usage for org.springframework.util ReflectionUtils findMethod

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

Introduction

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

Prototype

@Nullable
public static Method findMethod(Class<?> clazz, String name, @Nullable Class<?>... paramTypes) 

Source Link

Document

Attempt to find a Method on the supplied class with the supplied name and parameter types.

Usage

From source file:org.openmrs.module.webservices.rest.util.ReflectionUtil.java

/**
 * @param name the full method name to look for
 * @return the java Method object if found. (does not return null)
 * @throws RuntimeException if not method found by the given name in the current class
 * @param clazz/*from w  w  w.java  2  s.c  o m*/
 * @param propName
 * @return
 */
public static Method findMethod(Class<?> clazz, String name) {
    Method ret = ReflectionUtils.findMethod(clazz, name, (Class<?>[]) null);
    if (ret == null)
        throw new RuntimeException("No suitable method \"" + name + "\" in " + clazz);
    return ret;
}

From source file:org.pentaho.proxy.creators.userdatailsservice.ProxyUserDetailsServiceTest.java

@Test
public void testNoUserDetailsProxyWrapper() {

    Object wrappedObject = new ProxyUserDetailsService(mockUserDetailsService);

    Assert.assertNotNull(wrappedObject);

    Method loadUserByUsernameMethod = ReflectionUtils.findMethod(wrappedObject.getClass(), "loadUserByUsername",
            String.class);

    try {/*from  w ww.  j a va  2s.c  o m*/
        loadUserByUsernameMethod.invoke(wrappedObject, MOCK_USERNAME_NOT_EXISTS);
        Assert.fail();

    } catch (InvocationTargetException e) {
        Assert.assertTrue(e.getCause() instanceof UsernameNotFoundException);
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        Assert.fail();
    }

    try {
        loadUserByUsernameMethod.invoke(wrappedObject, MOCK_USERNAME_NOT_EXISTS_RETURNS_NULL);
        Assert.fail();

    } catch (InvocationTargetException e) {
        Assert.assertTrue(e.getCause() instanceof UsernameNotFoundException);
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        Assert.fail();
    }
}

From source file:org.pentaho.proxy.creators.userdetailsservice.S4UserDetailsServiceProxyCreatorTest.java

@Test
public void testNoUserDetailsProxyWrapper() {

    Object wrappedObject = new S4UserDetailsServiceProxyCreatorForTest().create(mockUserDetailsService);

    Assert.assertNotNull(wrappedObject);

    Method loadUserByUsernameMethod = ReflectionUtils.findMethod(wrappedObject.getClass(), "loadUserByUsername",
            String.class);

    try {//from  w  ww  .ja va2 s .  c om
        loadUserByUsernameMethod.invoke(wrappedObject, MOCK_USERNAME_NOT_EXISTS);
        Assert.fail();

    } catch (InvocationTargetException e) {
        Assert.assertTrue(e.getCause() instanceof UsernameNotFoundException);
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        Assert.fail();
    }

    try {
        loadUserByUsernameMethod.invoke(wrappedObject, MOCK_USERNAME_NOT_EXISTS_RETURNS_NULL);
        Assert.fail();

    } catch (InvocationTargetException e) {
        Assert.assertTrue(e.getCause() instanceof UsernameNotFoundException);
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        Assert.fail();
    }
}

From source file:com.github.hateoas.forms.spring.AffordanceBuilderFactoryTest.java

@Test
public void testLinkToMethodInvocationReverseRel() throws Exception {
    final Method getEventMethod = ReflectionUtils.findMethod(EventControllerSample.class, "findEventByName",
            String.class);
    final Affordance affordance = factory
            .linkTo(AffordanceBuilder.methodOn(EventControllerSample.class).getEvent((String) null))
            .reverseRel("schema:parent", "ex:children").build();
    assertEquals("http://example.com/events/{eventId}", affordance.getHref());
    assertEquals("schema:parent", affordance.getRev());
    assertEquals("ex:children", affordance.getRel());
}

From source file:com.javafxpert.wikibrowser.model.conceptmap.ItemRepository.java

/**
 * Adds an relationship to the repository
 * @param itemIdA//from ww w  .  j a  v  a2s. c  om
 * @param itemIdB
 * @param propId
 * @param propLabel
 *
 * TODO: Consider using reflection for method invocation
 * TODO: Protect against null or empty arguments
 */
// MATCH (a:Item {itemId:"Q2"}), (b:Item {itemId:"Q185969"})
// MERGE (a)-[:SHAPE {propId:"P1419", label:"shape"}]->(b)
default void addRelationship(String itemIdA, String itemIdB, String propId, String propLabel) {

    String methodStr = "addRel" + propId;
    Method method = ReflectionUtils.findMethod(ItemRepository.class, methodStr,
            new Class[] { String.class, String.class, String.class, String.class });
    if (method != null) {
        try {
            //ReflectionUtils.invokeMethod(method, this, itemIdA, itemIdB, propId, propLabel);

            //TODO: Ascertain whether blank propLabel is OK, as it would avoid dups
            ReflectionUtils.invokeMethod(method, this, itemIdA, itemIdB, propId, propId.toLowerCase());
        } catch (Exception e) {
            System.out.println("Exception in invokeMethod " + methodStr + ": " + e);
            // TODO: Remove println above and decide how to report
        }
    } else {
        //addRel(itemIdA, itemIdB, propId, propLabel);

        //TODO: Ascertain whether blank propLabel is OK, as it would avoid dups
        addRel(itemIdA, itemIdB, propId, propId.toLowerCase());

        // Temporary code to populate the properties-related code in this class

        Integer propIdInt = new Integer(propId.substring(1));

        if (!propCodeMap.containsKey(propIdInt)) {
            String capsPropLabel = propLabel.trim().replaceAll(" ", "_").replaceAll("-", "_")
                    .replaceAll("'", "").toUpperCase();

            String code = "  @Query(\"MATCH (a:Item {itemId:{itemIdA}}), (b:Item {itemId:{itemIdB}}) MERGE (a)-[:"
                    + capsPropLabel + " {propId:{propId}, label:{propLabel}}]->(b)\")\n";
            code += "  void " + methodStr
                    + "(@Param(\"itemIdA\") String itemIdA, @Param(\"itemIdB\") String itemIdB, @Param(\"propId\") String propId, @Param(\"propLabel\") String propLabel);";

            propCodeMap.put(propIdInt, code);

            System.out.println(
                    "============Please paste the following methods in ItemRepository:===============");

            propCodeMap.forEach((k, v) -> {
                System.out.println(v + "\n");
            });

            System.out.println(
                    "\n\n============End of methods to paste in ItemRepository===========================");

            /*
            System.out.println("\n\nNeed to create method " + methodStr + "() in ItemRepository:\n\n");
                    
            String capsPropLabel = propLabel.trim().replaceAll(" ", "_").toUpperCase();
            System.out.println("  @Query(\"MATCH (a:Item {itemId:{itemIdA}}), (b:Item {itemId:{itemIdB}}) MERGE (a)-[:" +
                capsPropLabel + " {propId:{propId}, label:{propLabel}}]->(b)\")"
            );
            System.out.println("  void " + methodStr +
            "(@Param(\"itemIdA\") String itemIdA, @Param(\"itemIdB\") String itemIdB, @Param(\"propId\") String propId, @Param(\"propLabel\") String propLabel);"
            );
                    
            System.out.println("\n\n");
            */
        }

    }
}

From source file:org.openmrs.module.jsslab.rest.v1_0.resource.LabOrderSubclassHandler.java

/**
 * @see org.openmrs.module.webservices.rest.web.resource.impl.DelegatingResourceHandler#getRepresentationDescription(org.openmrs.module.webservices.rest.web.representation.Representation)
 */// w  w w .j  a va  2 s  .  c  o m
@Override
public DelegatingResourceDescription getRepresentationDescription(Representation rep) {
    DelegatingResourceDescription description = new DelegatingResourceDescription();
    if (rep instanceof DefaultRepresentation) {
        //         
        description.addProperty("uuid");
        description.addProperty("labOrderId");
        description.addProperty("concept", Representation.REF);
        description.addProperty("orderer", Representation.REF);
        description.addProperty("startDate");
        description.addProperty("voided");
        description.addSelfLink();
        description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL);
        return description;
    } else if (rep instanceof FullRepresentation) {
        description.addProperty("uuid");
        description.addProperty("labOrderId");
        description.addProperty("urgent");
        description.addProperty("retestOf", Representation.REF);
        description.addProperty("physicianRetest");
        description.addProperty("retestReason");
        description.addProperty("orderType", Representation.REF);
        description.addProperty("patient", Representation.DEFAULT);
        description.addProperty("concept", Representation.REF);
        description.addProperty("orderer", Representation.REF);
        description.addProperty("encounter", Representation.REF);
        description.addProperty("instructions");
        description.addProperty("startDate");
        description.addProperty("autoExpireDate");
        description.addProperty("discontinued");
        description.addProperty("discontinuedDate");
        description.addProperty("discontinuedBy", Representation.REF);
        description.addProperty("discontinuedReason");
        description.addProperty("voided");
        description.addSelfLink();
        Method m = ReflectionUtils.findMethod(getResource().getClass(), "getAuditInfo", (Class<?>[]) null);
        description.addProperty("auditInfo", m);
        return description;
    }
    return null;
}

From source file:at.ac.tuwien.infosys.jcloudscale.test.unit.TestReflectionUtil.java

Method resolveMethod(Class<?> type, String name, Class<?>... paramTypes) {
    Method expected = ReflectionUtils.findMethod(type, name, paramTypes);
    Method actual = null;//from w  ww. j  a va  2  s .  c  om
    try {
        actual = findMethod(type, name, paramTypes);
    } catch (Exception e) {
        // Ignore
    }
    assertEquals(expected, actual);
    if (actual != null) {
        assertEquals(expected.getDeclaringClass(), actual.getDeclaringClass());
    }
    return actual;
}

From source file:org.javelin.sws.ext.bind.internal.metadata.PropertyCallback.java

/**
 * <p>Reads class' metadata and returns a {@link XmlEventsPattern pattern of XML events} which may be used to marshal
 * an object of the analyzed class.<?p>
 * /*from w w  w  . ja  v  a 2  s  .c  om*/
 * @return
 */
public TypedPattern<T> analyze() {
    TypedPattern<T> result = this.patternRegistry.findPatternByClass(this.clazz);

    if (result != null)
        return result;

    log.trace("Analyzing {} class with {} type name", this.clazz.getName(), this.typeName);

    // analyze fields
    ReflectionUtils.doWithFields(this.clazz, this, new FieldFilter() {
        @Override
        public boolean matches(Field field) {
            return !Modifier.isStatic(field.getModifiers());
        }
    });

    // analyze get/set methods - even private ones!
    ReflectionUtils.doWithMethods(this.clazz, this, new MethodFilter() {
        @Override
        public boolean matches(Method method) {
            boolean match = true;
            // is it getter?
            match &= method.getName().startsWith("get");
            match &= method.getParameterTypes().length == 0;
            match &= method.getReturnType() != Void.class;
            // is there a setter?
            if (match) {
                Method setter = ReflectionUtils.findMethod(clazz, method.getName().replaceFirst("^get", "set"),
                        method.getReturnType());
                // TODO: maybe allow non-void returning setters as Spring-Framework already does? Now: yes
                match = setter != null || Collection.class.isAssignableFrom(method.getReturnType());
            }

            return match;
        }
    });

    if (this.valueMetadata != null && this.childElementMetadata.size() == 0
            && this.childAttributeMetadata.size() == 0) {
        // we have a special case, where Java class becomes simpleType:
        //  - formatting the analyzed class is really formatting the value
        //  - the type information of the analyzed class is not changed!
        log.trace("Changing {} class' pattern to SimpleContentPattern", this.clazz.getName());

        SimpleContentPattern<T> valuePattern = SimpleContentPattern.newValuePattern(this.typeName, this.clazz);
        SimpleContentPattern<?> simpleTypePattern = (SimpleContentPattern<?>) this.valueMetadata.getPattern();
        valuePattern.setFormatter(
                PeelingFormatter.newPeelingFormatter(this.valueMetadata, simpleTypePattern.getFormatter()));
        result = valuePattern;
    } else {
        if (this.valueMetadata != null && this.childElementMetadata.size() > 0) {
            throw new RuntimeException("TODO: can't mix @XmlValue and @XmlElements");
        }

        // we have complex type (possibly with simpleContent, when there's @XmlValue + one or more @XmlAttributes)
        // @XmlAttributes first. then @XmlElements
        this.childAttributeMetadata.addAll(this.childElementMetadata);
        if (this.valueMetadata != null)
            this.childAttributeMetadata.add(this.valueMetadata);

        result = ComplexTypePattern.newContentModelPattern(this.typeName, this.clazz,
                this.childAttributeMetadata);
    }

    if (log.isTraceEnabled())
        log.trace("-> Class {} was mapped to {} with {} XSD type", this.clazz.getName(), result, this.typeName);

    return result;
}

From source file:org.synyx.hera.si.PluginRegistryAwareMessageHandler.java

private List<Object> invokePlugins(Collection<? extends Plugin<?>> plugins, Message<?> message) {
    List<Object> results = new ArrayList<Object>();
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Invoking plugin(s) %s with message %s",
                StringUtils.collectionToCommaDelimitedString(plugins), message));
    }/*from   w ww .  java  2s .c  o m*/

    for (Plugin<?> plugin : plugins) {

        Object[] invocationArguments = getInvocationArguments(message);
        Class<?>[] types = getTypes(invocationArguments);

        Method businessMethod = ReflectionUtils.findMethod(pluginType, serviceMethodName, types);

        if (businessMethod == null) {
            throw new MessageHandlingException(message,
                    String.format("Did not find a method %s on %s taking the following parameters %s",
                            serviceMethodName, pluginType.getName(), Arrays.toString(types)));
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Invoke plugin method %s using arguments %s", businessMethod,
                    Arrays.toString(invocationArguments)));
        }

        Object result = ReflectionUtils.invokeMethod(businessMethod, plugin, invocationArguments);

        if (!businessMethod.getReturnType().equals(void.class)) {
            results.add(result);
        }
    }

    return results;
}

From source file:org.shept.persistence.provider.DaoUtils.java

private static Object copyTemplate_Experimental(HibernateDaoSupport dao, Object entityModelTemplate) {
    ClassMetadata modelMeta = getClassMetadata(dao, entityModelTemplate);
    if (null == modelMeta) {
        return null;
    }/* w w w  .  j  a v a2s.co m*/
    String idName = modelMeta.getIdentifierPropertyName();
    Object modelCopy = BeanUtils.instantiateClass(entityModelTemplate.getClass());
    BeanUtils.copyProperties(entityModelTemplate, modelCopy, new String[] { idName });

    Type idType = modelMeta.getIdentifierType();
    if (null == idType || !idType.isComponentType()) {
        return modelCopy;
    }

    Object idValue = modelMeta.getPropertyValue(entityModelTemplate, idName, EntityMode.POJO);
    if (null == idValue) {
        return modelCopy;
    }

    Object idCopy = BeanUtils.instantiate(idValue.getClass());
    BeanUtils.copyProperties(idValue, idCopy);

    if (null == idValue || (null != idType)) {
        return modelCopy;
    }

    Method idMth = ReflectionUtils.findMethod(entityModelTemplate.getClass(),
            "set" + StringUtils.capitalize(idName), new Class[] {});
    if (idMth != null) {
        ReflectionUtils.invokeMethod(idMth, modelCopy, idCopy);
    }

    return modelCopy;
}