Example usage for java.lang.reflect Method toString

List of usage examples for java.lang.reflect Method toString

Introduction

In this page you can find the example usage for java.lang.reflect Method toString.

Prototype

public String toString() 

Source Link

Document

Returns a string describing this Method .

Usage

From source file:org.pentaho.hadoop.shim.cdh51.authentication.PropertyAuthenticationProviderParser.java

private void processPrefix(String prefix) {
    AuthenticationProvider provider = authenticationProviderInstantiator
            .instantiate(properties.getProperty(prefix + ".class"));
    if (provider != null) {
        for (Method method : provider.getClass().getMethods()) {
            if (method.getName().startsWith("set") && method.getName().length() >= 4
                    && method.getParameterTypes().length == 1) {
                String propName = prefix + "." + method.getName().substring(3, 4).toLowerCase();
                if (method.getName().length() > 4) {
                    propName += method.getName().substring(4);
                }//from  w  w  w .ja  v  a2s  .co m
                if (properties.containsKey(propName)) {
                    String strValue = Encr.decryptPasswordOptionallyEncrypted(properties.getProperty(propName));
                    Object actualValue = null;
                    Class<?> argType = method.getParameterTypes()[0];
                    if (argType.isPrimitive()) {
                        argType = ClassUtils.primitiveToWrapper(argType);
                    }
                    if (argType == String.class) {
                        actualValue = strValue;
                    } else {
                        Method valueOf = null;
                        try {
                            valueOf = argType.getMethod("valueOf", String.class);
                        } catch (NoSuchMethodException e1) {
                            logger.warn("Unable to find valueOf method on "
                                    + argType.getClass().getCanonicalName());
                        }
                        if (valueOf != null && Modifier.isStatic(valueOf.getModifiers())) {
                            try {
                                actualValue = valueOf.invoke(null, strValue);
                            } catch (Exception e) {
                                logger.warn("Unable to convert string property " + propName + "(" + strValue
                                        + ") to " + argType.getClass().getCanonicalName() + " to invoke setter "
                                        + method.getName(), e);
                            }
                        } else {
                            logger.warn("Could not find method to convert " + propName + "(" + strValue
                                    + ") to " + argType.getClass().getCanonicalName()
                                    + " (currently only primitives and their wrappers are supported)");
                        }
                    }
                    if (actualValue != null) {
                        try {
                            method.invoke(provider, actualValue);
                        } catch (Exception e) {
                            Throwable cause = e;
                            if (e instanceof InvocationTargetException) {
                                cause = e.getCause();
                            }
                            logger.warn("Error invoking setter " + method.toString() + " with property "
                                    + propName + "(" + strValue + ")", cause);
                        }
                    }
                }

            }
        }
        manager.registerAuthenticationProvider(provider);
    }
}

From source file:com.newmainsoftech.spray.slingong.datastore.Slim3PlatformTransactionManagerTest.java

