Example usage for java.lang.reflect Method getExceptionTypes

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

Introduction

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

Prototype

@Override
public Class<?>[] getExceptionTypes() 

Source Link

Usage

From source file:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * Validate a Method to be a main command line application method.
 *
 * Methods with more than 1 argument are not allowed. Methods with return types
 * are not allowed. Methods that throw an exception other than
 * org.apache.commons.cli.CommandLineException are not allowed,
 *
 * @param method the method to validate//  w  ww  .j  ava 2s. c  om
 * @return A new method helper for the method
 */
private CommandLineMethodHelper getHelperForCommandLineMain(Method method) throws CommandLineException {

    // Validate that the return type is a void
    if (!method.getReturnType().equals(Void.TYPE)) {
        throw new CommandLineException("For method " + method.getName() + ", the return type is not void");
    }

    // Validate the exceptions throws by the method
    for (Class<?> clazz : method.getExceptionTypes()) {
        if (!clazz.equals(CommandLineException.class)) {
            throw new CommandLineException("For method " + method.getName()
                    + ", there is an invalid exception class " + clazz.getName());
        }
    }

    // In order to get ready to create the configuration instance,
    // we will need to know the command line option type
    // and the element type.
    Class<?> elementClass;
    MethodType methodType;
    Converter converter;

    // Get the parameters of the method. We'll use these to
    // determine what type of option we have - scalar, boolean, etc.
    Class<?> parameterClasses[] = method.getParameterTypes();

    // See what the length tells us
    switch (parameterClasses.length) {
    case 0:
        throw new CommandLineException("Main command line method must take arguments");
    case 1: {

        // For a method with one argument, we have to look
        // more closely at the argument. It has to be a simple
        // scalar object, an array, or a list.
        Class<?> parameterClass = parameterClasses[0];
        if (parameterClass.isArray()) {

            // For an array, we get the element class based on the
            // underlying component type
            methodType = MethodType.Array;
            elementClass = parameterClass.getComponentType();
        } else {

            // For a scalar, we get the element type from the
            // type of the parameter.
            methodType = MethodType.Scalar;
            elementClass = parameterClass.getClass();
        }

        // Now that we have the element type, make sure it's convertable
        converter = ConvertUtils.lookup(String.class, elementClass);
        if (converter == null) {
            throw new CommandLineException("Cannot find a conversion from String to " + elementClass.getName()
                    + " for method " + method.getName());
        }
        break;
    }
    default: {

        // Other method types not allowed.
        throw new CommandLineException("Method " + method.getName() + " has too many arguments");
    }
    }

    // Now we can return the configuration for this method
    return new CommandLineMethodHelper(method, methodType, elementClass, converter);
}

From source file:com.meidusa.venus.client.VenusServiceFactory.java

