Example usage for java.lang.reflect Method getParameterAnnotations

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

Introduction

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

Prototype

@Override
public Annotation[][] getParameterAnnotations() 

Source Link

Usage

From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java

private EntityModel createWrapperEntity(String name, Method method, RegistryNodeModel registryNodeModel,
        boolean request, List<RelationshipModel> relationships, Map<String, EntityModel> models,
        Service service) {/*w  w w .  j  av  a  2 s.  c  o  m*/
    EntityModel model = models.get(name);
    if (model != null)
        return model;

    String modelName = name.replaceAll("\\B([A-Z]+)\\B", " $1");

    EntityModel entityModel = new EntityModel();
    entityModel.setName(modelName);
    entityModel.setLookup(DiffUtils.lookup(registryNodeModel.getLookup(), modelName));
    entityModel.setPath(registryNodeModel.getLookup());
    entityModel.setAbstractEntity(false);
    entityModel.setTypeEntity(true);
    entityModel.setReverseEngineer(true);
    entityModel.setProtocol(EntityProtocol.HTTP);
    entityModel.setParent(registryNodeModel);

    models.put(name, entityModel);

    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    Type[] parameterTypes = method.getGenericParameterTypes();
    List<FieldModel> fields = new ArrayList<FieldModel>(parameterTypes.length);

    for (int i = 0; i < parameterTypes.length; i++) {
        Annotation[] annotations = parameterAnnotations[i];
        for (Annotation annotation : annotations) {
            if (WebParam.class.isInstance(annotation)) {
                WebParam param = (WebParam) annotation;
                if (param.mode() == INOUT || request && param.mode() == IN || !request && param.mode() == OUT) {
                    analyzeField(param.name(), parameterTypes[i], TYPE, entityModel, null, models,
                            relationships, fields);
                    analyzeField(param.name(), parameterTypes[i], param.mode(), false, false, false, service);
                }
                break;
            }
        }
    }

    Type returnType = method.getGenericReturnType();
    if (!request && void.class != returnType) {
        analyzeField(RETURN, returnType, TYPE, entityModel, null, models, relationships, fields);
        analyzeField(RETURN, returnType, null, false, false, true, service);
    }

    entityModel.setFields(fields);

    return entityModel;
}

From source file:com.amazonaws.hal.client.HalResourceInvocationHandler.java