@Test
public void testTransactionalAttributesOnStaticMethod1() throws Throwable {
    try {//from w ww  .  j av  a2s . c o  m
        Method createNewAuthorStaticMethod = Author.class.getDeclaredMethod("createNewAuthor",
                new Class[] { String.class });

        TransactionAttributeSource transactionAttributeSource
        //         = new AnnotationTransactionAttributeSource( false);
                = annotationTransactionAspect.getTransactionAttributeSource();

        TransactionAttribute transactionAttribute = transactionAttributeSource
                .getTransactionAttribute(createNewAuthorStaticMethod, Author.class);

        /* Made addition to ExtendedAnnotationTransactionAspect, so no matter of attribute value of 
         * @Transactional annotation, noRollBack method instead of rollback method of 
         * Slim3PlatformTransactionManager class will be called when encountering 
         * ConcurrentModificationException exception and DeadlineExceededException exception. 
        Assert.assertFalse( 
              transactionAttribute.rollbackOn( new ConcurrentModificationException()));
        Assert.assertFalse( 
              transactionAttribute.rollbackOn( new DeadlineExceededException()));
        */

        String name = transactionAttribute.getName();
        String message = String.format(
                "Attribution values of @Transactional annotation on %1$s:" + "%n%2$cvalue=\"%3$s\"",
                createNewAuthorStaticMethod.toString(), '\t', (name == null ? "" : name));
        int isolationLevel = transactionAttribute.getIsolationLevel();
        Assert.assertEquals(TransactionAttribute.ISOLATION_DEFAULT, isolationLevel);
        switch (isolationLevel) {
        case TransactionAttribute.ISOLATION_DEFAULT:
            message = message + String.format("%n%1$cisolation=ISOLATION_DEFAULT", '\t');
            break;
        case TransactionAttribute.ISOLATION_READ_COMMITTED:
            message = message + String.format("%n%1$cisolation=ISOLATION_READ_COMMITTED", '\t');
            break;
        case TransactionAttribute.ISOLATION_READ_UNCOMMITTED:
            message = message + String.format("%n%1$cisolation=ISOLATION_READ_UNCOMMITTED", '\t');
            break;
        case TransactionAttribute.ISOLATION_REPEATABLE_READ:
            message = message + String.format("%n%1$cisolation=ISOLATION_REPEATABLE_READ", '\t');
            break;
        case TransactionAttribute.ISOLATION_SERIALIZABLE:
            message = message + String.format("%n%1$cisolation=ISOLATION_SERIALIZABLE", '\t');
            break;
        default:
            Assert.fail("Unrecognizable isolation level.");
        } // switch

        int propagationBehavior = transactionAttribute.getPropagationBehavior();
        //Default propagation behavior seems to be TransactionAttribute.PROPAGATION_REQUIRED
        Assert.assertEquals(TransactionAttribute.PROPAGATION_REQUIRED, propagationBehavior);
        switch (propagationBehavior) {
        case TransactionAttribute.PROPAGATION_MANDATORY:
            message = message + String.format("%n%1$cpropagation=PROPAGATION_MANDATORY", '\t');
            break;
        case TransactionAttribute.PROPAGATION_NESTED:
            message = message + String.format("%n%1$cpropagation=PROPAGATION_NESTED", '\t');
            break;
        case TransactionAttribute.PROPAGATION_NEVER:
            message = message + String.format("%n%1$cpropagation=PROPAGATION_NEVER", '\t');
            break;
        case TransactionAttribute.PROPAGATION_NOT_SUPPORTED:
            message = message + String.format("%n%1$cpropagation=PROPAGATION_NOT_SUPPORTED", '\t');
            break;
        case TransactionAttribute.PROPAGATION_REQUIRED:
            message = message + String.format("%n%1$cpropagation=PROPAGATION_REQUIRED", '\t');
            break;
        case TransactionAttribute.PROPAGATION_REQUIRES_NEW:
            message = message + String.format("%n%1$cpropagation=PROPAGATION_REQUIRES_NEW", '\t');
            break;
        case TransactionAttribute.PROPAGATION_SUPPORTS:
            message = message + String.format("%n%1$cpropagation=PROPAGATION_SUPPORTS", '\t');
            break;
        default:
            Assert.fail("Unrecognizable propagation behavior.");
        } // switch

        String qualifier = transactionAttribute.getQualifier();
        message = message + String.format("%n%1$cqualifier=%2$s", '\t', qualifier);

        int timeout = transactionAttribute.getTimeout();
        Assert.assertEquals(TransactionAttribute.TIMEOUT_DEFAULT, timeout);
        message = message + String.format("%n%1$ctimeout=%2$d", '\t', timeout);

        boolean readOnlyFlag = transactionAttribute.isReadOnly();
        Assert.assertFalse(readOnlyFlag);
        message = message + String.format("%n%1$creadOnly=%2$s", '\t', String.valueOf(readOnlyFlag));

        if (logger.isDebugEnabled()) {
            logger.debug(message);
        }
    } catch (Throwable throwable) {
        throw throwable;
    }
}

From source file:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java

/**
 * Test for {@link ReflectionUtils#toString(java.lang.reflect.Method)}.
 *///from w w  w. j  av a2 s.c o  m