private void loadConfiguration(Map<String, Tuple<ObjectPool, BackendConnectionPool>> poolMap,
        Map<Class<?>, Tuple<Object, RemotingInvocationHandler>> servicesMap,
        Map<Class<?>, ServiceConfig> serviceConfig, Map<String, Object> realPools) throws Exception {
    VenusClient all = new VenusClient();
    for (String configFile : configFiles) {
        configFile = (String) ConfigUtil.filter(configFile);
        URL url = this.getClass().getResource("venusClientRule.xml");
        if (url == null) {
            throw new VenusConfigException("venusClientRule.xml not found!,pls rebuild venus!");
        }/*from  ww  w .j  a  v  a2s  .  com*/
        RuleSet ruleSet = new FromXmlRuleSet(url, new DigesterRuleParser());
        Digester digester = new Digester();
        digester.setValidating(false);
        digester.addRuleSet(ruleSet);

        try {
            InputStream is = ResourceUtils.getURL(configFile.trim()).openStream();
            VenusClient venus = (VenusClient) digester.parse(is);
            for (ServiceConfig config : venus.getServiceConfigs()) {
                if (config.getType() == null) {
                    logger.error("Service type can not be null:" + configFile);
                    throw new ConfigurationException("Service type can not be null:" + configFile);
                }
            }
            all.getRemoteMap().putAll(venus.getRemoteMap());
            all.getServiceConfigs().addAll(venus.getServiceConfigs());
        } catch (Exception e) {
            throw new ConfigurationException("can not parser xml:" + configFile, e);
        }
    }

    // ? remotePool
    for (Map.Entry<String, Remote> entry : all.getRemoteMap().entrySet()) {
        RemoteContainer container = createRemoteContainer(entry.getValue(), realPools);
        Tuple<ObjectPool, BackendConnectionPool> tuple = new Tuple<ObjectPool, BackendConnectionPool>();
        tuple.left = container.getBioPool();
        tuple.right = container.getNioPool();
        poolMap.put(entry.getKey(), tuple);
    }

    for (ServiceConfig config : all.getServiceConfigs()) {

        Remote remote = all.getRemoteMap().get(config.getRemote());
        Tuple<ObjectPool, BackendConnectionPool> tuple = null;
        if (!StringUtil.isEmpty(config.getRemote())) {
            tuple = poolMap.get(config.getRemote());
            if (tuple == null) {
                throw new ConfigurationException("remote=" + config.getRemote() + " not found!!");
            }
        } else {
            String ipAddress = config.getIpAddressList();
            tuple = poolMap.get(ipAddress);
            if (ipAddress != null && tuple == null) {
                RemoteContainer container = createRemoteContainer(true, ipAddress, realPools);
                tuple = new Tuple<ObjectPool, BackendConnectionPool>();
                tuple.left = container.getBioPool();
                tuple.right = container.getNioPool();
                poolMap.put(ipAddress, tuple);
            }
        }

        if (tuple != null) {
            RemotingInvocationHandler invocationHandler = new RemotingInvocationHandler();
            invocationHandler.setBioConnPool(tuple.left);
            invocationHandler.setNioConnPool(tuple.right);
            invocationHandler.setServiceFactory(this);
            invocationHandler.setVenusExceptionFactory(this.getVenusExceptionFactory());
            if (remote != null && remote.getAuthenticator() != null) {
                invocationHandler.setSerializeType(remote.getAuthenticator().getSerializeType());
            }

            invocationHandler.setContainer(this.container);

            Object object = Proxy.newProxyInstance(this.getClass().getClassLoader(),
                    new Class[] { config.getType() }, invocationHandler);

            for (Method method : config.getType().getMethods()) {
                Endpoint endpoint = method.getAnnotation(Endpoint.class);
                if (endpoint != null) {
                    Class[] eclazz = method.getExceptionTypes();
                    for (Class clazz : eclazz) {
                        if (venusExceptionFactory != null && CodedException.class.isAssignableFrom(clazz)) {
                            venusExceptionFactory.addException(clazz);
                        }
                    }
                }
            }

            serviceConfig.put(config.getType(), config);
            Tuple<Object, RemotingInvocationHandler> serviceTuple = new Tuple<Object, RemotingInvocationHandler>(
                    object, invocationHandler);
            servicesMap.put(config.getType(), serviceTuple);
            if (config.getBeanName() != null) {
                serviceBeanMap.put(config.getBeanName(), serviceTuple);
            }
        } else {
            if (config.getInstance() != null) {
                Tuple<Object, RemotingInvocationHandler> serviceTuple = new Tuple<Object, RemotingInvocationHandler>(
                        config.getInstance(), null);
                servicesMap.put(config.getType(), serviceTuple);
                if (config.getBeanName() != null) {
                    serviceBeanMap.put(config.getBeanName(), serviceTuple);
                }
            } else {
                throw new ConfigurationException(
                        "Service instance or ipAddressList or remote can not be null:" + config.getType());
            }
        }

    }
}

