io.swagger.util.ParameterProcessor Java Examples

The following examples show how to use io.swagger.util.ParameterProcessor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RpcReaderExtension.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private Parameter readParam(Swagger swagger, Type type, Class<?> cls, ApiParam param) {
    PrimitiveType fromType = PrimitiveType.fromType(type);
    final Parameter para = null == fromType ? new BodyParameter() : new QueryParameter();
    Parameter parameter = ParameterProcessor.applyAnnotations(swagger, para, type,
        null == param ? new ArrayList<Annotation>()
            : Collections.<Annotation> singletonList(param));
    if (parameter instanceof AbstractSerializableParameter) {
        final AbstractSerializableParameter<?> p = (AbstractSerializableParameter<?>) parameter;
        if (p.getType() == null) {
            p.setType(null == fromType ? "string" : fromType.getCommonName());
        }
        p.setRequired(p.getRequired() || cls.isPrimitive());
    } else {
        //hack: Get the from data model paramter from BodyParameter
        BodyParameter bp = (BodyParameter) parameter;
        bp.setIn("body");
        Property property = ModelConverters.getInstance().readAsProperty(type);
        final Map<PropertyBuilder.PropertyId, Object> args = new EnumMap<PropertyBuilder.PropertyId, Object>(
            PropertyBuilder.PropertyId.class);
        bp.setSchema(PropertyBuilder.toModel(PropertyBuilder.merge(property, args)));
    }
    return parameter;
}
 
Example #2
Source File: Reader.java    From proteus with Apache License 2.0 6 votes vote down vote up
protected Parameter readImplicitParam(ApiImplicitParam param) {
    final Parameter p;
    if (param.paramType().equalsIgnoreCase("path")) {
        p = new PathParameter();
    } else if (param.paramType().equalsIgnoreCase("query")) {
        p = new QueryParameter();
    } else if (param.paramType().equalsIgnoreCase("form") || param.paramType().equalsIgnoreCase("formData")) {
        p = new FormParameter();
    } else if (param.paramType().equalsIgnoreCase("body")) {
        p = null;
    } else if (param.paramType().equalsIgnoreCase("header")) {
        p = new HeaderParameter();
    } else {
        LOGGER.warn("Unknown implicit parameter type: [{}]", param.paramType());
        return null;
    }
    final Type type = ReflectionUtils.typeFromString(param.dataType());
     return ParameterProcessor.applyAnnotations(swagger, p, (type == null) ? String.class : type,
            Arrays.<Annotation>asList(param));
}
 
Example #3
Source File: DubboReaderExtension.java    From swagger-dubbo with Apache License 2.0 6 votes vote down vote up
private Parameter readParam(Swagger swagger, Type type,Class<?> cls, ApiParam param) {
	PrimitiveType fromType = PrimitiveType.fromType(type);
	final Parameter para = null == fromType ? new BodyParameter() : new QueryParameter();
	Parameter parameter = ParameterProcessor.applyAnnotations(swagger, para,
			type == null ? String.class : type, null == param ? new ArrayList<Annotation>()
					: Collections.<Annotation> singletonList(param));
	if (parameter instanceof AbstractSerializableParameter) {
		final AbstractSerializableParameter<?> p = (AbstractSerializableParameter<?>) parameter;
		if (p.getType() == null) p.setType(null == fromType ? "string" : fromType.getCommonName());
		p.setRequired(p.getRequired() == true ? true : cls.isPrimitive());
	}else{
	    //hack: Get the from data model paramter from BodyParameter
	    BodyParameter bp = (BodyParameter)parameter;
	    bp.setIn("formData");
	}
	return parameter;
}
 