public void test_toString_forMethod() throws Exception {
    // "normal" Class
    {
        Method method = ReflectionUtils.getMethodBySignature(ArrayList.class, "size()");
        assertEquals("public int java.util.ArrayList.size()", ReflectionUtils.toString(method));
    }
    // "enchanced" Class
    {
        Class<?> clazz;
        {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(ArrayList.class);
            enhancer.setStrategy(new DefaultGeneratorStrategy() {
                private final ClassTransformer t = new ClassEmitterTransformer() {
                    @Override
                    public void begin_class(int version, int access, String className,
                            net.sf.cglib.asm.Type superType, net.sf.cglib.asm.Type[] interfaces,
                            String sourceFile) {
                        super.begin_class(version, access, className, superType, interfaces, sourceFile);
                        CodeEmitter emitter = begin_method(Opcodes.ACC_PUBLIC, new Signature("__foo__",
                                net.sf.cglib.asm.Type.VOID_TYPE, new net.sf.cglib.asm.Type[] {}), null);
                        emitter.return_value();
                        emitter.end_method();
                    }
                };

                @Override
                protected ClassGenerator transform(ClassGenerator cg) throws Exception {
                    return new TransformingClassGenerator(cg, t);
                }
            });
            enhancer.setCallback(new MethodInterceptor() {
                public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args,
                        MethodProxy proxy) throws Throwable {
                    return proxy.invokeSuper(obj, args);
                }
            });
            clazz = enhancer.create().getClass();
        }
        // method "size()" was done by CGLib, but exists in ArrayList, so method from ArrayList returned
        {
            Method method = ReflectionUtils.getMethodBySignature(clazz, "size()");
            assertThat(method.toString()).contains("$");
            assertEquals("public int java.util.ArrayList.size()", ReflectionUtils.toString(method));
        }
        // method "__foo__" was generated only in CGLib, so no other method to return
        {
            Method method = ReflectionUtils.getMethodBySignature(clazz, "__foo__()");
            String usualToString = method.toString();
            assertThat(usualToString).contains("$");
            assertEquals(usualToString, ReflectionUtils.toString(method));
        }
    }
}

From source file:org.jspresso.framework.model.component.basic.AbstractComponentInvocationHandler.java

/**
 * Invokes a service method on the component.
 *
 * @param proxy/*  ww  w . j a v a2 s .c o m*/
 *     the component to invoke the service on.
 * @param method
 *     the method implemented by the component.
 * @param args
 *     the arguments of the method implemented by the component.
 * @return the value returned by the method execution if any.
 *
 * @throws NoSuchMethodException
 *     if no mean could be found to service the method.
 */
@SuppressWarnings("unchecked")
protected Object invokeServiceMethod(Object proxy, Method method, Object... args) throws NoSuchMethodException {
    IComponentService service = componentDescriptor.getServiceDelegate(method);
    if (service != null) {
        try {
            if (service instanceof AbstractComponentServiceDelegate<?>) {
                Method refinedMethod = service.getClass().getMethod(method.getName(),
                        method.getParameterTypes());
                if (refinedMethod != null) {
                    return ((AbstractComponentServiceDelegate<Object>) service).executeWith(proxy,
                            refinedMethod, args);
                }
            }
            int signatureSize = method.getParameterTypes().length + 1;
            Class<?>[] parameterTypes = new Class<?>[signatureSize];
            Object[] parameters = new Object[signatureSize];

            parameterTypes[0] = componentDescriptor.getComponentContract();
            parameters[0] = proxy;

            for (int i = 1; i < signatureSize; i++) {
                parameterTypes[i] = method.getParameterTypes()[i - 1];
                parameters[i] = args[i - 1];
            }
            return MethodUtils.invokeMethod(service, method.getName(), parameters, parameterTypes);
        } catch (IllegalAccessException | NoSuchMethodException ex) {
            throw new ComponentException(ex);
        } catch (InvocationTargetException ex) {
            if (ex.getCause() instanceof RuntimeException) {
                throw (RuntimeException) ex.getCause();
            }
            throw new ComponentException(ex.getCause());
        }
    }
    throw new NoSuchMethodException(method.toString());
}

From source file:ca.uhn.fhir.rest.server.RestfulServer.java

