Example usage for java.lang.reflect Method getParameters

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

Introduction

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

Prototype

public Parameter[] getParameters() 

Source Link

Document

Returns an array of Parameter objects that represent all the parameters to the underlying executable represented by this object.

Usage

From source file:com.phoenixnap.oss.ramlapisync.parser.SpringMvcResourceParser.java

@Override
protected ApiParameterMetadata[] extractResourceIdParameter(Method method) {
    Map<String, ApiParameterMetadata> pathVariables = new HashMap<>();
    for (Parameter param : method.getParameters()) {
        if (isPathParameter(param)) {
            ApiParameterMetadata extractParameterMetadata = new ApiParameterMetadata(param);
            pathVariables.put(extractParameterMetadata.getName(), extractParameterMetadata);
        }/*  w w w. ja v  a2 s.c  o  m*/

    }
    // TODO HASH MAP AND REORDER BY URL
    return pathVariables.values().toArray(new ApiParameterMetadata[pathVariables.size()]);
}

From source file:com.phoenixnap.oss.ramlapisync.parser.SpringMvcResourceParser.java

@Override
protected List<ApiParameterMetadata> getApiParameters(Method method, boolean includeUrlParameters,
        boolean includeNonUrlParameters) {
    List<ApiParameterMetadata> params = new ArrayList<>();
    for (Parameter param : method.getParameters()) {
        boolean nonPathParameter = isNonPathParameter(param);
        ApiParameterMetadata parameterMetadata = new ApiParameterMetadata(param);
        if (parameterMetadata != null) {
            if (nonPathParameter && includeNonUrlParameters) {
                params.add(parameterMetadata);
            } else if (!nonPathParameter && includeUrlParameters) {
                params.add(parameterMetadata);
            }// w  ww .j  a v  a  2 s. c  o m
        }
    }
    return params;
}

From source file:com.phoenixnap.oss.ramlapisync.parser.ResourceParser.java

/**
 * Extracts parameters from a method call and attaches these with the comments extracted from the javadoc
 * //w  w  w  . ja v a 2 s  .c o  m
 * @param apiAction The Verb of the action containing these parametes
 * @param method The method to inspect
 * @param parameterComments The parameter comments associated with these parameters
 * @return A collection of parameters keyed by name
 */
protected Map<String, QueryParameter> extractQueryParameters(ActionType apiAction, Method method,
        Map<String, String> parameterComments) {
    // Since POST requests have a body we choose to keep all request data in one place as much as possible
    if (apiAction.equals(ActionType.POST) || method.getParameterCount() == 0) {
        return Collections.emptyMap();
    }
    Map<String, QueryParameter> queryParams = new LinkedHashMap<>();

    for (Parameter param : method.getParameters()) {
        if (isQueryParameter(param)) { // Lets skip resourceIds since these are going to be going in the URL
            ParamType simpleType = SchemaHelper.mapSimpleType(param.getType());

            if (simpleType == null) {
                queryParams.putAll(SchemaHelper.convertClassToQueryParameters(param,
                        javaDocs.getJavaDoc(param.getType())));
            } else {
                // Check if we have comments
                String paramComment = parameterComments.get(param.getName());
                queryParams.putAll(SchemaHelper.convertParameterToQueryParameter(param, paramComment));
            }
        }
    }
    return queryParams;
}

From source file:guru.qas.martini.jmeter.sampler.MartiniSampler.java