/**
 *///from w ww . j  a  v a 2s  .c o m
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (halResource == null || !halResource.isDefined()) {
        halResource = halClient.getHalResource(resourcePath);
    }

    try {
        Method resourceInfoMethod = ResourceInfo.class.getMethod(method.getName(), method.getParameterTypes());

        return resourceInfoMethod.invoke(halResource, args);
    } catch (NoSuchMethodException ignore) {
        // If the method is not defined in ResourceInfo, we handle it below
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }

    Link link;
    if ((link = method.getAnnotation(Link.class)) != null) {
        switch (link.method()) {
        case GET:
            if (List.class.isAssignableFrom(method.getReturnType())) {
                //noinspection unchecked
                return new HalLinkList(halResource, link.relation(),
                        (Class) getCollectionType(method.getGenericReturnType(), 0, ResourceInfo.class),
                        halClient);
            } else if (Map.class.isAssignableFrom(method.getReturnType())) {
                //noinspection unchecked
                return new HalLinkMap(halResource, link.relation(), link.keyField(),
                        (Class) getCollectionType(method.getGenericReturnType(), 1, ResourceInfo.class),
                        halClient);
            } else {
                return halClient.getResource(halResource, method.getReturnType(), getRelationHref(link,
                        args == null ? EMPTY_ARGS : args, method.getParameterAnnotations()), false);
            }

        case POST:
            if (args == null) {
                throw new IllegalArgumentException("POST operations require a representation argument.");
            }

            return halClient.postResource(method.getReturnType(),
                    getRelationHref(link, args, method.getParameterAnnotations()), args[0]);

        case PUT:
            if (args == null) {
                throw new IllegalArgumentException("PUT operations require a representation argument.");
            }

            return halClient.putResource(method.getReturnType(),
                    getRelationHref(link, args, method.getParameterAnnotations()), args[0]);

        case DELETE:
            return halClient.deleteResource(method.getReturnType(),
                    getRelationHref(link, args == null ? EMPTY_ARGS : args, method.getParameterAnnotations()));

        default:
            throw new UnsupportedOperationException("Unexpected HTTP method: " + link.method());
        }

    } else if (method.getName().startsWith("get")) {
        String propertyName = getPropertyName(method.getName());
        Object property = halResource.getProperty(propertyName);
        Type returnType = method.getGenericReturnType();

        // When a value is accessed, it's intended type can either be a
        // class or some other type (like a ParameterizedType).
        //
        // If the target type is a class and the value is of that type,
        // we return it.  If the value is not of that type, we convert
        // it and store the converted value (trusting it was converted
        // properly) back to the backing store.
        //
        // If the target type is not a class, it may be ParameterizedType
        // like List<T> or Map<K, V>.  We check if the value is already
        // a converting type and if so, we return it.  If the value is
        // not, we convert it and if it's now a converting type, we store
        // the new value in the backing store.

        if (returnType instanceof Class) {
            if (!((Class) returnType).isInstance(property)) {
                property = convert(returnType, property);

                //noinspection unchecked
                halResource.addProperty(propertyName, property);
            }
        } else {
            if (!(property instanceof ConvertingMap) && !(property instanceof ConvertingList)) {
                property = convert(returnType, property);

                if (property instanceof ConvertingMap || property instanceof ConvertingList) {
                    //noinspection unchecked
                    halResource.addProperty(propertyName, property);
                }
            }
        }

        return property;
    } else if (method.getName().equals("toString") && args == null) {
        return resourcePath;
    } else if (method.getName().equals("equals") && args != null && args.length == 1) {
        HalResourceInvocationHandler other;

        try {
            other = (HalResourceInvocationHandler) Proxy.getInvocationHandler(args[0]);
        } catch (IllegalArgumentException e) {
            // argument is not a proxy
            return false;
        } catch (ClassCastException e) {
            // argument is the wrong type of proxy
            return false;
        }

        return resourcePath.equals(other.resourcePath);
    } else if (method.getName().equals("hashCode") && args == null) {
        return resourcePath.hashCode();
    }

    throw new UnsupportedOperationException("Don't know how to handle '" + method.getName() + "'");
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private void initAnnotatedActionMethods(String className, Class<?> clazz) {
    for (Method method : HELPER.getBeanMethods(clazz)) {
        List<Arg> arguments = new ArrayList<>();

        for (Annotation[] annotations : method.getParameterAnnotations()) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof Arg) {
                    arguments.add((Arg) annotation);
                }/*  ww w . j av a  2s . c  o m*/
            }
        }

        if (method.isAnnotationPresent(Function.class)) {
            AnnotatedFunction annotatedFunction = new AnnotatedFunction(method, className, arguments);

            // Keep track of functions per bean method
            beanMethodFunctions.put(String.format(BEAN_METHOD_NAME_FORMAT, className, method.getName()),
                    annotatedFunction);

            List<String> urlPaths = HELPER.cleanPaths(annotatedFunction.getFunction().forPaths());

            for (String urlPath : urlPaths) {
                List<AnnotatedFunction> pathFunctions = annotatedFunctions.get(urlPath);
                if (pathFunctions == null) {
                    pathFunctions = new ArrayList<>();
                    annotatedFunctions.put(urlPath, pathFunctions);
                }
                pathFunctions.add(annotatedFunction);
            }
        }

        if (method.isAnnotationPresent(Action.class)) {
            AnnotatedAction annotatedAction = new AnnotatedAction(method, className, arguments);
            for (String id : annotatedAction.getAction().forIds()) {
                annotatedActions.put(id, annotatedAction);
            }
        }
    }
}

From source file:de.cubeisland.engine.core.webapi.ApiServer.java

public void registerApiHandlers(final Module owner, final Object holder) {
    expectNotNull(holder, "The API holder must not be null!");

    for (Method method : holder.getClass().getDeclaredMethods()) {
        Action aAction = method.getAnnotation(Action.class);
        if (aAction != null) {
            String route = aAction.value();
            if (route.isEmpty()) {
                route = StringUtils.deCamelCase(method.getName(), "/");
            }/*from www.  j a v  a2  s.co  m*/
            route = owner.getId() + "/" + route;
            route = HttpRequestHandler.normalizePath(route);
            de.cubeisland.engine.core.permission.Permission perm = null;
            if (aAction.needsAuth()) {
                perm = owner.getBasePermission().childWildcard("webapi");
                if (method.isAnnotationPresent(ApiPermission.class)) {
                    ApiPermission apiPerm = method.getAnnotation(ApiPermission.class);
                    if (apiPerm.value().isEmpty()) {
                        perm = perm.child(route, apiPerm.permDefault());
                    } else {
                        perm = perm.child(apiPerm.value(), apiPerm.permDefault());
                    }
                } else {
                    perm = perm.child(route, PermDefault.DEFAULT);
                }
            }
            LinkedHashMap<String, Class> params = new LinkedHashMap<>();
            Class<?>[] types = method.getParameterTypes();
            Annotation[][] paramAnnotations = method.getParameterAnnotations();
            for (int i = 1; i < types.length; i++) {
                Class<?> type = types[i];
                Value val = null;
                for (Annotation annotation : paramAnnotations[i]) {
                    if (annotation instanceof Value) {
                        val = (Value) annotation;
                        break;
                    }
                }
                if (val == null) {
                    throw new IllegalArgumentException("Missing Value Annotation for Additional Parameters");
                }
                if (params.put(val.value(), type) != null) {
                    throw new IllegalArgumentException("Duplicate value in Value Annotation");
                }
            }
            RequestMethod reqMethod = RequestMethod.GET;
            if (method.isAnnotationPresent(de.cubeisland.engine.core.webapi.Method.class)) {
                reqMethod = method.getAnnotation(de.cubeisland.engine.core.webapi.Method.class).value();
            }
            this.handlers.put(route,
                    new ReflectedApiHandler(owner, route, perm, params, reqMethod, method, holder));
        }
    }
}