private int findResourceMethods(Object theProvider, Class<?> clazz) throws ConfigurationException {
    int count = 0;

    for (Method m : ReflectionUtil.getDeclaredMethods(clazz)) {
        BaseMethodBinding<?> foundMethodBinding = BaseMethodBinding.bindMethod(m, getFhirContext(),
                theProvider);/*w w  w .j  a v a  2s. c o  m*/
        if (foundMethodBinding == null) {
            continue;
        }

        count++;

        if (foundMethodBinding instanceof ConformanceMethodBinding) {
            myServerConformanceMethod = foundMethodBinding;
            continue;
        }

        if (!Modifier.isPublic(m.getModifiers())) {
            throw new ConfigurationException(
                    "Method '" + m.getName() + "' is not public, FHIR RESTful methods must be public");
        } else {
            if (Modifier.isStatic(m.getModifiers())) {
                throw new ConfigurationException(
                        "Method '" + m.getName() + "' is static, FHIR RESTful methods must not be static");
            } else {
                ourLog.debug("Scanning public method: {}#{}", theProvider.getClass(), m.getName());

                String resourceName = foundMethodBinding.getResourceName();
                ResourceBinding resourceBinding;
                if (resourceName == null) {
                    resourceBinding = myServerBinding;
                } else {
                    RuntimeResourceDefinition definition = getFhirContext().getResourceDefinition(resourceName);
                    if (myResourceNameToBinding.containsKey(definition.getName())) {
                        resourceBinding = myResourceNameToBinding.get(definition.getName());
                    } else {
                        resourceBinding = new ResourceBinding();
                        resourceBinding.setResourceName(resourceName);
                        myResourceNameToBinding.put(resourceName, resourceBinding);
                    }
                }

                List<Class<?>> allowableParams = foundMethodBinding.getAllowableParamAnnotations();
                if (allowableParams != null) {
                    for (Annotation[] nextParamAnnotations : m.getParameterAnnotations()) {
                        for (Annotation annotation : nextParamAnnotations) {
                            Package pack = annotation.annotationType().getPackage();
                            if (pack.equals(IdParam.class.getPackage())) {
                                if (!allowableParams.contains(annotation.annotationType())) {
                                    throw new ConfigurationException("Method[" + m.toString()
                                            + "] is not allowed to have a parameter annotated with "
                                            + annotation);
                                }
                            }
                        }
                    }
                }

                resourceBinding.addMethod(foundMethodBinding);
                ourLog.debug(" * Method: {}#{} is a handler", theProvider.getClass(), m.getName());
            }
        }
    }

    return count;
}

From source file:org.jspresso.framework.model.component.basic.AbstractComponentInvocationHandler.java