protected SampleResult getSubResult(Step step, Method method, Pattern pattern) {
    String label = getLabel(step);
    SampleResult result = new SampleResult();
    result.setSuccessful(true);/*from ww  w  . j a  v a2s . c o m*/
    result.sampleStart();

    SamplerContext samplerContext = new SamplerContext(super.getThreadContext());

    try {
        ApplicationContext applicationContext = this.getApplicationContext();
        Parameter[] parameters = method.getParameters();
        Object[] arguments = new Object[parameters.length];

        if (parameters.length > 0) {
            String text = step.getText();
            Matcher matcher = pattern.matcher(text);
            checkState(matcher.find(), "unable to locate substitution parameters for pattern %s with input %s",
                    pattern.pattern(), text);

            ConversionService conversionService = applicationContext.getBean(ConversionService.class);

            int groupCount = matcher.groupCount();
            for (int i = 0; i < groupCount; i++) {
                String parameterAsString = matcher.group(i + 1);
                Parameter parameter = parameters[i];
                Class<?> parameterType = parameter.getType();
                Object converted = conversionService.convert(parameterAsString, parameterType);
                arguments[i] = converted;
            }
        }

        samplerContext.setStatus(Status.PASSED);
        Class<?> declaringClass = method.getDeclaringClass();
        Object bean = applicationContext.getBean(declaringClass);
        Object returnValue = method.invoke(bean, arguments);
        if (HttpEntity.class.isInstance(returnValue)) {
            HttpEntity entity = HttpEntity.class.cast(returnValue);
            samplerContext.setHttpEntities(Collections.singleton(entity));
        }
    } catch (Exception e) {
        samplerContext.setStatus(Status.FAILED);
        samplerContext.setException(e);
        result.setSuccessful(false);
        label = "FAIL: " + label;
    } finally {
        result.sampleEnd();
        result.setSampleLabel(label);
    }
    return result;
}

From source file:org.finra.herd.swaggergen.RestControllerProcessor.java

/**
 * Processes a Spring MVC REST controller class that is annotated with RestController. Also collects any required model objects based on parameters and
 * return types of each endpoint into the specified model classes set.
 *
 * @param clazz the class to process//from w ww .j a  va 2s .  com
 *
 * @throws MojoExecutionException if any errors were encountered.
 */
private void processRestControllerClass(Class<?> clazz) throws MojoExecutionException {
    // Get the Java class source information.
    JavaClassSource javaClassSource = sourceMap.get(clazz.getSimpleName());
    if (javaClassSource == null) {
        throw new MojoExecutionException("No source resource found for class \"" + clazz.getName() + "\".");
    }

    Api api = clazz.getAnnotation(Api.class);
    boolean hidden = api != null && api.hidden();

    if ((clazz.getAnnotation(RestController.class) != null) && (!hidden)) {
        log.debug("Processing RestController class \"" + clazz.getName() + "\".");

        // Default the tag name to the simple class name.
        String tagName = clazz.getSimpleName();

        // See if the "Api" annotation exists.
        if (api != null && api.tags().length > 0) {
            // The "Api" annotation was found so use it's configured tag.
            tagName = api.tags()[0];
        } else {
            // No "Api" annotation so try to get the tag name from the class name. If not, we will stick with the default simple class name.
            Matcher matcher = tagPattern.matcher(clazz.getSimpleName());
            if (matcher.find()) {
                // If our class has the form
                tagName = matcher.group("tag");
            }
        }
        log.debug("Using tag name \"" + tagName + "\".");

        // Add the tag and process each method.
        swagger.addTag(new Tag().name(tagName));

        List<Method> methods = Lists.newArrayList(clazz.getDeclaredMethods());
        // Based on the Java 8 doc, getDeclaredMethods() is not guaranteed sorted
        // In order to be sure we generate stable API when the URL's don't change
        // we can give it a sort order based on the first URI hit in the request mapping
        List<Method> outMethods = methods.stream().filter((method) -> {
            RequestMapping rm = method.getAnnotation(RequestMapping.class);
            ApiOperation apiOp = method.getAnnotation(ApiOperation.class);
            return rm != null && // Has RequestMapping
            rm.value().length > 0 && // has at least 1 URI
            rm.method().length > 0 && // has at least 1 HttpMethod
            (apiOp == null || !apiOp.hidden()); // marked as a hidden ApiOperation
        }).sorted(Comparator.comparing(a -> ((Method) a).getAnnotation(RequestMapping.class).value()[0])
                .thenComparing(a -> ((Method) a).getAnnotation(RequestMapping.class).method()[0]))
                .collect(Collectors.toList());

        for (Method method : outMethods) {
            // Get the method source information.
            List<Class<?>> methodParamClasses = new ArrayList<>();
            for (Parameter parameter : method.getParameters()) {
                methodParamClasses.add(parameter.getType());
            }
            MethodSource<JavaClassSource> methodSource = javaClassSource.getMethod(method.getName(),
                    methodParamClasses.toArray(new Class<?>[methodParamClasses.size()]));
            if (methodSource == null) {
                throw new MojoExecutionException("No method source found for class \"" + clazz.getName()
                        + "\" and method name \"" + method.getName() + "\".");
            }

            // Process the REST controller method along with its source information.
            processRestControllerMethod(method, clazz.getAnnotation(RequestMapping.class), tagName,
                    methodSource);
        }
    } else {
        log.debug("Skipping class \"" + clazz.getName()
                + "\" because it is either not a RestController or it is hidden.");
    }
}