From source file:com.vmware.photon.controller.swagger.resources.SwaggerJsonListing.java

/**
 * Gets all of the operation data for a method, such as http method, documentation, parameters, response class, etc.
 *
 * @param models       The hashmap of models that are being documented so that they can be referenced by swagger-ui.
 * @param method       The method to document.
 * @param parentParams The parameters of parent resources, so that they can be documented by subresources.
 * @return A SwaggerOperation API representation.
 *///from  w ww  . j  a  v  a 2 s  . com
private SwaggerOperation getOperation(HashMap<String, SwaggerModel> models, ResourceMethod method,
        List<SwaggerParameter> parentParams) {
    Method definitionMethod = method.getInvocable().getDefinitionMethod();
    SwaggerOperation operation = new SwaggerOperation();

    // If there is no @ApiOperation on a method we still document it because it's possible that the return class of
    // this method is a resource class with @Api and @ApiOperation on methods.
    ApiOperation apiOperation = definitionMethod.getAnnotation(ApiOperation.class);
    if (apiOperation != null) {
        operation.setSummary(apiOperation.value());
        operation.setNotes(apiOperation.notes());
        Class<?> responseClass = apiOperation.response().equals(Void.class) ? definitionMethod.getReturnType()
                : apiOperation.response();
        if (StringUtils.isNotBlank(apiOperation.responseContainer())) {
            operation.setResponseClass(addListModel(models, responseClass, apiOperation.responseContainer()));
        } else {
            operation.setResponseClass(
                    getTypeName(models, responseClass, definitionMethod.getGenericReturnType()));
        }

        addModel(models, responseClass);
    }

    operation.setHttpMethod(parseHttpOperation(definitionMethod));
    operation.setNickname(definitionMethod.getName());

    // In this block we get all of the parameters to the method and convert them to SwaggerParameter types. We
    // introspect the generic types.
    List<SwaggerParameter> swaggerParameters = new ArrayList<>();
    Class[] parameterTypes = definitionMethod.getParameterTypes();
    Type[] genericParameterTypes = definitionMethod.getGenericParameterTypes();
    Annotation[][] parameterAnnotations = definitionMethod.getParameterAnnotations();
    for (int i = 0; i < parameterTypes.length; i++) {
        Class parameter = parameterTypes[i];

        Type genericParameterType = genericParameterTypes[i];
        if (genericParameterType instanceof Class
                && "javax.ws.rs.core.Request".equals(((Class) genericParameterType).getName())) {
            continue;
        }

        SwaggerParameter swaggerParameter = parameterToSwaggerParameter(models, parameter, genericParameterType,
                parameterAnnotations[i]);
        swaggerParameters.add(swaggerParameter);
        // Add this parameter to the list of model documentation.
        addModel(models, parameter);
    }
    swaggerParameters.addAll(parentParams);
    operation.setParameters(swaggerParameters);
    return operation;
}

From source file:org.codehaus.enunciate.modules.rest.RESTOperation.java

/**
 * Construct a REST operation./*from   w  w w . j  a va2  s  .c  om*/
 *
 * @param resource The resource for this operation.
 * @param contentType The content type of the operation.
 * @param verb     The verb for the operation.
 * @param method   The method.
 * @param parameterNames The parameter names.
 */