From source file:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * Validate a Method to be a command line option methods.
 *
 * Methods with more than 1 argument are not allowed. Methods with return types
 * other than boolean are not allowed. Methods that throw an exception other than
 * org.apache.commons.cli.CommandLineException are not allowed,
 *
 * @param method the method to validate//  ww w.  j  a  v  a  2  s.co m
 * @param commandLineOption the options on that method
 * @return A new method helper for the method
 */
private CommandLineMethodHelper getHelperForCommandOption(Method method, CommandLineOption commandLineOption)
        throws CommandLineException {

    // Validate that the return type is a boolean or void
    if (!method.getReturnType().equals(Boolean.TYPE) && !method.getReturnType().equals(Void.TYPE)) {
        throw new CommandLineException(
                "For method " + method.getName() + ", the return type is not boolean or void");
    }

    // Validate the exceptions throws by the method
    for (Class<?> clazz : method.getExceptionTypes()) {
        if (!clazz.equals(CommandLineException.class)) {
            throw new CommandLineException("For method " + method.getName()
                    + ", there is an invalid exception class " + clazz.getName());
        }
    }

    // In order to get ready to create the configuration instance,
    // we will need to know the command line option type
    // and the element type.
    Class<?> elementClass = null;
    MethodType methodType;
    Converter converter;

    // Get the parameters of the method. We'll use these to
    // determine what type of option we have - scalar, boolean, etc.
    Class<?> parameterClasses[] = method.getParameterTypes();

    // See what the length tells us
    switch (parameterClasses.length) {
    case 0:
        methodType = MethodType.Boolean;
        converter = null;
        break;
    case 1: {

        // For a method with one argument, we have to look
        // more closely at the argument. It has to be a simple
        // scalar object, an array, or a list.
        Class<?> parameterClass = parameterClasses[0];
        if (parameterClass.isArray()) {

            // For an array, we get the element class based on the
            // underlying component type
            methodType = MethodType.Array;
            elementClass = parameterClass.getComponentType();
        } else if (List.class.isAssignableFrom(parameterClass)) {

            // For a list, we get the element class from the command
            // line options annotation
            methodType = MethodType.List;
            elementClass = commandLineOption.argumentType();
        } else {

            // For a scalar, we get the element type from the
            // type of the parameter.
            methodType = MethodType.Scalar;
            elementClass = parameterClass.getClass();
        }

        // Now that we have the element type, make sure it's convertable
        converter = ConvertUtils.lookup(String.class, elementClass);
        if (converter == null) {
            throw new CommandLineException("Cannot find a conversion from String to " + elementClass.getName()
                    + " for method " + method.getName());
        }
        break;
    }
    default: {

        // Other method types not allowed.
        throw new CommandLineException("Method " + method.getName() + " has too many arguments");
    }
    }

    // Now we can return the configuration for this method
    return new CommandLineMethodHelper(method, methodType, elementClass, converter);
}

From source file:com.redhat.rhn.frontend.xmlrpc.api.ApiHandler.java

/**
 * Lists all available api calls for the specified namespace
 * @param loggedInUser The current user//from w  ww . j a v  a2s. c o  m
 * @param namespace namespace of interest
 * @return a map containing list of api calls for every namespace
 * @throws ClassNotFoundException if namespace isn't valid
 *
 * @xmlrpc.doc Lists all available api calls for the specified namespace
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #param("string", "namespace")
 * @xmlrpc.returntype
 *   #struct("method_info")
 *        #prop_desc("string", "name", "method name")
 *        #prop_desc("string", "parameters", "method parameters")
 *        #prop_desc("string", "exceptions", "method exceptions")
 *        #prop_desc("string", "return", "method return type")
 *   #struct_end()
 */