Example #4
Source File: AbstractReader.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
protected Parameter readImplicitParam(ApiImplicitParam param, Class<?> apiClass) {
    Parameter parameter;
    if (param.paramType().equalsIgnoreCase("path")) {
        parameter = new PathParameter();
    } else if (param.paramType().equalsIgnoreCase("query")) {
        parameter = new QueryParameter();
    } else if (param.paramType().equalsIgnoreCase("form") || param.paramType().equalsIgnoreCase("formData")) {
        parameter = new FormParameter();
    } else if (param.paramType().equalsIgnoreCase("body")) {
        parameter = new BodyParameter();
    } else if (param.paramType().equalsIgnoreCase("header")) {
        parameter = new HeaderParameter();
    } else {
        return null;
    }

    return ParameterProcessor.applyAnnotations(swagger, parameter, apiClass, Arrays.asList(new Annotation[]{param}));
}
 
Example #5
Source File: ReaderUtils.java    From dorado with Apache License 2.0 5 votes vote down vote up
/**
 * Collects field-level parameters from class.
 *
 * @param cls     is a class for collecting
 * @param swagger is the instance of the Swagger
 * @return the collection of supported parameters
 */
public static List<Parameter> collectFieldParameters(Class<?> cls, Swagger swagger) {
    final List<Parameter> parameters = new ArrayList<Parameter>();
    for (Field field : ReflectionUtils.getDeclaredFields(cls)) {
        final List<Annotation> annotations = Arrays.asList(field.getAnnotations());
        final Type genericType = field.getGenericType();
        for (Parameter parameter : collectParameters(genericType, annotations)) {
            if (ParameterProcessor.applyAnnotations(swagger, parameter, genericType, annotations) != null) {
                parameters.add(parameter);
            }
        }
    }
    return parameters;
}
 
Example #6
Source File: Reader.java    From dorado with Apache License 2.0 5 votes vote down vote up
private List<Parameter> getParameters(Type type, List<Annotation> annotations, MethodDescriptor methodDescriptor) {
	final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
	if (!chain.hasNext()) {
		return Collections.emptyList();
	}
	LOGGER.debug("getParameters for {}", type);
	Set<Type> typesToSkip = new HashSet<Type>();
	final SwaggerExtension extension = chain.next();
	LOGGER.debug("trying extension {}", extension);

	final List<Parameter> parameters = extension.extractParameters(annotations, type, typesToSkip, chain,
			methodDescriptor);
	if (!parameters.isEmpty()) {
		final List<Parameter> processed = new ArrayList<Parameter>(parameters.size());
		for (Parameter parameter : parameters) {
			if (ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations) != null) {
				processed.add(parameter);
			}
		}
		return processed;
	} else {
		LOGGER.debug("no parameter found, looking at body params");
		final List<Parameter> body = new ArrayList<Parameter>();
		if (!typesToSkip.contains(type)) {
			Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
			if (param != null) {
				body.add(param);
			}
		}
		return body;
	}
}
 
Example #7
Source File: RpcReaderExtension.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private Parameter readImplicitParam(Swagger swagger, ApiImplicitParam param) {
    PrimitiveType fromType = PrimitiveType.fromName(param.paramType());
    final Parameter p = null == fromType ? new FormParameter() : new QueryParameter();
    final Type type = ReflectionUtils.typeFromString(param.dataType());
    return ParameterProcessor.applyAnnotations(swagger, p, type == null ? String.class : type,
        Collections.<Annotation> singletonList(param));
}
 
Example #8
Source File: TestGenerate.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateParameter() throws NoSuchMethodException {
    Method someMethod = TestGenerate.class.getMethod("someMethod", SomeParameter.class);
    Type type = someMethod.getGenericParameterTypes()[0];
    Swagger swagger = new Swagger();
    BodyParameter parameter = new BodyParameter();
    Parameter parameter1 = ParameterProcessor.applyAnnotations(swagger, parameter, type,
        new ArrayList<Annotation>());
    Assert.assertTrue(parameter1 instanceof BodyParameter);
    Model schema = ((BodyParameter) parameter1).getSchema();
    Assert.assertTrue(schema instanceof RefModel);
    Assert.assertEquals("#/definitions/SomeParameter", ((RefModel) schema).get$ref());
}
 