protected RESTOperation(RESTResource resource, String contentType, VerbType verb, Method method,
        String[] parameterNames) {
    this.resource = resource;
    this.verb = verb;
    this.method = method;
    this.contentType = contentType;

    int properNounIndex = -1;
    Class properNoun = null;
    Boolean properNounOptional = null;
    int nounValueIndex = -1;
    Class nounValue = null;
    Boolean nounValueOptional = Boolean.FALSE;
    int contentTypeParameterIndex = -1;
    adjectiveTypes = new HashMap<String, Class>();
    adjectiveIndices = new HashMap<String, Integer>();
    adjectivesOptional = new HashMap<String, Boolean>();
    complexAdjectives = new ArrayList<String>();
    contextParameterTypes = new HashMap<String, Class>();
    contextParameterIndices = new HashMap<String, Integer>();
    Class[] parameterTypes = method.getParameterTypes();
    HashSet<Class> contextClasses = new HashSet<Class>();
    for (int i = 0; i < parameterTypes.length; i++) {
        Class parameterType = Collection.class.isAssignableFrom(parameterTypes[i])
                ? getCollectionTypeAsArrayType(method, i)
                : parameterTypes[i];

        boolean isAdjective = true;
        String adjectiveName = "arg" + i;
        if ((parameterNames != null) && (parameterNames.length > i) && (parameterNames[i] != null)) {
            adjectiveName = parameterNames[i];
        }
        boolean adjectiveOptional = !parameterType.isPrimitive();
        boolean adjectiveComplex = false;
        Annotation[] parameterAnnotations = method.getParameterAnnotations()[i];
        for (Annotation annotation : parameterAnnotations) {
            if (annotation instanceof ProperNoun) {
                if (parameterType.isArray()) {
                    throw new IllegalStateException(
                            "Proper nouns must be simple types, found an array or collection for parameter " + i
                                    + " of method " + method.getDeclaringClass().getName() + "."
                                    + method.getName() + ".");
                } else if (properNoun == null) {
                    ProperNoun properNounInfo = (ProperNoun) annotation;
                    if (properNounInfo.optional()) {
                        if (parameterType.isPrimitive()) {
                            throw new IllegalStateException(
                                    "An optional proper noun cannot be a primitive type for method "
                                            + method.getDeclaringClass().getName() + "." + method.getName()
                                            + ".");
                        }

                        properNounOptional = true;
                    }

                    if (!properNounInfo.converter().equals(ProperNoun.DEFAULT.class)) {
                        try {
                            ConvertUtils.register((Converter) properNounInfo.converter().newInstance(),
                                    parameterType);
                        } catch (ClassCastException e) {
                            throw new IllegalArgumentException("Illegal converter class for method "
                                    + method.getDeclaringClass().getName() + "." + method.getName()
                                    + ". Must be an instance of org.apache.commons.beanutils.Converter.");
                        } catch (Exception e) {
                            throw new IllegalArgumentException("Unable to instantiate converter class "
                                    + properNounInfo.converter().getName() + " on method "
                                    + method.getDeclaringClass().getName() + "." + method.getName() + ".", e);
                        }
                    }

                    properNoun = parameterType;
                    properNounIndex = i;
                    isAdjective = false;
                    break;
                } else {
                    throw new IllegalStateException("There are two proper nouns for method "
                            + method.getDeclaringClass().getName() + "." + method.getName() + ".");
                }
            } else if (annotation instanceof NounValue) {
                if ((!parameterType.isAnnotationPresent(XmlRootElement.class))
                        && (!parameterType.equals(DataHandler.class)) && (!(parameterType.isArray()
                                && parameterType.getComponentType().equals(DataHandler.class)))) {
                    LOG.warn(
                            "Enunciate doesn't support unmarshalling objects of type " + parameterType.getName()
                                    + ". Unless a custom content type handler is provided, this operation ("
                                    + method.getDeclaringClass() + "." + method.getName() + ") will fail.");
                }

                if (nounValue == null) {
                    if (((NounValue) annotation).optional()) {
                        if (parameterType.isPrimitive()) {
                            throw new IllegalStateException(
                                    "An optional noun value cannot be a primitive type for method "
                                            + method.getDeclaringClass().getName() + "." + method.getName()
                                            + ".");
                        }

                        nounValueOptional = true;
                    }

                    nounValue = parameterType;
                    nounValueIndex = i;
                    isAdjective = false;
                    break;
                } else {
                    throw new IllegalStateException("There are two proper nouns for method "
                            + method.getDeclaringClass().getName() + "." + method.getName() + ".");
                }
            } else if (annotation instanceof ContextParameter) {
                ContextParameter contextParameterInfo = (ContextParameter) annotation;
                String contextParameterName = contextParameterInfo.value();

                if (!contextParameterInfo.converter().equals(ContextParameter.DEFAULT.class)) {
                    try {
                        ConvertUtils.register((Converter) contextParameterInfo.converter().newInstance(),
                                parameterType);
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException("Illegal converter class for method "
                                + method.getDeclaringClass().getName() + "." + method.getName()
                                + ". Must be an instance of org.apache.commons.beanutils.Converter.");
                    } catch (Exception e) {
                        throw new IllegalArgumentException(
                                "Unable to instantiate converter class "
                                        + contextParameterInfo.converter().getName() + " on method "
                                        + method.getDeclaringClass().getName() + "." + method.getName() + ".",
                                e);
                    }
                }

                contextParameterTypes.put(contextParameterName, parameterType);
                contextParameterIndices.put(contextParameterName, i);
                isAdjective = false;
                break;
            } else if (annotation instanceof ContentTypeParameter) {
                contentTypeParameterIndex = i;
                isAdjective = false;
                break;
            } else if (annotation instanceof Adjective) {
                Adjective adjectiveInfo = (Adjective) annotation;
                adjectiveOptional = adjectiveInfo.optional();
                if (adjectiveOptional && parameterType.isPrimitive()) {
                    throw new IllegalStateException(
                            "An optional adjective cannot be a primitive type for method "
                                    + method.getDeclaringClass().getName() + "." + method.getName() + ".");
                }

                if (!"##default".equals(adjectiveInfo.name())) {
                    adjectiveName = adjectiveInfo.name();
                }

                adjectiveComplex = adjectiveInfo.complex();

                if (!adjectiveInfo.converter().equals(Adjective.DEFAULT.class)) {
                    try {
                        ConvertUtils.register((Converter) adjectiveInfo.converter().newInstance(),
                                parameterType);
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException("Illegal converter class for method "
                                + method.getDeclaringClass().getName() + "." + method.getName()
                                + ". Must be an instance of org.apache.commons.beanutils.Converter.");
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Unable to instantiate converter class "
                                + adjectiveInfo.converter().getName() + " on method "
                                + method.getDeclaringClass().getName() + "." + method.getName() + ".", e);
                    }
                }

                break;
            }
        }

        if (isAdjective) {
            this.adjectiveTypes.put(adjectiveName, parameterType);
            this.adjectiveIndices.put(adjectiveName, i);
            this.adjectivesOptional.put(adjectiveName, adjectiveOptional);
            if (adjectiveComplex) {
                this.complexAdjectives.add(adjectiveName);
            }
        }

        if (parameterType.isArray()) {
            contextClasses.add(parameterType.getComponentType());
        } else {
            contextClasses.add(parameterType);
        }
    }

    Class returnType = null;
    if (!Void.TYPE.equals(method.getReturnType())) {
        returnType = method.getReturnType();

        if (!returnType.isAnnotationPresent(XmlRootElement.class)
                && (!DataHandler.class.isAssignableFrom(returnType))) {
            LOG.warn("Enunciate doesn't support marshalling objects of type " + returnType.getName()
                    + ". Unless a custom content type handler is provided, this operation ("
                    + method.getDeclaringClass() + "." + method.getName() + ") will fail.");
        }

        contextClasses.add(returnType);
    }

    for (Class exceptionClass : method.getExceptionTypes()) {
        for (Method exceptionMethod : exceptionClass.getMethods()) {
            if ((exceptionMethod.isAnnotationPresent(RESTErrorBody.class))
                    && (exceptionMethod.getReturnType() != Void.TYPE)) {
                //add the error body to the context classes.
                contextClasses.add(exceptionMethod.getReturnType());
            }
        }
    }

    //now load any additional context classes as specified by @RESTSeeAlso
    if (method.isAnnotationPresent(RESTSeeAlso.class)) {
        contextClasses.addAll(Arrays.asList(method.getAnnotation(RESTSeeAlso.class).value()));
    }
    if (method.getDeclaringClass().isAnnotationPresent(RESTSeeAlso.class)) {
        contextClasses
                .addAll(Arrays.asList(method.getDeclaringClass().getAnnotation(RESTSeeAlso.class).value()));
    }
    if ((method.getDeclaringClass().getPackage() != null)
            && (method.getDeclaringClass().getPackage().isAnnotationPresent(RESTSeeAlso.class))) {
        contextClasses.addAll(Arrays
                .asList(method.getDeclaringClass().getPackage().getAnnotation(RESTSeeAlso.class).value()));
    }

    String jsonpParameter = null;
    JSONP jsonpInfo = method.getAnnotation(JSONP.class);
    if (jsonpInfo == null) {
        jsonpInfo = method.getDeclaringClass().getAnnotation(JSONP.class);
        if (jsonpInfo == null) {
            jsonpInfo = method.getDeclaringClass().getPackage().getAnnotation(JSONP.class);
        }
    }
    if (jsonpInfo != null) {
        jsonpParameter = jsonpInfo.paramName();
    }

    String charset = "utf-8";
    org.codehaus.enunciate.rest.annotations.ContentType contentTypeInfo = method
            .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class);
    if (contentTypeInfo == null) {
        contentTypeInfo = method.getDeclaringClass()
                .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class);
        if (contentTypeInfo == null) {
            contentTypeInfo = method.getDeclaringClass().getPackage()
                    .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class);
        }
    }
    if (contentTypeInfo != null) {
        charset = contentTypeInfo.charset();
    }

    String defaultNamespace = "";
    if (method.getDeclaringClass().getPackage() != null
            && method.getDeclaringClass().getPackage().isAnnotationPresent(XmlSchema.class)) {
        defaultNamespace = method.getDeclaringClass().getPackage().getAnnotation(XmlSchema.class).namespace();
    }

    this.properNounType = properNoun;
    this.properNounIndex = properNounIndex;
    this.properNounOptional = properNounOptional;
    this.nounValueType = nounValue;
    this.nounValueIndex = nounValueIndex;
    this.nounValueOptional = nounValueOptional;
    this.resultType = returnType;
    this.charset = charset;
    this.JSONPParameter = jsonpParameter;
    this.contextClasses = contextClasses;
    this.contentTypeParameterIndex = contentTypeParameterIndex;
    this.defaultNamespace = defaultNamespace;
}