public Map getApiNamespaceCallList(User loggedInUser, String namespace) throws ClassNotFoundException {
    Class<? extends BaseHandler> handlerClass = new HandlerFactory().getHandler(namespace).getClass();
    Map<String, Map<String, Object>> methods = new HashMap<String, Map<String, Object>>();

    for (Method method : handlerClass.getDeclaredMethods()) {

        if (0 != (method.getModifiers() & Modifier.PUBLIC)) {

            Map<String, Object> methodInfo = new HashMap<String, Object>();

            methodInfo.put("name", method.getName());

            List<String> paramList = new ArrayList<String>();
            String paramListString = "";
            for (Type paramType : method.getParameterTypes()) {
                String paramTypeString = getType(paramType, StringUtils.isEmpty(paramListString));
                paramList.add(paramTypeString);
                paramListString += "_" + paramTypeString;
            }
            methodInfo.put("parameters", paramList);

            Set<String> exceptList = new HashSet<String>();
            for (Class<?> exceptClass : method.getExceptionTypes()) {
                exceptList.add(StringUtil.getClassNameNoPackage(exceptClass));
            }
            methodInfo.put("exceptions", exceptList);
            methodInfo.put("return", getType(method.getReturnType(), false));

            String methodName = namespace + "." + methodInfo.get("name") + paramListString;
            methods.put(methodName, methodInfo);
        }
    }
    return methods;
}

From source file:com.appleframework.core.utils.ClassUtility.java

/** ??method?? */
public static String getSimpleMethodSignature(Method method, boolean withModifiers, boolean withReturnType,
        boolean withClassName, boolean withExceptionType) {
    if (method == null) {
        return null;
    }//  w  w  w .ja  v a 2 s  .  co m

    StringBuilder buf = new StringBuilder();

    if (withModifiers) {
        buf.append(Modifier.toString(method.getModifiers())).append(' ');
    }

    if (withReturnType) {
        buf.append(getSimpleClassName(method.getReturnType())).append(' ');
    }

    if (withClassName) {
        buf.append(getSimpleClassName(method.getDeclaringClass())).append('.');
    }

    buf.append(method.getName()).append('(');

    Class<?>[] paramTypes = method.getParameterTypes();

    for (int i = 0; i < paramTypes.length; i++) {
        Class<?> paramType = paramTypes[i];

        buf.append(getSimpleClassName(paramType));

        if (i < paramTypes.length - 1) {
            buf.append(", ");
        }
    }

    buf.append(')');

    if (withExceptionType) {
        Class<?>[] exceptionTypes = method.getExceptionTypes();

        if (!isEmptyArray(exceptionTypes)) {
            buf.append(" throws ");

            for (int i = 0; i < exceptionTypes.length; i++) {
                Class<?> exceptionType = exceptionTypes[i];

                buf.append(getSimpleClassName(exceptionType));

                if (i < exceptionTypes.length - 1) {
                    buf.append(", ");
                }
            }
        }
    }

    return buf.toString();
}

From source file:org.bytesoft.bytetcc.supports.spring.CompensableAnnotationValidator.java

private void validateTransactionalRollbackFor(Method method, Class<?> clazz, String beanName)
        throws IllegalStateException {
    Transactional transactional = method.getAnnotation(Transactional.class);
    if (transactional == null) {
        Class<?> declaringClass = method.getDeclaringClass();
        transactional = declaringClass.getAnnotation(Transactional.class);
    }/*  w w  w . ja v a 2s. c o m*/

    if (transactional == null) {
        throw new IllegalStateException(
                String.format("Method(%s) must be specificed a Transactional annotation!", method));
    }

    String[] rollbackForClassNameArray = transactional.rollbackForClassName();
    if (rollbackForClassNameArray != null && rollbackForClassNameArray.length > 0) {
        throw new IllegalStateException(String.format(
                "The transactional annotation on the confirm/cancel class does not support the property rollbackForClassName yet(beanId= %s)!",
                beanName));
    }

    Class<?>[] rollErrorArray = transactional.rollbackFor();

    Class<?>[] errorTypeArray = method.getExceptionTypes();
    for (int j = 0; errorTypeArray != null && j < errorTypeArray.length; j++) {
        Class<?> errorType = errorTypeArray[j];
        if (RuntimeException.class.isAssignableFrom(errorType)) {
            continue;
        }

        boolean matched = false;
        for (int k = 0; rollErrorArray != null && k < rollErrorArray.length; k++) {
            Class<?> rollbackError = rollErrorArray[k];
            if (rollbackError.isAssignableFrom(errorType)) {
                matched = true;
                break;
            }
        }

        if (matched == false) {
            throw new IllegalStateException(String.format(
                    "The value of Transactional.rollbackFor annotated on method(%s) must includes %s!", method,
                    errorType.getName()));
        }
    }
}

