Java Code Examples for io.swagger.models.parameters.Parameter#getName()

The following examples show how to use io.swagger.models.parameters.Parameter#getName() . 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: NotOnlyEnumValuesRule.java    From swagger-coverage with Apache License 2.0 6 votes vote down vote up
@Override
public Condition processParameter(Parameter parameter) {
    List<String> enumValues = SwaggerSpecificationProcessor.extractEnum(parameter);

    if (enumValues != null && !enumValues.isEmpty()) {
        ConditionPredicate predicate = new NotOnlyParameterListValueConditionPredicate(
                parameter.getName(), parameter.getIn(), enumValues
        );

        return new SinglePredicateCondition(
                String.format("%s «%s»  contains values not only from enum", parameter.getIn(), parameter.getName()),
                "",
                predicate
        );
    }

    return null;
}
 
Example 2
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 3
Source File: BaseParameterValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public Status validate(final String value, final Parameter p) {

    if (!supports(p)) {
        return null;
    }

    final SerializableParameter parameter = (SerializableParameter)p;

    if (parameter.getRequired() && (value == null || value.trim().isEmpty())) {
        return new Status("ERR11001", p.getName());
    }

    if (value == null || value.trim().isEmpty()) {
        return null;
    }

    if (!matchesEnumIfDefined(value, parameter)) {
        return new Status("ERR11002", value, parameter.getName(), parameter.getEnum());
    }
    return doValidate(value, parameter);
}
 
Example 4
Source File: ArrayParameterValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
public Status validate(final Collection<String> values, final Parameter p) {
    if (p == null) {
        return null;
    }

    final SerializableParameter parameter = (SerializableParameter)p;
    if (parameter.getRequired() && (values == null || values.isEmpty())) {
        return new Status("ERR11001", parameter.getName());
    }

    if (values == null) {
        return null;
    }

    if (!parameter.getCollectionFormat().equalsIgnoreCase(CollectionFormat.MULTI.name())) {
        return new Status("ERR11005", p.getName(), parameter.getCollectionFormat(), "multi");
    }

    return doValidate(values, parameter);
}
 
Example 5
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateHeader(final HttpServerExchange exchange,
                              final SwaggerOperation swaggerOperation,
                              final Parameter headerParameter) {

    final HeaderValues headerValues = exchange.getRequestHeaders().get(headerParameter.getName());
    if ((headerValues == null || headerValues.isEmpty())) {
        if(headerParameter.getRequired()) {
            return new Status(VALIDATOR_REQUEST_PARAMETER_HEADER_MISSING, headerParameter.getName(), swaggerOperation.getPathString().original());
        }
    } else {

        Optional<Status> optional = headerValues
                .stream()
                .map((v) -> parameterValidators.validate(v, headerParameter))
                .filter(s -> s != null)
                .findFirst();
        if(optional.isPresent()) {
            return optional.get();
        }
    }
    return null;
}
 
Example 6
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateQueryParameter(final HttpServerExchange exchange,
                                      final SwaggerOperation swaggerOperation,
                                      final Parameter queryParameter) {

    final Collection<String> queryParameterValues = exchange.getQueryParameters().get(queryParameter.getName());

    if ((queryParameterValues == null || queryParameterValues.isEmpty())) {
        if(queryParameter.getRequired()) {
            return new Status(VALIDATOR_REQUEST_PARAMETER_QUERY_MISSING, queryParameter.getName(), swaggerOperation.getPathString().original());
        }
    } else {

        Optional<Status> optional = queryParameterValues
                .stream()
                .map((v) -> parameterValidators.validate(v, queryParameter))
                .filter(s -> s != null)
                .findFirst();
        if(optional.isPresent()) {
            return optional.get();
        }
    }
    return null;
}
 
Example 7
Source File: JaxrsReader.java    From swagger-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void readCommonParameters(Class<?> cls) {
    Path path = AnnotationUtils.findAnnotation(cls, Path.class);
    if (path != null) {
        return;
    }

    List<Method> filteredMethods = getFilteredMethods(cls);
    for (Method method : filteredMethods) {
        path = AnnotationUtils.findAnnotation(method, Path.class);
        if (path != null) {
            return;
        }

        String httpMethod = extractOperationMethod(null, method, SwaggerExtensions.chain());
        if (httpMethod != null) {
            return;
        }
    }

    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();
        if (annotations.length > 0) {
            List<Parameter> params = getParameters(cls, Arrays.asList(annotations));
            for (Parameter param : params) {
                if (hasCommonParameter(param)) {
                    String msg = "[" + cls.getCanonicalName() + "] Redefining common parameter '" + param.getName()
                        + "' already defined elsewhere";
                    throw new RuntimeException(msg);
                }
                swagger.addParameter(param.getName(), param);
            }
        }
    }
}
 