From source file:ca.uhn.fhir.jaxrs.server.AbstractJaxRsConformanceProvider.java

/**
 * This method will add a provider to the conformance. This method is almost an exact copy of {@link ca.uhn.fhir.rest.server.RestfulServer#findResourceMethods }
 * //from   ww w .  j av a  2  s.com
 * @param theProvider
 *           an instance of the provider interface
 * @param theProviderInterface
 *           the class describing the providers interface
 * @return the numbers of basemethodbindings added
 * @see ca.uhn.fhir.rest.server.RestfulServer#findResourceMethods
 */
public int addProvider(IResourceProvider theProvider, Class<? extends IResourceProvider> theProviderInterface)
        throws ConfigurationException {
    int count = 0;

    for (Method m : ReflectionUtil.getDeclaredMethods(theProviderInterface)) {
        BaseMethodBinding<?> foundMethodBinding = BaseMethodBinding.bindMethod(m, getFhirContext(),
                theProvider);
        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.apache.axis2.description.java2wsdl.DocLitBareSchemaGenerator.java

@Override
protected Method[] processMethods(Method[] declaredMethods) throws Exception {
    ArrayList<Method> list = new ArrayList<Method>();
    //short the elements in the array
    Arrays.sort(declaredMethods, new MathodComparator());

    // since we do not support overload
    HashMap<String, Method> uniqueMethods = new LinkedHashMap<String, Method>();
    XmlSchemaComplexType methodSchemaType;
    XmlSchemaSequence sequence;/*from w ww. j  a v a2s  . c  o  m*/

    for (Method jMethod : declaredMethods) {
        if (jMethod.isBridge()) {
            continue;
        }
        WebMethodAnnotation methodAnnon = JSR181Helper.INSTANCE.getWebMethodAnnotation(jMethod);
        if (methodAnnon != null) {
            if (methodAnnon.isExclude()) {
                continue;
            }
        }
        String methodName = jMethod.getName();
        // no need to think abt this method , since that is system
        // config method
        if (excludeMethods.contains(methodName)) {
            continue;
        }

        if (uniqueMethods.get(methodName) != null) {
            log.warn("We don't support method overloading. Ignoring [" + methodName + "]");
            continue;
        }

        if (!Modifier.isPublic(jMethod.getModifiers())) {
            // no need to generate Schema for non public methods
            continue;
        }

        boolean addToService = false;
        AxisOperation axisOperation = service.getOperation(new QName(methodName));
        if (axisOperation == null) {
            axisOperation = Utils.getAxisOperationForJmethod(jMethod);
            if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(axisOperation.getMessageExchangePattern())) {
                AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
                if (outMessage != null) {
                    outMessage.setName(methodName + RESULT);
                }
            }
            addToService = true;
        }

        // Maintain a list of methods we actually work with
        list.add(jMethod);
        processException(jMethod, axisOperation);
        uniqueMethods.put(methodName, jMethod);
        //create the schema type for the method wrapper

        uniqueMethods.put(methodName, jMethod);
        Class<?>[] paras = jMethod.getParameterTypes();
        String parameterNames[] = methodTable.getParameterNames(methodName);
        AxisMessage inMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        if (inMessage != null) {
            inMessage.setName(methodName + "RequestMessage");
        }
        Annotation[][] parameterAnnotation = jMethod.getParameterAnnotations();
        if (paras.length > 1) {
            sequence = new XmlSchemaSequence();
            methodSchemaType = createSchemaTypeForMethodPart(methodName);
            methodSchemaType.setParticle(sequence);
            inMessage.setElementQName(typeTable.getQNamefortheType(methodName));
            service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation);
            inMessage.setPartName(methodName);
            for (int j = 0; j < paras.length; j++) {
                Class<?> methodParameter = paras[j];
                String parameterName = getParameterName(parameterAnnotation, j, parameterNames);
                if (generateRequestSchema(methodParameter, parameterName, jMethod, sequence)) {
                    break;
                }
            }
        } else if (paras.length == 1) {
            if (paras[0].isArray()) {
                sequence = new XmlSchemaSequence();

                methodSchemaType = createSchemaTypeForMethodPart(methodName);
                methodSchemaType.setParticle(sequence);
                Class<?> methodParameter = paras[0];
                inMessage.setElementQName(typeTable.getQNamefortheType(methodName));
                service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation);
                inMessage.setPartName(methodName);
                String parameterName = getParameterName(parameterAnnotation, 0, parameterNames);
                if (generateRequestSchema(methodParameter, parameterName, jMethod, sequence)) {
                    break;
                }
            } else {
                String parameterName = getParameterName(parameterAnnotation, 0, parameterNames);
                Class<?> methodParameter = paras[0];
                Method processMethod = processedParameters.get(parameterName);
                if (processMethod != null) {
                    throw new AxisFault(
                            "Inavalid Java class," + " there are two methods [" + processMethod.getName()
                                    + " and " + jMethod.getName() + " ]which have the same parameter names");
                } else {
                    processedParameters.put(parameterName, jMethod);
                    generateSchemaForType(null, methodParameter, parameterName);
                    inMessage.setElementQName(typeTable.getQNamefortheType(parameterName));
                    inMessage.setPartName(parameterName);
                    inMessage.setWrapped(false);
                    service.addMessageElementQNameToOperationMapping(
                            typeTable.getQNamefortheType(parameterName), axisOperation);
                }
            }
        }

        // for its return type
        Class<?> returnType = jMethod.getReturnType();

        if (!"void".equals(jMethod.getReturnType().getName())) {
            AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
            if (returnType.isArray()) {
                methodSchemaType = createSchemaTypeForMethodPart(jMethod.getName() + RESULT);
                sequence = new XmlSchemaSequence();
                methodSchemaType.setParticle(sequence);
                WebResultAnnotation returnAnnon = JSR181Helper.INSTANCE.getWebResultAnnotation(jMethod);
                String returnName = "return";
                if (returnAnnon != null) {
                    returnName = returnAnnon.getName();
                    if (returnName != null && !"".equals(returnName)) {
                        returnName = "return";
                    }
                }
                if (nonRpcMethods.contains(methodName)) {
                    generateSchemaForType(sequence, null, returnName);
                } else {
                    generateSchemaForType(sequence, returnType, returnName);
                }
            } else {
                generateSchemaForType(null, returnType, methodName + RESULT);
                outMessage.setWrapped(false);
            }
            outMessage.setElementQName(typeTable.getQNamefortheType(methodName + RESULT));
            outMessage.setName(methodName + "ResponseMessage");
            outMessage.setPartName(methodName + RESULT);
            service.addMessageElementQNameToOperationMapping(typeTable.getQNamefortheType(methodName + RESULT),
                    axisOperation);
        }
        if (addToService) {
            service.addOperation(axisOperation);
        }
    }
    return list.toArray(new Method[list.size()]);
}