From source file:com.gs.jrpip.client.FastServletProxyInvocationHandler.java

protected Object invokeRemoteMethod(Object proxy, Method method, Object[] args) throws Throwable {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("starting remote method {}.{}", method.getDeclaringClass(), method.getName());
    }//from ww  w . ja v a2s . c o m
    RequestId requestId = new RequestId(this.proxyId);
    int retries = RETRY_COUNT;
    int state = SEND_PARAMETERS_STATE;
    Exception lastException = null;
    boolean checkServerStatus = false;
    while (retries > 0) {
        InputStream is = null;
        byte status = StreamBasedInvocator.FAULT_STATUS;
        Object returned = null;
        HttpClient httpClient = FastServletProxyFactory.getHttpClient(this.url);
        httpClient.getState().addCookies(this.cookies);
        boolean gotResult = false;
        HttpMethod postMethod = null;
        try {
            OutputStreamWriter writer = null;
            switch (state) {
            case SEND_PARAMETERS_STATE:
                writer = new ParameterWriter(proxy, method, args, requestId);
                break;
            case RECEIVE_RESULT_STATE:
                writer = new ResultResendWriter(requestId);
                break;
            }
            postMethod = this.getPostMethod(writer);

            this.setMethodTimeout(postMethod, method);

            httpClient.executeMethod(postMethod);

            this.cookies = httpClient.getState().getCookies();

            state = RECEIVE_RESULT_STATE;

            int code = postMethod.getStatusCode();

            if (code != 200) {
                checkServerStatus = true;
                this.analyzeServerErrorAndThrow(code, postMethod);
            }

            is = postMethod.getResponseBodyAsStream();

            //if (CAUSE_RANDOM_ERROR) if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!");

            status = (byte) is.read();
            if (status != StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS) {
                returned = this.getResult(method, args, is);
            }
            gotResult = true;
            is.close();
            is = null;
            postMethod.releaseConnection();
            postMethod = null;
        } catch (SocketTimeoutException e) {
            LOGGER.debug("Socket timeout reached for JRPIP invocation", e);
            throw new JrpipTimeoutException("Remote method " + method.getName() + " timed out." + this.url, e);
        } catch (NotSerializableException e) {
            throw new JrpipRuntimeException("Method arguments are not serializable!", e);
        } catch (ClassNotFoundException e) {
            throw new JrpipRuntimeException("Method call successfully completed but result class not found", e);
        } catch (Exception e) {
            retries--;
            lastException = e;
            LOGGER.debug("Exception in JRPIP invocation. Retries left {}", retries, e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.debug("Could not close stream. See previous exception for cause", e);
                }
            }
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }
        if (gotResult) {
            switch (status) {
            case StreamBasedInvocator.OK_STATUS:
                ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("finished remote method normally {}.{}", method.getDeclaringClass(),
                            method.getName());
                }
                return returned;
            case StreamBasedInvocator.FAULT_STATUS:
                ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("finished remote method {}.{} with exception {}", method.getDeclaringClass(),
                            method.getName(), returned.getClass().getName(),
                            new JrpipRuntimeException("for tracing local invocation context"));
                }
                Class[] exceptions = method.getExceptionTypes();
                for (int i = 0; i < exceptions.length; i++) {
                    if (exceptions[i].isAssignableFrom(returned.getClass())) {
                        throw (Throwable) returned;
                    }
                }
                if (RuntimeException.class.isAssignableFrom(returned.getClass())) {
                    throw (RuntimeException) returned;
                }
                if (Error.class.isAssignableFrom(returned.getClass())) {
                    throw (Error) returned;
                }
                if (Throwable.class.isAssignableFrom(returned.getClass())
                        && !Exception.class.isAssignableFrom(returned.getClass())) {
                    throw (Throwable) returned;
                }
                throw new JrpipRuntimeException(
                        "Could not throw returned exception, as it was not declared in the method signature for method "
                                + method.getName(),
                        (Throwable) returned);
            case StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS:
                state = SEND_PARAMETERS_STATE;
                break;
            }
        } else {
            checkServerStatus = true;
        }
        if (checkServerStatus) {
            this.determineServerStatus(state == RECEIVE_RESULT_STATE);
            checkServerStatus = false;
        }
    }
    throw new JrpipRuntimeException(
            "Could not invoke remote method " + method.getName() + " while accessing " + this.url,
            lastException);
}