Example 8
Source File: SwaggerSpecificationProcessor.java    From swagger-coverage with Apache License 2.0 5 votes vote down vote up
public static String extractValue(Parameter p) {
    if (p.getVendorExtensions() == null) {
        return p.getName();
    }

    if (p.getVendorExtensions().containsKey(X_EXAMPLE)) {
        return (String) p.getVendorExtensions().get(X_EXAMPLE);
    }

    return p.getName();
}
 
Example 9
Source File: SequenceGenerator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void populateParametersFromOperation(Operation operation, Map<String, Model> definitions,
        Map<String, String> parameterJsonPathMapping, Map<String, String> queryParameters) {

    List<Parameter> parameters = operation.getParameters();
    for (Parameter parameter : parameters) {
        String name = parameter.getName();
        if (parameter instanceof BodyParameter) {
            Model schema = ((BodyParameter) parameter).getSchema();
            if (schema instanceof RefModel) {
                String $ref = ((RefModel) schema).get$ref();
                if (StringUtils.isNotBlank($ref)) {
                    String defName = $ref.substring("#/definitions/".length());
                    Model model = definitions.get(defName);
                    Example example = ExampleBuilder.fromModel(defName, model, definitions, new HashSet<String>());

                    String jsonExample = Json.pretty(example);
                    try {
                        org.json.JSONObject json = new org.json.JSONObject(jsonExample);
                        SequenceUtils.listJson(json, parameterJsonPathMapping);
                    } catch (JSONException e) {
                        log.error("Error occurred while generating json mapping for the definition: " + defName, e);
                    }
                }
            }
        }
        if (parameter instanceof QueryParameter) {
            String type = ((QueryParameter) parameter).getType();
            queryParameters.put(name, type);
        }
    }
}
 
Example 10
Source File: UtilityPathExample.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
     * @param context                    to get configurations and to use in ParameterAdapter
     * @param definitionDocumentResolver to use in ParameterAdapter
     * @param operation                  the Swagger Operation
     */
    public UtilityPathExample(Swagger2MarkupConverter.SwaggerContext context,
                              DocumentResolver definitionDocumentResolver,
                              SwaggerPathOperation operation) {
        super(context, definitionDocumentResolver, operation);


        List<Parameter> bodyParameters = operation
                .getOperation()
                .getParameters()
                .stream()
                .filter(it -> it.getIn().equals("body"))
                .collect(Collectors.toList());

        if (!bodyParameters.isEmpty()) {
            Parameter bodyParameter = bodyParameters.get(0);
            data = "{" + bodyParameter.getName() + "}";
        }


//        operation.getOperation().getSecurity().forEach({ it->
//
//        });

        headerParameters = operation
                .getOperation()
                .getParameters()
                .stream()
                .filter(it -> it.getIn().equals("header"))
                .map(it ->
                        new ParameterAdapter(
                                context,
                                operation,
                                it,
                                definitionDocumentResolver
                        ))
                .collect(Collectors.toMap(ParameterAdapter::getName, it -> "{" + it.getName() + "}"));


    }
 
Example 11
Source File: CookieProcessorCreator.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
  JavaType targetType =
      genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType);
  return new CookieProcessor(parameter.getName(), targetType, ((CookieParameter) parameter).getDefaultValue(),
      parameter.getRequired());
}
 
