io.swagger.models.parameters.Parameter Java Examples

The following examples show how to use io.swagger.models.parameters.Parameter. 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: AbstractOperationGenerator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected void initMethodParameterGenerators(Map<String, List<Annotation>> methodAnnotationMap) {
  for (java.lang.reflect.Parameter methodParameter : method.getParameters()) {
    Type genericType = ParamUtils.getGenericParameterType(clazz, method, methodParameter);
    ParameterGenerator parameterGenerator = new ParameterGenerator(method, methodAnnotationMap, methodParameter,
        genericType);
    validateParameter(parameterGenerator.getGenericType());
    if (isContextParameter(parameterGenerator.getGenericType())) {
      continue;
    }

    // jaxrs: @BeanParam
    // springmvc: is query, and is bean type
    if (isAggregatedParameter(parameterGenerator, methodParameter)) {
      extractAggregatedParameterGenerators(methodAnnotationMap, methodParameter);
      continue;
    }

    parameterGenerators.add(parameterGenerator);
  }
}
 
Example #2
Source File: SwaggerGeneratorUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public static Type collectGenericType(List<Annotation> annotations, Type defaultType) {
  Type genericType = null;
  for (Annotation annotation : annotations) {
    ParameterProcessor<Parameter, Annotation> processor = findParameterProcessors(annotation.annotationType());
    if (processor == null) {
      continue;
    }

    Type type = processor.getGenericType(annotation);
    if (type != null) {
      genericType = type;
    }
  }

  return genericType != null ? genericType : defaultType;
}
 
Example #3
Source File: BodyParameterExtractor.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Override
public Object extract(String name, Parameter parameter, RoutingContext context) {
    BodyParameter bodyParam = (BodyParameter) parameter;
    if ("".equals(context.getBodyAsString())) {
        if (bodyParam.getRequired())
            throw new IllegalArgumentException("Missing required parameter: " + name);
        else
            return null;
    }

    try {
        if(bodyParam.getSchema() instanceof ArrayModel) {
            return context.getBodyAsJsonArray();
        } else {
            return context.getBodyAsJson();
        }
    } catch (DecodeException e) {
        return context.getBodyAsString();  
    }
}
 
Example #4
Source File: AbstractOperationGenerator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected Parameter createParameter(HttpParameterType httpParameterType) {
  switch (httpParameterType) {
    case PATH:
      return new PathParameter();
    case QUERY:
      return new QueryParameter();
    case HEADER:
      return new HeaderParameter();
    case FORM:
      return new FormParameter();
    case COOKIE:
      return new CookieParameter();
    case BODY:
      return new BodyParameter();
    default:
      throw new IllegalStateException("not support httpParameterType " + httpParameterType);
  }
}
 
Example #5
Source File: ParameterContributorTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testContribute() {
  underTest.contribute(swagger);

  assertContributedMap(true);

  Parameter param = PARAMS.iterator().next();
  verify(getOperationPath1).addParameter(param);
  verify(postOperationPath1).addParameter(param);
  verify(getOperationPath2).addParameter(param);
  verify(postOperationPath2).addParameter(param);

  // call it again for short-circuit use case
  reset(getOperationPath1, postOperationPath1, getOperationPath2, postOperationPath2);
  underTest.contribute(swagger);
  verify(getOperationPath1, never()).addParameter(param);
  verify(postOperationPath1, never()).addParameter(param);
  verify(getOperationPath2, never()).addParameter(param);
  verify(postOperationPath2, never()).addParameter(param);
}
 
Example #6
Source File: ConsumerDrivenValidator.java    From assertj-swagger with Apache License 2.0 6 votes vote down vote up
private void validateParameters(List<Parameter> actualOperationParameters,  List<Parameter> expectedOperationParameters, String httpMethod, String path) {
    String message = String.format("Checking parameters of '%s' operation of path '%s'.", httpMethod, path);
    Map<String, Parameter> actualParametersMap = new HashMap<>();
    for (final Parameter parameter : actualOperationParameters) {
        actualParametersMap.put(parameterUniqueKey(parameter), parameter);
    }
    // All expectedParameters must be there and must match.
    for (final Parameter expectedParameter : expectedOperationParameters) {
        final String parameterName = expectedParameter.getName();
        Parameter actualParameter = actualParametersMap.remove(parameterUniqueKey(expectedParameter));
        String actualParameterNotNullMessage = String.format("%s Expected parameter with name='%s' and in='%s' is missing", message, expectedParameter.getName(), expectedParameter.getIn());
        softAssertions.assertThat(actualParameter).as(actualParameterNotNullMessage).isNotNull();
        validateParameter(actualParameter, expectedParameter, parameterName, httpMethod, path);
    }
    // If there are any extra parameters, these are OK, as long as they are optional.
    for (final Parameter extraParameter : actualParametersMap.values()) {
        String extraParameterNotOptionalMessage = String.format("%s Unexpected parameter with name='%s' and in='%s' is missing", message, extraParameter.getName(), extraParameter.getIn());
        softAssertions.assertThat(extraParameter.getRequired()).as(extraParameterNotOptionalMessage).isFalse();
    }
}
 