From source file:com.strider.datadefender.DatabaseAnonymizer.java

/**
 * Calls the anonymization function for the given Column, and returns its
 * anonymized value./* w w  w  .  j ava 2s . c o m*/
 * 
 * @param dbConn
 * @param row
 * @param column
 * @return
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException 
 */
private Object callAnonymizingFunctionWithParameters(final Connection dbConn, final ResultSet row,
        final Column column, final String vendor) throws SQLException, NoSuchMethodException, SecurityException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    final String function = column.getFunction();
    if (function == null || function.equals("")) {
        log.warn("Function is not defined for column [" + column + "]. Moving to the next column.");
        return "";
    }

    try {
        final String className = Utils.getClassName(function);
        final String methodName = Utils.getMethodName(function);
        final Class<?> clazz = Class.forName(className);

        final CoreFunctions instance = (CoreFunctions) Class.forName(className).newInstance();
        instance.setDatabaseConnection(dbConn);
        instance.setVendor(vendor);

        final List<Parameter> parms = column.getParameters();
        final Map<String, Object> paramValues = new HashMap<>(parms.size());
        final String columnValue = row.getString(column.getName());

        for (final Parameter param : parms) {
            if (param.getValue().equals("@@value@@")) {
                paramValues.put(param.getName(), columnValue);
            } else if (param.getValue().equals("@@row@@") && param.getType().equals("java.sql.ResultSet")) {
                paramValues.put(param.getName(), row);
            } else {
                paramValues.put(param.getName(), param.getTypeValue());
            }
        }

        final List<Object> fnArguments = new ArrayList<>(parms.size());
        final Method[] methods = clazz.getMethods();
        Method selectedMethod = null;

        methodLoop: for (final Method m : methods) {
            if (m.getName().equals(methodName) && m.getReturnType() == String.class) {

                log.debug("  Found method: " + m.getName());
                log.debug("  Match w/: " + paramValues);

                final java.lang.reflect.Parameter[] mParams = m.getParameters();
                fnArguments.clear();
                for (final java.lang.reflect.Parameter par : mParams) {
                    //log.debug("    Name present? " + par.isNamePresent());
                    // Note: requires -parameter compiler flag
                    log.debug("    Real param: " + par.getName());
                    if (!paramValues.containsKey(par.getName())) {
                        continue methodLoop;
                    }

                    final Object value = paramValues.get(par.getName());
                    Class<?> fnParamType = par.getType();
                    final Class<?> confParamType = (value == null) ? fnParamType : value.getClass();

                    if (fnParamType.isPrimitive() && value == null) {
                        continue methodLoop;
                    }
                    if (ClassUtils.isPrimitiveWrapper(confParamType)) {
                        if (!ClassUtils.isPrimitiveOrWrapper(fnParamType)) {
                            continue methodLoop;
                        }
                        fnParamType = ClassUtils.primitiveToWrapper(fnParamType);
                    }
                    if (!fnParamType.equals(confParamType)) {
                        continue methodLoop;
                    }
                    fnArguments.add(value);
                }

                // actual parameters check less than xml defined parameters size, because values could be auto-assigned (like 'values' and 'row' params)
                if (fnArguments.size() != mParams.length || fnArguments.size() < paramValues.size()) {
                    continue;
                }

                selectedMethod = m;
                break;
            }
        }

        if (selectedMethod == null) {
            final StringBuilder s = new StringBuilder("Anonymization method: ");
            s.append(methodName).append(" with parameters matching (");
            String comma = "";
            for (final Parameter p : parms) {
                s.append(comma).append(p.getType()).append(' ').append(p.getName());
                comma = ", ";
            }
            s.append(") was not found in class ").append(className);
            throw new NoSuchMethodException(s.toString());
        }

        log.debug("Anonymizing function: " + methodName + " with parameters: "
                + Arrays.toString(fnArguments.toArray()));
        final Object anonymizedValue = selectedMethod.invoke(instance, fnArguments.toArray());
        if (anonymizedValue == null) {
            return null;
        }
        return anonymizedValue.toString();

    } catch (InstantiationException | ClassNotFoundException ex) {
        log.error(ex.toString());
    }

    return "";
}