From source file:io.swagger.jaxrs.MethodProcessor.java

static Operation parseMethod(Class<?> cls, Method method, List<Parameter> globalParameters, Swagger swagger) {
    Operation operation = new Operation();

    ApiOperation apiOperationAnnotation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);

    String operationId = method.getName();
    String responseContainer = null;

    Type responseType = null;//from   w  w w. ja va  2 s  .  c om
    Map<String, Property> defaultResponseHeaders = new HashMap<>();

    if (apiOperationAnnotation != null) {
        if (apiOperationAnnotation.hidden()) {
            return null;
        }
        if (!"".equals(apiOperationAnnotation.nickname())) {
            operationId = apiOperationAnnotation.nickname();
        }

        defaultResponseHeaders = parseResponseHeaders(swagger, apiOperationAnnotation.responseHeaders());

        operation.summary(apiOperationAnnotation.value()).description(apiOperationAnnotation.notes());

        if (apiOperationAnnotation.response() != null && !isVoid(apiOperationAnnotation.response())) {
            responseType = apiOperationAnnotation.response();
        }
        if (!"".equals(apiOperationAnnotation.responseContainer())) {
            responseContainer = apiOperationAnnotation.responseContainer();
        }
        if (apiOperationAnnotation.authorizations() != null) {
            List<SecurityRequirement> securities = new ArrayList<>();
            for (Authorization auth : apiOperationAnnotation.authorizations()) {
                if (auth.value() != null && !"".equals(auth.value())) {
                    SecurityRequirement security = new SecurityRequirement();
                    security.setName(auth.value());
                    AuthorizationScope[] scopes = auth.scopes();
                    for (AuthorizationScope scope : scopes) {
                        if (scope.scope() != null && !"".equals(scope.scope())) {
                            security.addScope(scope.scope());
                        }
                    }
                    securities.add(security);
                }
            }
            if (securities.size() > 0) {
                securities.stream().forEach((sec) -> {
                    operation.security(sec);
                });
            }
        }
        if (apiOperationAnnotation.consumes() != null && !apiOperationAnnotation.consumes().isEmpty()) {
            operation.consumes(apiOperationAnnotation.consumes());
        }
        if (apiOperationAnnotation.produces() != null && !apiOperationAnnotation.produces().isEmpty()) {
            operation.produces(apiOperationAnnotation.produces());
        }
    }

    if (apiOperationAnnotation != null && StringUtils.isNotEmpty(apiOperationAnnotation.responseReference())) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);
        response.schema(new RefProperty(apiOperationAnnotation.responseReference()));
        operation.addResponse(String.valueOf(apiOperationAnnotation.code()), response);
    } else if (responseType == null) {
        // pick out response from method declaration
        //handle Response types
        if (method.getGenericReturnType() instanceof ParameterizedType
                && org.thingsplode.synapse.core.Response.class.isAssignableFrom(
                        (Class<?>) ((ParameterizedType) method.getGenericReturnType()).getRawType())) {
            responseType = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0];
        } else {
            responseType = method.getGenericReturnType();
        }

    }
    if (isValidResponse(responseType)) {
        final Property property = ModelConverters.getInstance().readAsProperty(responseType);
        if (property != null) {
            final Property responseProperty = Reader.ContainerWrapper.wrapContainer(responseContainer,
                    property);
            final int responseCode = apiOperationAnnotation == null ? 200 : apiOperationAnnotation.code();
            operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION)
                    .schema(responseProperty).headers(defaultResponseHeaders));
            appendModels(swagger, responseType);
        }
    }

    operation.operationId(operationId);

    if (apiOperationAnnotation != null && apiOperationAnnotation.consumes() != null
            && apiOperationAnnotation.consumes().isEmpty()) {
        //todo: check what to do with consumers
        //            final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class);
        //            if (consumes != null) {
        //                for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) {
        //                    operation.consumes(mediaType);
        //                }
        //            }
    }

    if (apiOperationAnnotation != null && apiOperationAnnotation.produces() != null
            && apiOperationAnnotation.produces().isEmpty()) {
        //todo: check what to do with produces
        //            final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class);
        //            if (produces != null) {
        //                for (String mediaType : ReaderUtils.splitContentValues(produces.value())) {
        //                    operation.produces(mediaType);
        //                }
        //            }
    }

    List<ApiResponse> apiResponses = new ArrayList<>();
    if (responseAnnotation != null) {
        apiResponses.addAll(Arrays.asList(responseAnnotation.value()));
    }

    Class<?>[] exceptionTypes = method.getExceptionTypes();
    for (Class<?> exceptionType : exceptionTypes) {
        ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class);
        if (exceptionResponses != null) {
            apiResponses.addAll(Arrays.asList(exceptionResponses.value()));
        }
    }

    for (ApiResponse apiResponse : apiResponses) {
        Map<String, Property> responseHeaders = parseResponseHeaders(swagger, apiResponse.responseHeaders());

        Response response = new Response().description(apiResponse.message()).headers(responseHeaders);

        if (apiResponse.code() == 0) {
            operation.defaultResponse(response);
        } else {
            operation.response(apiResponse.code(), response);
        }

        if (StringUtils.isNotEmpty(apiResponse.reference())) {
            response.schema(new RefProperty(apiResponse.reference()));
        } else if (!isVoid(apiResponse.response())) {
            responseType = apiResponse.response();
            final Property property = ModelConverters.getInstance().readAsProperty(responseType);
            if (property != null) {
                response.schema(
                        Reader.ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
                appendModels(swagger, responseType);
            }
        }
    }
    if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) {
        operation.setDeprecated(true);
    }

    // process parameters
    //=====================
    globalParameters.stream().forEach((globalParameter) -> {
        operation.parameter(globalParameter);
    });

    ParameterExtractor.getParameters(swagger, cls, method).forEach(p -> operation.parameter(p));

    if (operation.getResponses() == null) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);
        operation.defaultResponse(response);
    }
    return operation;
}