Example #7
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validatePathParameters(final NormalisedPath requestPath,
                                      final SwaggerOperation swaggerOperation) {
    Status status = null;
    for (int i = 0; i < swaggerOperation.getPathString().parts().size(); i++) {
        if (!swaggerOperation.getPathString().isParam(i)) {
            continue;
        }

        final String paramName = swaggerOperation.getPathString().paramName(i);
        final String paramValue = requestPath.part(i);

        final Optional<Parameter> parameter = swaggerOperation.getOperation().getParameters()
                .stream()
                .filter(p -> p.getIn().equalsIgnoreCase("PATH"))
                .filter(p -> p.getName().equalsIgnoreCase(paramName))
                .findFirst();

        if (parameter.isPresent()) {
            status = parameterValidators.validate(paramValue, parameter.get());
        }
    }
    return status;
}
 
Example #8
Source File: SwaggerUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public static boolean isFileParameter(Parameter parameter) {
  if (!(parameter instanceof FormParameter)) {
    return false;
  }

  FormParameter formParameter = (FormParameter) parameter;
  if (FileProperty.isType(formParameter.getType(), formParameter.getFormat())) {
    return true;
  }

  Property property = formParameter.getItems();
  if (!ArrayProperty.isType(formParameter.getType()) || property == null) {
    return false;
  }

  return FileProperty.isType(property.getType(), property.getFormat());
}
 
Example #9
Source File: ResourceReaderExtension.java    From mdw with Apache License 2.0 6 votes vote down vote up
/**
 * Implemented to allow loading of custom types using PackageClassLoader.
 */
@Override
public void applyImplicitParameters(ReaderContext context, Operation operation, Method method) {
    // copied from io.swagger.servlet.extensions.ServletReaderExtension
    final ApiImplicitParams implicitParams = method.getAnnotation(ApiImplicitParams.class);
    if (implicitParams != null && implicitParams.value().length > 0) {
        for (ApiImplicitParam param : implicitParams.value()) {
            final Parameter p = readImplicitParameter(context.getSwagger(), param);
            if (p != null) {
                if (p instanceof BodyParameter && param.format() != null)
                    p.getVendorExtensions().put("format", param.format());
                operation.parameter(p);
            }
        }
    }
}
 
Example #10
Source File: AbstractArgumentsMapperCreator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param providerParamIdx
 * @param providerParameter processing provider parameter
 * @param parameterName
 * @return true means processed
 */
protected boolean processKnownParameter(int providerParamIdx, java.lang.reflect.Parameter providerParameter,
    String parameterName) {
  Integer swaggerIdx = findSwaggerParameterIndex(parameterName);
  if (swaggerIdx == null) {
    return false;
  }

  // complex scenes
  // swagger: int add(Body x)
  // producer: int add(int x, int y)
  if (bodyParameter != null &&
      !SwaggerUtils.isBean(providerParameter.getType()) &&
      swaggerIdx == swaggerBodyIdx &&
      SwaggerUtils.isBean(bodyParameter.getSchema())) {
    return false;
  }

  ArgumentMapper mapper = createKnownParameterMapper(providerParamIdx, swaggerIdx);
  mappers.add(mapper);
  return true;
}
 
Example #11
Source File: BodyProcessorCreator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
  Model model = ((BodyParameter) parameter).getSchema();
  JavaType swaggerType = null;
  if (model instanceof ModelImpl) {
    swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat());
  }
  boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class);

  JavaType targetType =
      genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType);
  boolean rawJson = SwaggerUtils.isRawJsonType(parameter);
  if (rawJson) {
    return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions()
        .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired());
  }

  return new BodyProcessor(targetType, (String) parameter.getVendorExtensions()
      .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired());
}
 
Example #12
Source File: BasicPathExample.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Override
public void updatePathParameterValue(Parameter parameter, Object example) {
    if (parameter.getName().contains("id")) {
        System.getenv();
    }

    if (example == null)
        return;

    if (path.contains(parameter.getName()))
        path = StringUtils.replace(
                path,
                '{' + parameter.getName() + '}',
                encodeExampleForUrl(example)
        );
}
 