From source file:easyrpc.server.serialization.jsonrpc.JSONCallee.java

@Override
public byte[] matchMethod(Object object, byte[] callInfo) {
    try {/*from   w w  w .j a v a  2 s.  c o  m*/
        Object returnedObject = null;
        ObjectNode call = (ObjectNode) MAPPER.readTree(callInfo);

        String jsonrpc = call.get("jsonrpc").textValue();
        if (jsonrpc == null || !"2.0".equals(jsonrpc)) {
            throw new SerializationException(
                    "'jsonrpc' value must be '2.0' and actually is: '" + jsonrpc + "'");
        }

        String methodName = call.get("method").textValue();
        if (methodName == null)
            throw new SerializationException("The 'method' field must not be null: " + call.toString());

        Class iface = object.getClass();
        for (Method m : iface.getMethods()) {
            if (methodName.equals(m.getName())) {
                ArrayNode jsParams = (ArrayNode) call.get("params");
                if (jsParams == null || jsParams.size() == 0) {
                    try {
                        returnedObject = m.invoke(object);
                        //                            System.out.println("returnedObject = " + returnedObject);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return returnJsonRpcError(call.get("id"), e);
                    }
                } else {
                    //                        System.out.println("methodName = " + methodName);
                    Object[] params = new Object[jsParams.size()];
                    for (int i = 0; i < params.length; i++) {
                        params[i] = MAPPER.convertValue(jsParams.get(i), m.getParameters()[i].getType());
                        //                            System.out.println("params[i] = " + params[i] + "("+ params[i].getClass().getName() +")");
                    }
                    try {
                        returnedObject = m.invoke(object, params);
                        //                            System.out.println("returnedObject = " + returnedObject);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return returnJsonRpcError(call.get("id"), e);
                    }
                }
                break;
            }
        }
        ObjectNode jsret = JsonNodeFactory.instance.objectNode();
        jsret.put("jsonrpc", "2.0");
        jsret.put("id", call.get("id").toString());
        if (returnedObject != null) {
            addResult(jsret, returnedObject);
        }

        //            System.out.println("jsret.toString() = " + jsret.toString());
        return jsret.toString().getBytes();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.structr.core.entity.SchemaMethod.java

private boolean getSignature(final Class type, final String methodName, final ActionEntry entry) {

    // superclass is AbstractNode
    for (final Method method : type.getMethods()) {

        if (methodName.equals(method.getName()) && (method.getModifiers() & Modifier.STATIC) == 0) {

            final Type[] parameterTypes = method.getGenericParameterTypes();
            final Type returnType = method.getGenericReturnType();
            final List<Type> types = new LinkedList<>();

            // compile list of types to check for generic type parameter
            types.addAll(Arrays.asList(parameterTypes));
            types.add(returnType);//from   w ww . j  a  v  a 2s . co  m

            final String genericTypeParameter = getGenericMethodParameter(types, method);

            // check for generic return type, and if the method defines its own generic type
            if (returnType instanceof TypeVariable
                    && ((TypeVariable) returnType).getGenericDeclaration().equals(method)) {

                // method defines its own generic type
                entry.setReturnType(genericTypeParameter + returnType.getTypeName());

            } else {

                // non-generic return type
                final Class returnClass = method.getReturnType();
                if (returnClass.isArray()) {

                    entry.setReturnType(genericTypeParameter + returnClass.getComponentType().getName() + "[]");

                } else {

                    entry.setReturnType(genericTypeParameter + method.getReturnType().getName());
                }
            }

            for (final Parameter parameter : method.getParameters()) {

                String typeName = parameter.getParameterizedType().getTypeName();
                String name = parameter.getType().getSimpleName();

                if (typeName.contains("$")) {
                    typeName = typeName.replace("$", ".");
                }

                entry.addParameter(typeName, parameter.getName());
            }

            for (final Class exception : method.getExceptionTypes()) {
                entry.addException(exception.getName());
            }

            entry.setOverrides(getProperty(overridesExisting));
            entry.setCallSuper(getProperty(callSuper));

            // success
            return true;
        }
    }

    return false;
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Finds the setter method from the declaring class suitable to set a
 * value for the field.//  w  w w  . ja  v  a2  s . c om
 *
 * @author paouelle
 *
 * @param  declaringClass the non-<code>null</code> class declaring the field
 * @return the setter method for the field or <code>null</code> if none found
 * @throws IllegalArgumentException if unable to find a suitable setter
 */
private Method findSetterMethod(Class<?> declaringClass) {
    final String mname = "set" + WordUtils.capitalize(name, '_', '-');

    try {
        final Method m = declaringClass.getDeclaredMethod(mname, type);
        final int mods = m.getModifiers();

        if (Modifier.isAbstract(mods) || Modifier.isStatic(mods)) {
            return null;
        }
        org.apache.commons.lang3.Validate.isTrue(m.getParameterCount() == 1,
                "expecting setter for field '%s' with one parameter", field);
        final Class<?> wtype = ClassUtils.primitiveToWrapper(type);
        final Class<?> wptype = ClassUtils.primitiveToWrapper(DataTypeImpl.unwrapOptionalIfPresent(
                m.getParameterTypes()[0], m.getParameters()[0].getParameterizedType()));

        org.apache.commons.lang3.Validate.isTrue(wtype.isAssignableFrom(wptype),
                "expecting setter for field '%s' with parameter type: %s", field, type.getName());
        m.setAccessible(true);
        return m;
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:io.stallion.restfulEndpoints.ResourceToEndpoints.java

public List<JavaRestEndpoint> convert(EndpointResource resource) {
    Class cls = resource.getClass();
    List<JavaRestEndpoint> endpoints = new ArrayList<>();

    // Get defaults from the resource

    Role defaultMinRole = Settings.instance().getUsers().getDefaultEndpointRoleObj();
    MinRole minRoleAnno = (MinRole) cls.getAnnotation(MinRole.class);
    if (minRoleAnno != null) {
        defaultMinRole = minRoleAnno.value();
    }//from   w  ww.  j a  va2s  .  c om

    String defaultProduces = "text/html";
    Produces producesAnno = (Produces) cls.getAnnotation(Produces.class);
    if (producesAnno != null && producesAnno.value().length > 0) {
        defaultProduces = producesAnno.value()[0];
    }

    Path pathAnno = (Path) cls.getAnnotation(Path.class);
    if (pathAnno != null) {
        basePath += pathAnno.value();
    }

    Class defaultJsonViewClass = null;
    DefaultJsonView jsonView = (DefaultJsonView) cls.getAnnotation(DefaultJsonView.class);
    if (jsonView != null) {
        defaultJsonViewClass = jsonView.value();
    }

    for (Method method : cls.getDeclaredMethods()) {
        JavaRestEndpoint endpoint = new JavaRestEndpoint();
        endpoint.setRole(defaultMinRole);
        endpoint.setProduces(defaultProduces);
        if (defaultJsonViewClass != null) {
            endpoint.setJsonViewClass(defaultJsonViewClass);
        }

        Log.finer("Resource class method: {0}", method.getName());
        for (Annotation anno : method.getDeclaredAnnotations()) {
            if (Path.class.isInstance(anno)) {
                Path pth = (Path) anno;
                endpoint.setRoute(getBasePath() + pth.value());
            } else if (GET.class.isInstance(anno)) {
                endpoint.setMethod("GET");
            } else if (POST.class.isInstance(anno)) {
                endpoint.setMethod("POST");
            } else if (DELETE.class.isInstance(anno)) {
                endpoint.setMethod("DELETE");
            } else if (PUT.class.isInstance(anno)) {
                endpoint.setMethod("PUT");
            } else if (Produces.class.isInstance(anno)) {
                endpoint.setProduces(((Produces) anno).value()[0]);
            } else if (MinRole.class.isInstance(anno)) {
                endpoint.setRole(((MinRole) anno).value());
            } else if (XSRF.class.isInstance(anno)) {
                endpoint.setCheckXSRF(((XSRF) anno).value());
            } else if (JsonView.class.isInstance(anno)) {
                Class[] classes = ((JsonView) anno).value();
                if (classes == null || classes.length != 1) {
                    throw new UsageException("JsonView annotation for method " + method.getName()
                            + " must have exactly one view class");
                }
                endpoint.setJsonViewClass(classes[0]);
            }
        }
        if (!empty(endpoint.getMethod()) && !empty(endpoint.getRoute())) {
            endpoint.setJavaMethod(method);
            endpoint.setResource(resource);
            endpoints.add(endpoint);
            Log.fine("Register endpoint {0} {1}", endpoint.getMethod(), endpoint.getRoute());
        } else {
            continue;
        }
        int x = -1;
        for (Parameter param : method.getParameters()) {
            x++;
            RequestArg arg = new RequestArg();
            for (Annotation anno : param.getAnnotations()) {
                arg.setAnnotationInstance(anno);
                Log.finer("Param Annotation is: {0}, {1}", anno, anno.getClass().getName());
                if (BodyParam.class.isInstance(anno)) {
                    BodyParam bodyAnno = (BodyParam) (anno);
                    arg.setType("BodyParam");
                    if (empty(bodyAnno.value())) {
                        arg.setName(param.getName());
                    } else {
                        arg.setName(((BodyParam) anno).value());
                    }
                    arg.setAnnotationClass(BodyParam.class);
                    arg.setRequired(bodyAnno.required());
                    arg.setEmailParam(bodyAnno.isEmail());
                    arg.setMinLength(bodyAnno.minLength());
                    arg.setAllowEmpty(bodyAnno.allowEmpty());
                    if (!empty(bodyAnno.validationPattern())) {
                        arg.setValidationPattern(Pattern.compile(bodyAnno.validationPattern()));
                    }
                } else if (ObjectParam.class.isInstance(anno)) {
                    ObjectParam oParam = (ObjectParam) anno;
                    arg.setType("ObjectParam");
                    arg.setName("noop");
                    if (oParam.targetClass() == null || oParam.targetClass().equals(Object.class)) {
                        arg.setTargetClass(param.getType());
                    } else {
                        arg.setTargetClass(oParam.targetClass());
                    }
                    arg.setAnnotationClass(ObjectParam.class);
                } else if (MapParam.class.isInstance(anno)) {
                    arg.setType("MapParam");
                    arg.setName("noop");
                    arg.setAnnotationClass(MapParam.class);
                } else if (QueryParam.class.isInstance(anno)) {
                    arg.setType("QueryParam");
                    arg.setName(((QueryParam) anno).value());
                    arg.setAnnotationClass(QueryParam.class);
                } else if (PathParam.class.isInstance(anno)) {
                    arg.setType("PathParam");
                    arg.setName(((PathParam) anno).value());
                    arg.setAnnotationClass(PathParam.class);
                } else if (DefaultValue.class.isInstance(anno)) {
                    arg.setDefaultValue(((DefaultValue) anno).value());
                } else if (NotNull.class.isInstance(anno)) {
                    arg.setRequired(true);
                } else if (Nullable.class.isInstance(anno)) {
                    arg.setRequired(false);
                } else if (NotEmpty.class.isInstance(anno)) {
                    arg.setRequired(true);
                    arg.setAllowEmpty(false);
                } else if (Email.class.isInstance(anno)) {
                    arg.setEmailParam(true);
                }
            }
            if (StringUtils.isEmpty(arg.getType())) {
                arg.setType("ObjectParam");
                arg.setName(param.getName());
                arg.setTargetClass(param.getType());
                arg.setAnnotationClass(ObjectParam.class);
            }

            if (StringUtils.isEmpty(arg.getName())) {
                arg.setName(param.getName());
            }
            endpoint.getArgs().add(arg);
        }
    }
    return endpoints;
}