From source file:com.github.reinert.jjschema.HyperSchemaGeneratorV4.java

private ObjectNode generateLink(Method method) throws InvalidLinkMethod, TypeException {
    String href = null, rel = null, httpMethod = null;
    boolean isLink = false;

    Annotation[] ans = method.getAnnotations();
    for (Annotation a : ans) {
        if (a.annotationType().equals(GET.class)) {
            httpMethod = "GET";
            isLink = true;//w  w  w  .ja  v a 2 s .c om
        } else if (a.annotationType().equals(POST.class)) {
            httpMethod = "POST";
            isLink = true;
        } else if (a.annotationType().equals(PUT.class)) {
            httpMethod = "PUT";
            isLink = true;
        } else if (a.annotationType().equals(DELETE.class)) {
            httpMethod = "DELETE";
            isLink = true;
        } else if (a.annotationType().equals(HEAD.class)) {
            throw new RuntimeException("HEAD not yet supported.");
        } else if (a.annotationType().equals(Path.class)) {
            Path p = (Path) a;
            href = p.value();
        } else if (a.annotationType().equals(Rel.class)) {
            Rel l = (Rel) a;
            rel = l.value();
        }
    }

    // Check if the method is actually a link
    if (!isLink) {
        throw new InvalidLinkMethod(
                "Method " + method.getName() + " is not a link. Must use a HTTP METHOD annotation.");
    }

    // If the rel was not informed than assume the method name
    if (rel == null)
        rel = method.getName();

    // if the href was not informed than fill with default #
    if (href == null)
        href = "#";

    ObjectNode link = jsonSchemaGenerator.createInstance();
    link.put("href", href);
    link.put("method", httpMethod);
    link.put("rel", rel);

    // TODO: by default use a Prototype containing only the $id or $ref for the TargetSchema
    ObjectNode tgtSchema = generateSchema(method.getReturnType());
    if (tgtSchema != null)
        link.put("targetSchema", tgtSchema);

    // Check possible params and form schema attribute.
    // If it has QueryParam or FormParam than the schema must have these params as properties.
    // If it has none of the above and has some ordinary object than the schema must be this
    // object and it is passed by the body.
    Class<?>[] paramTypes = method.getParameterTypes();
    if (paramTypes.length > 0) {
        ObjectNode schema = null;
        boolean hasParam = false;
        boolean hasBodyParam = false;
        for (int i = 0; i < paramTypes.length; i++) {
            Annotation[] paramAns = method.getParameterAnnotations()[i];
            com.github.reinert.jjschema.Media media = null;
            String prop = null;
            boolean isBodyParam = true;
            boolean isParam = false;
            for (int j = 0; j < paramAns.length; j++) {
                Annotation a = paramAns[j];
                if (a instanceof QueryParam) {
                    if (schema == null) {
                        schema = jsonSchemaGenerator.createInstance();
                        schema.put("type", "object");
                    }
                    QueryParam q = (QueryParam) a;
                    schema.put(q.value(), jsonSchemaGenerator.generateSchema(paramTypes[i]));
                    prop = q.value();
                    hasParam = true;
                    isBodyParam = false;
                    isParam = true;
                } else if (a instanceof FormParam) {
                    if (schema == null) {
                        schema = jsonSchemaGenerator.createInstance();
                        schema.put("type", "object");
                    }
                    FormParam q = (FormParam) a;

                    schema.put(q.value(), jsonSchemaGenerator.generateSchema(paramTypes[i]));
                    prop = q.value();
                    hasParam = true;
                    isBodyParam = false;
                    isParam = true;
                } else if (a instanceof PathParam) {
                    if (media != null) {
                        throw new RuntimeException("Media cannot be declared along with PathParam.");
                    }
                    for (int k = j + 1; k < paramAns.length; k++) {
                        Annotation a2 = paramAns[k];
                        if (a2 instanceof com.github.reinert.jjschema.Media)
                            throw new RuntimeException("Media cannot be declared along with PathParam.");
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof CookieParam) {
                    if (media != null) {
                        media = null;
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof HeaderParam) {
                    if (media != null) {
                        media = null;
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof MatrixParam) {
                    if (media != null) {
                        throw new RuntimeException("Media cannot be declared along with MatrixParam.");
                    }
                    for (int k = j + 1; k < paramAns.length; k++) {
                        Annotation a2 = paramAns[k];
                        if (a2 instanceof com.github.reinert.jjschema.Media)
                            throw new RuntimeException("Media cannot be declared along with MatrixParam.");
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof Context) {
                    if (media != null) {
                        throw new RuntimeException("Media cannot be declared along with Context.");
                    }
                    isBodyParam = false;
                    continue;
                } else if (a instanceof com.github.reinert.jjschema.Media) {
                    media = (com.github.reinert.jjschema.Media) a;
                }
            }
            if (isBodyParam) {
                hasBodyParam = true;
                schema = generateSchema(paramTypes[i]);
                if (media != null) {
                    schema.put(MEDIA_TYPE, media.type());
                    schema.put(BINARY_ENCODING, media.binaryEncoding());
                }
            } else if (isParam) {
                hasParam = true;
                if (media != null) {
                    ObjectNode hs = (ObjectNode) schema.get(prop);
                    hs.put(MEDIA_TYPE, media.type());
                    hs.put(BINARY_ENCODING, media.binaryEncoding());
                    schema.put(prop, hs);
                }
            }
        }

        if (hasBodyParam && hasParam)
            throw new RuntimeException(
                    "JsonSchema does not support both FormParam or QueryParam and BodyParam at the same time.");

        link.put("schema", schema);
    }

    return link;
}