Example #9
Source File: DubboReaderExtension.java    From swagger-dubbo with Apache License 2.0 5 votes vote down vote up
private Parameter readImplicitParam(Swagger swagger, ApiImplicitParam param) {
	PrimitiveType fromType = PrimitiveType.fromName(param.paramType());
	final Parameter p = null == fromType ? new FormParameter() : new QueryParameter();
	final Type type = ReflectionUtils.typeFromString(param.dataType());
	return ParameterProcessor.applyAnnotations(swagger, p, type == null ? String.class : type,
			Collections.<Annotation> singletonList(param));
}
 
Example #10
Source File: ControllerReaderExtension.java    From jboot with Apache License 2.0 5 votes vote down vote up
private Parameter readImplicitParam(Swagger swagger, ApiImplicitParam param) {
    final Parameter p = ParameterFactory.createParam(param.paramType());
    if (p == null) {
        return null;
    }
    final Type type = ReflectionUtils.typeFromString(param.dataType());
    return ParameterProcessor.applyAnnotations(swagger, p, type == null ? String.class : type,
            Collections.<Annotation>singletonList(param));
}
 
Example #11
Source File: ResourceReaderExtension.java    From mdw with Apache License 2.0 5 votes vote down vote up
private Parameter readImplicitParameter(Swagger swagger, ApiImplicitParam param) {
    final Parameter p = createParam(param.paramType());
    if (p == null) {
        return null;
    }
    final Type type = typeFromString(param.dataType());
    return ParameterProcessor.applyAnnotations(swagger, p, type == null ? String.class : type,
            Collections.<Annotation>singletonList(param));
}
 
Example #12
Source File: ExtendedSwaggerReader.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private List<Parameter> getParameters(Type type, List<Annotation> annotations) {
    final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
    if (!chain.hasNext()) {
        return Collections.emptyList();
    }
    LOGGER.debug("getParameters for " + type);
    Set<Type> typesToSkip = new HashSet<>();
    final SwaggerExtension extension = chain.next();
    LOGGER.debug("trying extension " + extension);

    final List<Parameter> parameters = extension.extractParameters(annotations, type, typesToSkip, chain);
    if (parameters.size() > 0) {
        final List<Parameter> processed = new ArrayList<>(parameters.size());
        processed.addAll(parameters.stream().filter(parameter -> ParameterProcessor
                                                                         .applyAnnotations(swagger, parameter, type,
                                                                                           annotations) != null)
                                   .collect(Collectors.toList()));
        return processed;
    } else {
        LOGGER.debug("no parameter found, looking at body params");
        final List<Parameter> body = new ArrayList<>();
        if (!typesToSkip.contains(type)) {
            Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
            if (param != null) {
                body.add(param);
            }
        }
        return body;
    }
}
 
Example #13
Source File: AbstractReader.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected List<Parameter> getParameters(Type type, List<Annotation> annotations, Set<Type> typesToSkip) {
    if (!hasValidAnnotations(annotations) || isApiParamHidden(annotations)) {
        return Collections.emptyList();
    }

    Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
    List<Parameter> parameters = new ArrayList<>();
    Class<?> cls = TypeUtils.getRawType(type, type);
    LOG.debug("Looking for path/query/header/form/cookie params in " + cls);

    if (chain.hasNext()) {
        SwaggerExtension extension = chain.next();
        LOG.debug("trying extension " + extension);
        parameters = extension.extractParameters(annotations, type, typesToSkip, chain);
    }

    if (!parameters.isEmpty()) {
        for (Parameter parameter : parameters) {
            ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations);
        }
    } else {
        LOG.debug("Looking for body params in " + cls);
        // parameters is guaranteed to be empty at this point, replace it with a mutable collection
        parameters = Lists.newArrayList();
        if (!typesToSkip.contains(type)) {
            Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
            if (param != null) {
                parameters.add(param);
            }
        }
    }
    return parameters;
}
 