Example #13
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 #14
Source File: HighwayCodec.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private static Map<String, Object> addPrimitiveTypeDefaultValues(Invocation invocation,
    Map<String, Object> swaggerArguments) {
  // proto buffer never serialize default values, put it back in provider
  if (invocation.getOperationMeta().getSwaggerProducerOperation() != null && !invocation.isEdge()) {
    List<Parameter> swaggerParameters = invocation.getOperationMeta().getSwaggerOperation()
        .getParameters();
    for (Parameter parameter : swaggerParameters) {
      if (swaggerArguments.get(parameter.getName()) == null) {
        Type type = invocation.getOperationMeta().getSwaggerProducerOperation()
            .getSwaggerParameterType(parameter.getName());
        if (type instanceof Class) {
          if (((Class) type).isPrimitive()) {
            swaggerArguments.put(parameter.getName(), Defaults.defaultValue((Class) type));
          }
        }
      }
    }
  }
  return swaggerArguments;
}
 
Example #15
Source File: SwaggerToProtoGenerator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void fillRequestType(Operation operation, ProtoMethod protoMethod) {
  List<Parameter> parameters = operation.getParameters();
  if (parameters.isEmpty()) {
    addImports(ProtoConst.EMPTY_PROTO);
    protoMethod.setArgTypeName(ProtoConst.EMPTY.getCanonicalName());
    return;
  }

  if (parameters.size() == 1) {
    String type = convertSwaggerType(parameters.get(0));
    if (messages.contains(type)) {
      protoMethod.setArgTypeName(type);
      return;
    }
  }

  String wrapName = StringUtils.capitalize(operation.getOperationId()) + "RequestWrap";
  createWrapArgs(wrapName, parameters);

  protoMethod.setArgTypeName(wrapName);
}
 
Example #16
Source File: RestOperationMeta.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * EdgeService cannot recognize the map type form body whose value type is String,
 * so there should be this additional setting.
 * @param parameter the swagger information of the parameter
 * @param type the resolved param type
 * @return the corrected param type
 */
private Type correctFormBodyType(Parameter parameter, Type type) {
  if (null != type || !(parameter instanceof BodyParameter)) {
    return type;
  }
  final BodyParameter bodyParameter = (BodyParameter) parameter;
  if (!(bodyParameter.getSchema() instanceof ModelImpl)) {
    return type;
  }
  final Property additionalProperties = ((ModelImpl) bodyParameter.getSchema()).getAdditionalProperties();
  if (additionalProperties instanceof StringProperty) {
    type = RestObjectMapperFactory.getRestObjectMapper().getTypeFactory()
        .constructMapType(Map.class, String.class, String.class);
  }
  return type;
}
 
Example #17
Source File: Reader.java    From swagger-dubbo with Apache License 2.0 5 votes vote down vote up
/**
 * Scans a set of classes for Swagger annotations.
 *
 * @param swagger
 *            is the Swagger instance
 * @param classes
 *            are a set of classes to scan
 */
public static void read(Swagger swagger, Set<Class<?>> classes) {
	final Reader reader = new Reader(swagger);
	for (Class<?> cls : classes) {
		final ReaderContext context = new ReaderContext(swagger, cls, cls, "", null, false,
				new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(),
				new ArrayList<Parameter>());
		reader.read(context);
	}
}
 
Example #18
Source File: ReaderContext.java    From swagger-dubbo with Apache License 2.0 5 votes vote down vote up
public ReaderContext(Swagger swagger, Class<?> refCls, Class<?> interfaceCls, String parentPath,
		String parentHttpMethod, boolean readHidden, List<String> parentConsumes,
		List<String> parentProduces, List<String> parentTags,
		List<Parameter> parentParameters) {
	setSwagger(swagger);
	setRefCls(refCls);
	setInterfaceCls(interfaceCls);
	setParentPath(parentPath);
	setParentHttpMethod(parentHttpMethod);
	setReadHidden(readHidden);
	setParentConsumes(parentConsumes);
	setParentProduces(parentProduces);
	setParentTags(parentTags);
	setParentParameters(parentParameters);
}
 
Example #19
Source File: AbstractArgumentsMapperCreator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param providerParamIdx
 * @param providerParameter processing provider parameter
 * @return true means processed
 */
protected boolean processContextParameter(int providerParamIdx, java.lang.reflect.Parameter providerParameter) {
  ContextArgumentMapperFactory contextFactory = contextFactorys.get(providerParameter.getType());
  if (contextFactory == null) {
    return false;
  }

  mappers.add(contextFactory
      .create(this.providerMethod.getParameters()[providerParamIdx].getName(), providerParameter.getName()));
  return true;
}
 