Example 12
Source File: FlaskConnexionCodegen.java    From TypeScript-Microservices with MIT License 5 votes vote down vote up
@Override
public void preprocessSwagger(Swagger swagger) {
    // need vendor extensions for x-swagger-router-controller
    Map<String, Path> paths = swagger.getPaths();
    if(paths != null) {
        for(String pathname : paths.keySet()) {
            Path path = paths.get(pathname);
            Map<HttpMethod, Operation> operationMap = path.getOperationMap();
            if(operationMap != null) {
                for(HttpMethod method : operationMap.keySet()) {
                    Operation operation = operationMap.get(method);
                    String tag = "default";
                    if(operation.getTags() != null && operation.getTags().size() > 0) {
                        tag = operation.getTags().get(0);
                    }
                    String operationId = operation.getOperationId();
                    if(operationId == null) {
                        operationId = getOrGenerateOperationId(operation, pathname, method.toString());
                    }
                    operation.setOperationId(toOperationId(operationId));
                    if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) {
                        operation.getVendorExtensions().put(
                                "x-swagger-router-controller",
                                controllerPackage + "." + toApiFilename(tag)
                        );
                    }
                    for (Parameter param: operation.getParameters()) {
                        // sanitize the param name but don't underscore it since it's used for request mapping
                        String name = param.getName();
                        String paramName = sanitizeName(name);
                        if (!paramName.equals(name)) {
                            LOGGER.warn(name + " cannot be used as parameter name with flask-connexion and was sanitized as " + paramName);
                        }
                        param.setName(paramName);
                    }
                }
            }
        }
    }
}
 
Example 13
Source File: EmptyHeaderRule.java    From swagger-coverage with Apache License 2.0 5 votes vote down vote up
@Override
public Condition processParameter(Parameter parameter) {
    if (parameter instanceof HeaderParameter) {
        ConditionPredicate predicate = new DefaultParameterConditionPredicate(true, parameter.getName(), parameter.getIn());
        return new SinglePredicateCondition(
                String.format("header «%s» is empty", parameter.getName()),
                "",
                predicate
        );
    }

    return null;
}
 
Example 14
Source File: NotEmptyParameterRule.java    From swagger-coverage with Apache License 2.0 5 votes vote down vote up
@Override
public Condition processParameter(Parameter parameter) {
    if (parameter instanceof BodyParameter) {
        return null;
    }

    ConditionPredicate predicate = new DefaultParameterConditionPredicate(false, parameter.getName(), parameter.getIn());
    return new SinglePredicateCondition(
            String.format("%s «%s» is not empty", parameter.getIn(), parameter.getName()),
            "",
            predicate
    );
}
 
Example 15
Source File: EnumAllValuesRule.java    From swagger-coverage with Apache License 2.0 5 votes vote down vote up
@Override
public Condition processParameter(Parameter parameter) {
    List<String> enumValues = SwaggerSpecificationProcessor.extractEnum(parameter);

    if (enumValues != null && !enumValues.isEmpty()) {
        ConditionPredicate predicate = new ParameterValueConditionPredicate(parameter.getName(), parameter.getIn(), enumValues);
        return new SinglePredicateCondition(
                String.format("%s «%s» contains all values from enum %s", parameter.getIn(), parameter.getName(), enumValues),
                "",
                predicate
        );
    }

    return null;
}
 
Example 16
Source File: PathProcessorCreator.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@Override
public ParamValueProcessor create(Parameter parameter, Type genericParamType) {
  JavaType targetType =
      genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType);
  return new PathProcessor(parameter.getName(), targetType, ((PathParameter) parameter).getDefaultValue(), true);
}
 
Example 17
Source File: RestParam.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public RestParam(Parameter parameter, Type genericParamType) {
  this.paramName = parameter.getName();

  init(parameter, genericParamType);
}
 
Example 18
Source File: DefaultGenerator.java    From TypeScript-Microservices with MIT License 4 votes vote down vote up
private static String generateParameterId(Parameter parameter) {
    return parameter.getName() + ":" + parameter.getIn();
}
 
Example 19
Source File: ApiGatewaySdkSwaggerApiImporter.java    From aws-apigateway-importer with Apache License 2.0 4 votes vote down vote up
private String createRequestParameterExpression(Parameter p) {
    Optional<String> loc = getParameterLocation(p);
    return "method.request." + loc.get() + "." + p.getName();
}
 
Example 20
Source File: ConsumerDrivenValidator.java    From assertj-swagger with Apache License 2.0 2 votes vote down vote up
/**
 * Generates a unique key for a parameter.
 * <p>
 * From <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject" target="_top">OpenAPI Specification</a>
 * "A unique parameter is defined by a combination of a name and location."
 *
 * @param parameter the parameter to generate a unique key for
 * @return a unique key based on name and location ({@link Parameter#getIn()})
 */
private String parameterUniqueKey(Parameter parameter) {
    return parameter.getName() + parameter.getIn();
}