Example #14
Source File: ReaderUtils.java    From dorado with Apache License 2.0 4 votes vote down vote up
/**
 * Collects constructor-level parameters from class.
 *
 * @param cls     is a class for collecting
 * @param swagger is the instance of the Swagger
 * @return the collection of supported parameters
 */
public static List<Parameter> collectConstructorParameters(Class<?> cls, Swagger swagger) {
    if (cls.isLocalClass() || (cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers()))) {
        return Collections.emptyList();
    }

    List<Parameter> selected = Collections.emptyList();
    int maxParamsCount = 0;

    for (Constructor<?> constructor : cls.getDeclaredConstructors()) {
        if (!ReflectionUtils.isConstructorCompatible(constructor)
                && !ReflectionUtils.isInject(Arrays.asList(constructor.getDeclaredAnnotations()))) {
            continue;
        }

        final Type[] genericParameterTypes = constructor.getGenericParameterTypes();
        final Annotation[][] annotations = constructor.getParameterAnnotations();

        int paramsCount = 0;
        final List<Parameter> parameters = new ArrayList<Parameter>();
        for (int i = 0; i < genericParameterTypes.length; i++) {
            final List<Annotation> tmpAnnotations = Arrays.asList(annotations[i]);
            if (isContext(tmpAnnotations)) {
                paramsCount++;
            } else {
                final Type genericParameterType = genericParameterTypes[i];
                final List<Parameter> tmpParameters = collectParameters(genericParameterType, tmpAnnotations);
                if (tmpParameters.size() >= 1) {
                    for (Parameter tmpParameter : tmpParameters) {
                        if (ParameterProcessor.applyAnnotations(swagger, tmpParameter, genericParameterType, tmpAnnotations) != null) {
                            parameters.add(tmpParameter);
                        }
                    }
                    paramsCount++;
                }
            }
        }

        if (paramsCount >= maxParamsCount) {
            maxParamsCount = paramsCount;
            selected = parameters;
        }
    }

    return selected;
}
 
Example #15
Source File: Reader.java    From proteus with Apache License 2.0 4 votes vote down vote up
private List<Parameter> getParameters(Type type, List<Annotation> annotations, java.lang.reflect.Parameter methodParameter, List<String> pathParamNames) {
      final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();
      
       
      if (!chain.hasNext()) {
          return Collections.emptyList();
      }
 
      
   //   LOGGER.debug("getParameters for {}", type);
      Set<Type> typesToSkip = new HashSet<>();
      typesToSkip.add(TypeFactory.defaultInstance().constructType(ServerRequest.class));
      typesToSkip.add(TypeFactory.defaultInstance().constructType(HttpServerExchange.class));
      typesToSkip.add(TypeFactory.defaultInstance().constructType(ServerResponse.class));
      typesToSkip.add(TypeFactory.defaultInstance().constructType(HttpHandler.class));
      typesToSkip.add(TypeFactory.defaultInstance().constructType(io.undertow.server.session.Session.class));

      final SwaggerExtension extension = chain.next();
            
      if (typesToSkip.contains(type)) {
          return Collections.emptyList();
      }
 
 
      annotations = new ArrayList<>(annotations);

       
      if(! annotations.stream().filter( a -> a instanceof ApiParam ).findFirst().isPresent() )
      {
      	annotations.add( AnnotationHelper.createApiParam( methodParameter ) ) ; 
      }
      

if(type.getTypeName().contains("java.nio.file.Path") || type.getTypeName().contains("java.nio.ByteBuffer")  || type.getTypeName().contains("java.io.File"))
      { 
	  if(type.getTypeName().contains("java.nio.file.Path") || type.getTypeName().contains("java.nio.ByteBuffer"))
      {
      	type = java.io.File.class;
      }
	
	  annotations.add(AnnotationHelper.createFormParam(methodParameter));
	  
      }

      if(annotations.size() == 1)
      {
      	if( annotations.get(0) instanceof ApiParam)
      	{ 
      	    // If there is only one ApiParam and the parameter type is a member of the java.lang and the name of that parameter is in the path operation's path make the assumption that this is a path param
      		if(methodParameter.getType().getName().indexOf("java.lang") > -1 && pathParamNames.contains(methodParameter.getName()))
      		{
      			annotations.add(AnnotationHelper.createPathParam(methodParameter));

      		}
      	    // If there is only one ApiParam and the parameter type is a member of the java.lang or java.util package we make the assumption that this is a query param
      		else if( methodParameter.getType().getName().indexOf("java.lang") > -1 || methodParameter.getType().getName().indexOf("java.util") > -1 )
      		{
      			annotations.add(AnnotationHelper.createQueryParam(methodParameter));
      		}
      	}
      }
      
      final List<Parameter> parameters = extension.extractParameters(annotations, type, typesToSkip, chain);
      if (!parameters.isEmpty()) {
          final List<Parameter> processed = new ArrayList<Parameter>(parameters.size());
          for (Parameter parameter : parameters) {
          	
            //  LOGGER.debug("getParameters for {}", type);

              if (ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations) != null) {
              	
                  processed.add(parameter);
              }
          }
          return processed;
      } else {
        //  LOGGER.debug("no parameter found, looking at body params");
          final List<Parameter> body = new ArrayList<Parameter>();
          if (!typesToSkip.contains(type)) {
          	
              Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
              if (param != null) {
              	 
                  body.add(param);
              }
          }
          return body;
      }
  }
 