Example #20
Source File: PojoOperationGenerator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
protected void fillParameter(Swagger swagger, Parameter parameter, String parameterName, Type type,
    List<Annotation> annotations) {
  if (isWrapBody(parameter)) {
    return;
  }

  super.fillParameter(swagger, parameter, parameterName, type, annotations);
}
 
Example #21
Source File: DubboReaderExtension.java    From swagger-dubbo with Apache License 2.0 5 votes vote down vote up
@Override
public void applyImplicitParameters(ReaderContext context, Operation operation, Method method) {
	final ApiImplicitParams implicitParams = method.getAnnotation(ApiImplicitParams.class);
	if (implicitParams != null && implicitParams.value().length > 0) {
		for (ApiImplicitParam param : implicitParams.value()) {
			final Parameter p = readImplicitParam(context.getSwagger(), param);
			if (p != null) {
				operation.parameter(p);
			}
		}
	}
}
 
Example #22
Source File: Reader.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Scans a set of classes for Swagger annotations.
 *
 * @param swagger is the Swagger instance
 * @param classes are a set of classes to scan
 */
public static void read(Swagger swagger, Set<Class<?>> classes) {
    final Reader reader = new Reader(swagger);
    for (Class<?> cls : classes) {
        final ReaderContext context = new ReaderContext(swagger, cls, cls, "", null, false,
            new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(),
            new ArrayList<Parameter>());
        reader.read(context);
    }
}
 
Example #23
Source File: BasicPathExample.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Override
public void updateQueryParameterValue(Parameter parameter, Object example) {
    if (example == null)
        return;

    if (query.contains(parameter.getName()))
        query = StringUtils.replace(
                query,
                '{' + parameter.getName() + '}',
                encodeExampleForUrl(example)
        );
}
 
Example #24
Source File: SpringSwaggerExtensionTest.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractParametersNoModelAttributeAnnotation() {
    List<Parameter> parameters = new SpringSwaggerExtension(new SystemStreamLog()).extractParameters(
            Lists.newArrayList(),
            PaginationHelper.class,
            Sets.<Type>newHashSet(),
            Lists.<SwaggerExtension>newArrayList().iterator());

    assertEquals(parameters.size(), 2);
}
 
Example #25
Source File: ReaderContext.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public ReaderContext(Swagger swagger, Class<?> refCls, Class<?> interfaceCls, String parentPath,
                     String parentHttpMethod, boolean readHidden, List<String> parentConsumes,
                     List<String> parentProduces, List<String> parentTags,
                     List<Parameter> parentParameters) {
    setSwagger(swagger);
    setRefCls(refCls);
    setInterfaceCls(interfaceCls);
    setParentPath(parentPath);
    setParentHttpMethod(parentHttpMethod);
    setReadHidden(readHidden);
    setParentConsumes(parentConsumes);
    setParentProduces(parentProduces);
    setParentTags(parentTags);
    setParentParameters(parentParameters);
}
 
Example #26
Source File: SwaggerExtension.java    From dorado with Apache License 2.0 5 votes vote down vote up
default public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip,
		Iterator<SwaggerExtension> chain) {
	if (chain.hasNext()) {
		return chain.next().extractParameters(annotations, type, typesToSkip, chain);
	} else {
		return Collections.emptyList();
	}
}
 
Example #27
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 #28
Source File: ParameterGenerator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public ParameterGenerator(Executable executable, Map<String, List<Annotation>> methodAnnotationMap,
    java.lang.reflect.Parameter methodParameter, Type genericType) {
  this(executable,
      methodAnnotationMap,
      methodParameter.isNamePresent() ? methodParameter.getName() : null,
      methodParameter.getAnnotations(),
      genericType);
}
 
Example #29
Source File: Reader.java    From dorado with Apache License 2.0 5 votes vote down vote up
/**
 * Scans a single class for Swagger annotations - does not invoke
 * ReaderListeners
 */
public Swagger read(Class<?> cls) {
	SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);
	if (swaggerDefinition != null) {
		readSwaggerConfig(cls, swaggerDefinition);
	}

	return read(cls, new LinkedHashMap<String, Tag>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
}
 
Example #30
Source File: Reader.java    From dorado with Apache License 2.0 5 votes vote down vote up
private void processImplicitParams(ApiImplicitParams implicitParams, Operation operation) {
	if (implicitParams != null) {
		for (ApiImplicitParam param : implicitParams.value()) {
			Parameter p = readImplicitParam(param);
			if (p != null) {
				operation.addParameter(p);
			}
		}
	}
}