/**
 * Handles methods invocations on the component proxy. Either : <li>delegates
 * to one of its extension if the accessed property is registered as being
 * part of an extension <li>handles property access internally
 * <p/>//w w w.  ja v  a 2 s.  co  m
 * {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public synchronized Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName()/* .intern() */;
    switch (methodName) {
    case "hashCode":
        return computeHashCode((IComponent) proxy);
    case "equals":
        return computeEquals((IComponent) proxy, args[0]);
    case "toString":
        return toString(proxy);
    case "getComponentContract":
        return componentDescriptor.getComponentContract();
    case "addPropertyChangeListener":
        if (args.length == 1) {
            addPropertyChangeListener(proxy, (PropertyChangeListener) args[0]);
            return null;
        }
        addPropertyChangeListener(proxy, (String) args[0], (PropertyChangeListener) args[1]);
        return null;
    case "addWeakPropertyChangeListener":
        if (args.length == 1) {
            addWeakPropertyChangeListener(proxy, (PropertyChangeListener) args[0]);
            return null;
        }
        addWeakPropertyChangeListener(proxy, (String) args[0], (PropertyChangeListener) args[1]);
        return null;
    case "removePropertyChangeListener":
        if (args.length == 1) {
            removePropertyChangeListener((PropertyChangeListener) args[0]);
            return null;
        }
        removePropertyChangeListener((String) args[0], (PropertyChangeListener) args[1]);
        return null;
    case "hasListeners":
        return hasListeners(proxy, (String) args[0]);
    case "getPropertyChangeListeners":
        if (args != null && args.length > 0) {
            return getPropertyChangeListeners(proxy, (String) args[0]);
        }
        return getPropertyChangeListeners(proxy);
    case "firePropertyChange":
        firePropertyChange(proxy, (String) args[0], args[1], args[2]);
        return null;
    case "blockEvents":
        return blockEvents();
    case "releaseEvents":
        releaseEvents();
        return null;
    case "straightSetProperty":
        straightSetProperty(proxy, (String) args[0], args[1]);
        return null;
    case "straightGetProperty":
        return straightGetProperty(proxy, (String) args[0]);
    case "straightSetProperties":
        straightSetProperties(proxy, (Map<String, Object>) args[0]);
        return null;
    case "straightGetProperties":
        return straightGetProperties(proxy);
    case "setPropertyProcessorsEnabled":
        propertyProcessorsEnabled = (Boolean) args[0];
        return null;
    case "getOwningComponent":
        return owningComponent;
    case "getOwningPropertyDescriptor":
        return owningPropertyDescriptor;
    case "setOwningComponent":
        owningComponent = (IComponent) args[0];
        owningPropertyDescriptor = (IPropertyDescriptor) args[1];
        return null;
    case "checkIntegrity":
        checkIntegrity(proxy);
        return null;
    case "checkMandatoryProperties":
        checkMandatoryProperties(proxy);
        return null;
    default:
        if (isLifecycleMethod(method)) {
            return invokeLifecycleInterceptors(proxy, method, args);
        }
        AccessorInfo accessorInfo = getAccessorFactory().getAccessorInfo(method);
        EAccessorType accessorType = accessorInfo.getAccessorType();
        IPropertyDescriptor propertyDescriptor = null;
        if (accessorType != EAccessorType.NONE) {
            String accessedPropertyName = accessorInfo.getAccessedPropertyName();
            if (accessedPropertyName != null) {
                propertyDescriptor = componentDescriptor.getPropertyDescriptor(accessedPropertyName);
            }
        }
        if (propertyDescriptor != null) {
            Class<IComponentExtension<IComponent>> extensionClass = (Class<IComponentExtension<IComponent>>) propertyDescriptor
                    .getDelegateClass();
            if (extensionClass != null) {
                return accessComputedProperty(propertyDescriptor, accessorInfo, extensionClass, proxy, method,
                        args);
            } else if (!propertyDescriptor.isComputed()) {
                if (accessorInfo.isModifier()) {
                    if (modifierMonitors != null && modifierMonitors.contains(methodName)) {
                        return null;
                    }
                    if (modifierMonitors == null) {
                        modifierMonitors = new THashSet<>(1);
                    }
                    modifierMonitors.add(methodName);
                }
                try {
                    Object param;
                    switch (accessorType) {
                    case GETTER:
                        return getProperty(proxy, propertyDescriptor);
                    case SETTER:
                        param = sanitizeModifierParam(proxy, propertyDescriptor, args[0]);
                        setProperty(proxy, propertyDescriptor, param);
                        return null;
                    case ADDER:
                        if (args.length == 2) {
                            param = sanitizeModifierParam(proxy, propertyDescriptor, args[1]);
                            addToProperty(proxy, (ICollectionPropertyDescriptor<?>) propertyDescriptor,
                                    (Integer) args[0], param);
                        } else {
                            param = sanitizeModifierParam(proxy, propertyDescriptor, args[0]);
                            addToProperty(proxy, (ICollectionPropertyDescriptor<?>) propertyDescriptor, param);
                        }
                        return null;
                    case REMOVER:
                        param = sanitizeModifierParam(proxy, propertyDescriptor, args[0]);
                        removeFromProperty(proxy, (ICollectionPropertyDescriptor<?>) propertyDescriptor, param);
                        return null;
                    default:
                        break;
                    }
                } finally {
                    if (modifierMonitors != null && accessorInfo.isModifier()) {
                        modifierMonitors.remove(methodName);
                    }
                }
            } else if (propertyDescriptor instanceof IStringPropertyDescriptor
                    && ((IStringPropertyDescriptor) propertyDescriptor).isTranslatable()) {
                if (accessorInfo.isModifier()) {
                    if (propertyDescriptor.getName().endsWith(IComponentDescriptor.NLS_SUFFIX)) {
                        invokeNlsSetter(proxy, (IStringPropertyDescriptor) propertyDescriptor,
                                (String) args[0]);
                    } else {
                        invokeNlsOrRawSetter(proxy, (IStringPropertyDescriptor) propertyDescriptor,
                                (String) args[0]);
                    }
                    return null;
                } else {
                    if (propertyDescriptor.getName().endsWith(IComponentDescriptor.NLS_SUFFIX)) {
                        return invokeNlsGetter(proxy, (IStringPropertyDescriptor) propertyDescriptor);
                    } else {
                        return invokeNlsOrRawGetter(proxy, (IStringPropertyDescriptor) propertyDescriptor);
                    }
                }
            } else {
                try {
                    return invokeServiceMethod(proxy, method, args);
                } catch (NoSuchMethodException ignored) {
                    // it will fall back in the general case.
                }
                throw new ComponentException("The '" + propertyDescriptor.getName()
                        + "' property is described as computed but we couldn't determine a way to compute it,"
                        + " either through an extension or a service delegate on the following component : \n"
                        + componentDescriptor.getComponentContract().getName());
            }
        } else {
            try {
                return invokeServiceMethod(proxy, method, args);
            } catch (NoSuchMethodException ignored) {
                // it will fall back in the general case.
            }
        }
        break;
    }
    throw new ComponentException(method.toString() + " is not supported on the component "
            + componentDescriptor.getComponentContract().getName());
}