Example #16
Source File: SpringSwaggerExtension.java    From swagger-maven-plugin with Apache License 2.0 4 votes vote down vote up
private List<Parameter> extractParametersFromModelAttributeAnnotation(Type type, Map<Class<?>, Annotation> annotations) {
    ModelAttribute modelAttribute = (ModelAttribute)annotations.get(ModelAttribute.class);
    if ((modelAttribute == null || !hasClassStartingWith(annotations.keySet(), "org.springframework.web.bind.annotation"))&& BeanUtils.isSimpleProperty(TypeUtils.getRawType(type, null))) {
        return Collections.emptyList();
    }

    List<Parameter> parameters = new ArrayList<Parameter>();
    Class<?> clazz = TypeUtils.getRawType(type, type);
    for (PropertyDescriptor propertyDescriptor : BeanUtils.getPropertyDescriptors(clazz)) {
        // Get all the valid setter methods inside the bean
        Method propertyDescriptorSetter = propertyDescriptor.getWriteMethod();
        if (propertyDescriptorSetter != null) {
            ApiParam propertySetterApiParam = AnnotationUtils.findAnnotation(propertyDescriptorSetter, ApiParam.class);
            if (propertySetterApiParam == null) {
                // If we find a setter that doesn't have @ApiParam annotation, then skip it
                continue;
            }

            // Here we have a bean setter method that is annotted with @ApiParam, but we still
            // need to know what type of parameter to create. In order to do this, we look for
            // any annotation attached to the first method parameter of the setter fucntion.
            Annotation[][] parameterAnnotations = propertyDescriptorSetter.getParameterAnnotations();
            if (parameterAnnotations == null || parameterAnnotations.length == 0) {
                continue;
            }

            Class parameterClass = propertyDescriptor.getPropertyType();
            List<Parameter> propertySetterExtractedParameters = this.extractParametersFromAnnotation(
                    parameterClass, toMap(Arrays.asList(parameterAnnotations[0])));

            for (Parameter parameter : propertySetterExtractedParameters) {
                if (Strings.isNullOrEmpty(parameter.getName())) {
                    parameter.setName(propertyDescriptor.getDisplayName());
                }
                ParameterProcessor.applyAnnotations(new Swagger(), parameter, type, Lists.newArrayList(propertySetterApiParam));
            }
            parameters.addAll(propertySetterExtractedParameters);
        }
    }

    return parameters;
}