From source file:io.swagger.jaxrs.Reader.java

private Operation parseMethod(Class<?> cls, Method method, List<Parameter> globalParameters) {
    Operation operation = new Operation();

    ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);

    String operationId = method.getName();
    String responseContainer = null;

    Type responseType = null;/*from  w ww. j  ava2  s.c o m*/
    Map<String, Property> defaultResponseHeaders = new HashMap<String, Property>();

    if (apiOperation != null) {
        if (apiOperation.hidden()) {
            return null;
        }
        if (!"".equals(apiOperation.nickname())) {
            operationId = apiOperation.nickname();
        }

        defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());

        operation.summary(apiOperation.value()).description(apiOperation.notes());

        if (apiOperation.response() != null && !isVoid(apiOperation.response())) {
            responseType = apiOperation.response();
        }
        if (!"".equals(apiOperation.responseContainer())) {
            responseContainer = apiOperation.responseContainer();
        }
        if (apiOperation.authorizations() != null) {
            List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
            for (Authorization auth : apiOperation.authorizations()) {
                if (auth.value() != null && !"".equals(auth.value())) {
                    SecurityRequirement security = new SecurityRequirement();
                    security.setName(auth.value());
                    AuthorizationScope[] scopes = auth.scopes();
                    for (AuthorizationScope scope : scopes) {
                        if (scope.scope() != null && !"".equals(scope.scope())) {
                            security.addScope(scope.scope());
                        }
                    }
                    securities.add(security);
                }
            }
            if (securities.size() > 0) {
                for (SecurityRequirement sec : securities) {
                    operation.security(sec);
                }
            }
        }
        if (apiOperation.consumes() != null && !apiOperation.consumes().isEmpty()) {
            operation.consumes(apiOperation.consumes());
        }
        if (apiOperation.produces() != null && !apiOperation.produces().isEmpty()) {
            operation.produces(apiOperation.produces());
        }
    }

    if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);
        response.schema(new RefProperty(apiOperation.responseReference()));
        operation.addResponse(String.valueOf(apiOperation.code()), response);
    } else if (responseType == null) {
        // pick out response from method declaration
        LOGGER.debug("picking up response class from method " + method);
        responseType = method.getGenericReturnType();
    }
    if (isValidResponse(responseType)) {
        final Property property = ModelConverters.getInstance().readAsProperty(responseType);
        if (property != null) {
            final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property);
            final int responseCode = apiOperation == null ? 200 : apiOperation.code();
            operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION)
                    .schema(responseProperty).headers(defaultResponseHeaders));
            appendModels(responseType);
        }
    }

    operation.operationId(operationId);

    if (apiOperation != null && apiOperation.consumes() != null && apiOperation.consumes().isEmpty()) {
        final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class);
        if (consumes != null) {
            for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) {
                operation.consumes(mediaType);
            }
        }
    }

    if (apiOperation != null && apiOperation.produces() != null && apiOperation.produces().isEmpty()) {
        final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class);
        if (produces != null) {
            for (String mediaType : ReaderUtils.splitContentValues(produces.value())) {
                operation.produces(mediaType);
            }
        }
    }

    List<ApiResponse> apiResponses = new ArrayList<ApiResponse>();
    if (responseAnnotation != null) {
        apiResponses.addAll(Arrays.asList(responseAnnotation.value()));
    }

    Class<?>[] exceptionTypes = method.getExceptionTypes();
    for (Class<?> exceptionType : exceptionTypes) {
        ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class);
        if (exceptionResponses != null) {
            apiResponses.addAll(Arrays.asList(exceptionResponses.value()));
        }
    }

    for (ApiResponse apiResponse : apiResponses) {
        Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders());

        Response response = new Response().description(apiResponse.message()).headers(responseHeaders);

        if (apiResponse.code() == 0) {
            operation.defaultResponse(response);
        } else {
            operation.response(apiResponse.code(), response);
        }

        if (StringUtils.isNotEmpty(apiResponse.reference())) {
            response.schema(new RefProperty(apiResponse.reference()));
        } else if (!isVoid(apiResponse.response())) {
            responseType = apiResponse.response();
            final Property property = ModelConverters.getInstance().readAsProperty(responseType);
            if (property != null) {
                response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
                appendModels(responseType);
            }
        }
    }
    if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) {
        operation.setDeprecated(true);
    }

    // process parameters
    for (Parameter globalParameter : globalParameters) {
        operation.parameter(globalParameter);
    }

    Type[] genericParameterTypes = method.getGenericParameterTypes();
    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    for (int i = 0; i < genericParameterTypes.length; i++) {
        final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls);
        List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]));

        for (Parameter parameter : parameters) {
            operation.parameter(parameter);
        }
    }

    if (operation.getResponses() == null) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);
        operation.defaultResponse(response);
    }
    return operation;
}