Search in sources :

Example 1 with RefProperty

use of io.swagger.models.properties.RefProperty in project swagger-core by swagger-api.

the class SwaggerSerializerTest method convertSpec.

@Test(description = "it should convert a spec")
public void convertSpec() throws IOException {
    final Model personModel = ModelConverters.getInstance().read(Person.class).get("Person");
    final Model errorModel = ModelConverters.getInstance().read(Error.class).get("Error");
    final Info info = new Info().version("1.0.0").title("Swagger Petstore");
    final Contact contact = new Contact().name("Swagger API Team").email("foo@bar.baz").url("http://swagger.io");
    info.setContact(contact);
    final Map<String, Object> map = new HashMap<String, Object>();
    map.put("name", "value");
    info.setVendorExtension("x-test2", map);
    info.setVendorExtension("x-test", "value");
    final Swagger swagger = new Swagger().info(info).host("petstore.swagger.io").securityDefinition("api-key", new ApiKeyAuthDefinition("key", In.HEADER)).scheme(Scheme.HTTP).consumes("application/json").produces("application/json").model("Person", personModel).model("Error", errorModel);
    final Operation get = new Operation().produces("application/json").summary("finds pets in the system").description("a longer description").tag("Pet Operations").operationId("get pet by id").deprecated(true);
    get.parameter(new QueryParameter().name("tags").description("tags to filter by").required(false).property(new StringProperty()));
    get.parameter(new PathParameter().name("petId").description("pet to fetch").property(new LongProperty()));
    final Response response = new Response().description("pets returned").schema(new RefProperty().asDefault("Person")).example("application/json", "fun!");
    final Response errorResponse = new Response().description("error response").schema(new RefProperty().asDefault("Error"));
    get.response(200, response).defaultResponse(errorResponse);
    final Operation post = new Operation().summary("adds a new pet").description("you can add a new pet this way").tag("Pet Operations").operationId("add pet").defaultResponse(errorResponse).parameter(new BodyParameter().description("the pet to add").schema(new RefModel().asDefault("Person")));
    swagger.path("/pets", new Path().get(get).post(post));
    final String swaggerJson = Json.mapper().writeValueAsString(swagger);
    final Swagger rebuilt = Json.mapper().readValue(swaggerJson, Swagger.class);
    SerializationMatchers.assertEqualsToJson(rebuilt, swaggerJson);
}
Also used : Path(io.swagger.models.Path) QueryParameter(io.swagger.models.parameters.QueryParameter) RefModel(io.swagger.models.RefModel) HashMap(java.util.HashMap) Error(io.swagger.models.Error) StringProperty(io.swagger.models.properties.StringProperty) Operation(io.swagger.models.Operation) Info(io.swagger.models.Info) BodyParameter(io.swagger.models.parameters.BodyParameter) PathParameter(io.swagger.models.parameters.PathParameter) Contact(io.swagger.models.Contact) RefProperty(io.swagger.models.properties.RefProperty) Response(io.swagger.models.Response) ApiKeyAuthDefinition(io.swagger.models.auth.ApiKeyAuthDefinition) Swagger(io.swagger.models.Swagger) LongProperty(io.swagger.models.properties.LongProperty) Model(io.swagger.models.Model) RefModel(io.swagger.models.RefModel) Person(io.swagger.models.Person) Test(org.testng.annotations.Test)

Example 2 with RefProperty

use of io.swagger.models.properties.RefProperty in project swagger-core by swagger-api.

the class ModelConverterTest method serializeParameterizedType.

@Test(description = "it should serialize a parameterized type per 606")
public void serializeParameterizedType() {
    final Map<String, Model> schemas = readAll(Employee.class);
    final ModelImpl employee = (ModelImpl) schemas.get("employee");
    final Map<String, Property> props = employee.getProperties();
    final Iterator<String> et = props.keySet().iterator();
    final Property id = props.get(et.next());
    assertTrue(id instanceof IntegerProperty);
    final Property firstName = props.get(et.next());
    assertTrue(firstName instanceof StringProperty);
    final Property lastName = props.get(et.next());
    assertTrue(lastName instanceof StringProperty);
    final Property department = props.get(et.next());
    assertTrue(department instanceof RefProperty);
    final Property manager = props.get(et.next());
    assertTrue(manager instanceof RefProperty);
    final Property team = props.get(et.next());
    assertTrue(team instanceof ArrayProperty);
    final ArrayProperty ap = (ArrayProperty) team;
    assertTrue(ap.getUniqueItems());
    assertNotNull(employee.getXml());
    assertEquals(employee.getXml().getName(), "employee");
}
Also used : BaseIntegerProperty(io.swagger.models.properties.BaseIntegerProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) AbstractModelWithApiModel(io.swagger.models.composition.AbstractModelWithApiModel) Model(io.swagger.models.Model) ModelWithApiModel(io.swagger.models.ModelWithApiModel) EmptyModel(io.swagger.models.EmptyModel) JodaDateTimeModel(io.swagger.models.JodaDateTimeModel) JacksonReadonlyModel(io.swagger.models.JacksonReadonlyModel) StringProperty(io.swagger.models.properties.StringProperty) ModelImpl(io.swagger.models.ModelImpl) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) LongProperty(io.swagger.models.properties.LongProperty) DecimalProperty(io.swagger.models.properties.DecimalProperty) Property(io.swagger.models.properties.Property) DoubleProperty(io.swagger.models.properties.DoubleProperty) MapProperty(io.swagger.models.properties.MapProperty) ApiModelProperty(io.swagger.annotations.ApiModelProperty) BaseIntegerProperty(io.swagger.models.properties.BaseIntegerProperty) ModelWithUrlProperty(io.swagger.models.composition.ModelWithUrlProperty) RefProperty(io.swagger.models.properties.RefProperty) FloatProperty(io.swagger.models.properties.FloatProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) RefProperty(io.swagger.models.properties.RefProperty) Test(org.testng.annotations.Test)

Example 3 with RefProperty

use of io.swagger.models.properties.RefProperty in project swagger-core by swagger-api.

the class ModelPropertyTest method extractProperties.

@Test
public void extractProperties() {
    final Map<String, Model> models = ModelConverters.getInstance().readAll(Family.class);
    assertEquals(models.size(), 3);
    final Model person = models.get("Person");
    final Property employer = person.getProperties().get("employer");
    assertTrue(employer instanceof ArrayProperty);
    final ArrayProperty employerProperty = (ArrayProperty) employer;
    final Property items = employerProperty.getItems();
    assertTrue(items instanceof RefProperty);
    assertEquals(((RefProperty) items).getSimpleRef(), "Employer");
    final Property awards = person.getProperties().get("awards");
    assertTrue(awards instanceof ArrayProperty);
    assertTrue(((ArrayProperty) awards).getItems() instanceof StringProperty);
}
Also used : ArrayProperty(io.swagger.models.properties.ArrayProperty) Model(io.swagger.models.Model) StringProperty(io.swagger.models.properties.StringProperty) ModelWithBooleanProperty(io.swagger.models.ModelWithBooleanProperty) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) BooleanProperty(io.swagger.models.properties.BooleanProperty) LongProperty(io.swagger.models.properties.LongProperty) RefProperty(io.swagger.models.properties.RefProperty) Property(io.swagger.models.properties.Property) RefProperty(io.swagger.models.properties.RefProperty) Test(org.testng.annotations.Test)

Example 4 with RefProperty

use of io.swagger.models.properties.RefProperty in project swagger-core by swagger-api.

the class ServletReaderExtension method applyResponses.

@Override
public void applyResponses(ReaderContext context, Operation operation, Method method) {
    final Map<Integer, Response> result = new HashMap<Integer, Response>();
    final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    if (apiOperation != null && StringUtils.isNotBlank(apiOperation.responseReference())) {
        final Response response = new Response().description(SUCCESSFUL_OPERATION);
        response.schema(new RefProperty(apiOperation.responseReference()));
        result.put(apiOperation.code(), response);
    }
    final Type responseType = getResponseType(method);
    if (isValidResponse(responseType)) {
        final Property property = ModelConverters.getInstance().readAsProperty(responseType);
        if (property != null) {
            final Property responseProperty = ContainerWrapper.wrapContainer(getResponseContainer(apiOperation), property);
            final int responseCode = apiOperation == null ? 200 : apiOperation.code();
            final Map<String, Property> defaultResponseHeaders = apiOperation == null ? Collections.<String, Property>emptyMap() : parseResponseHeaders(context, apiOperation.responseHeaders());
            final Response response = new Response().description(SUCCESSFUL_OPERATION).schema(responseProperty).headers(defaultResponseHeaders);
            result.put(responseCode, response);
            appendModels(context.getSwagger(), responseType);
        }
    }
    final ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);
    if (responseAnnotation != null) {
        for (ApiResponse apiResponse : responseAnnotation.value()) {
            final Map<String, Property> responseHeaders = parseResponseHeaders(context, apiResponse.responseHeaders());
            final Response response = new Response().description(apiResponse.message()).headers(responseHeaders);
            if (StringUtils.isNotEmpty(apiResponse.reference())) {
                response.schema(new RefProperty(apiResponse.reference()));
            } else if (!ReflectionUtils.isVoid(apiResponse.response())) {
                final Type type = apiResponse.response();
                final Property property = ModelConverters.getInstance().readAsProperty(type);
                if (property != null) {
                    response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property));
                    appendModels(context.getSwagger(), type);
                }
            }
            result.put(apiResponse.code(), response);
        }
    }
    for (Map.Entry<Integer, Response> responseEntry : result.entrySet()) {
        if (responseEntry.getKey() == 0) {
            operation.defaultResponse(responseEntry.getValue());
        } else {
            operation.response(responseEntry.getKey(), responseEntry.getValue());
        }
    }
}
Also used : HashMap(java.util.HashMap) ApiResponse(io.swagger.annotations.ApiResponse) RefProperty(io.swagger.models.properties.RefProperty) Response(io.swagger.models.Response) ApiResponse(io.swagger.annotations.ApiResponse) Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) ApiOperation(io.swagger.annotations.ApiOperation) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) MapProperty(io.swagger.models.properties.MapProperty) RefProperty(io.swagger.models.properties.RefProperty) Map(java.util.Map) HashMap(java.util.HashMap) ApiResponses(io.swagger.annotations.ApiResponses)

Example 5 with RefProperty

use of io.swagger.models.properties.RefProperty in project swagger-core by swagger-api.

the class Reader method parseMethod.

private Operation parseMethod(Class<?> cls, Method method, AnnotatedMethod annotatedMethod, List<Parameter> globalParameters, List<ApiResponse> classApiResponses) {
    Operation operation = new Operation();
    if (annotatedMethod != null) {
        method = annotatedMethod.getAnnotated();
    }
    ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);
    String operationId = null;
    // check if it's an inherited or implemented method.
    boolean methodInSuperType = false;
    if (!cls.isInterface()) {
        methodInSuperType = ReflectionUtils.findMethod(method, cls.getSuperclass()) != null;
    }
    if (!methodInSuperType) {
        for (Class<?> implementedInterface : cls.getInterfaces()) {
            methodInSuperType = ReflectionUtils.findMethod(method, implementedInterface) != null;
            if (methodInSuperType) {
                break;
            }
        }
    }
    if (!methodInSuperType) {
        operationId = method.getName();
    } else {
        operationId = this.getOperationId(method.getName());
    }
    String responseContainer = null;
    Type responseType = null;
    Map<String, Property> defaultResponseHeaders = new LinkedHashMap<String, Property>();
    if (apiOperation != null) {
        if (apiOperation.hidden()) {
            return null;
        }
        if (!apiOperation.nickname().isEmpty()) {
            operationId = apiOperation.nickname();
        }
        defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());
        operation.summary(apiOperation.value()).description(apiOperation.notes());
        if (!isVoid(apiOperation.response())) {
            responseType = apiOperation.response();
        }
        if (!apiOperation.responseContainer().isEmpty()) {
            responseContainer = apiOperation.responseContainer();
        }
        List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
        for (Authorization auth : apiOperation.authorizations()) {
            if (!auth.value().isEmpty()) {
                SecurityRequirement security = new SecurityRequirement();
                security.setName(auth.value());
                for (AuthorizationScope scope : auth.scopes()) {
                    if (!scope.scope().isEmpty()) {
                        security.addScope(scope.scope());
                    }
                }
                securities.add(security);
            }
        }
        for (SecurityRequirement sec : securities) {
            operation.security(sec);
        }
        if (!apiOperation.consumes().isEmpty()) {
            String[] consumesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.consumes() });
            for (String consume : consumesAr) {
                operation.consumes(consume);
            }
        }
        if (!apiOperation.produces().isEmpty()) {
            String[] producesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.produces() });
            for (String produce : producesAr) {
                operation.produces(produce);
            }
        }
    }
    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 (operation.getConsumes() == null || operation.getConsumes().isEmpty()) {
        final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class);
        if (consumes != null) {
            for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) {
                operation.consumes(mediaType);
            }
        }
    }
    if (operation.getProduces() == null || operation.getProduces().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) {
        addResponse(operation, apiResponse);
    }
    // merge class level @ApiResponse
    for (ApiResponse apiResponse : classApiResponses) {
        String key = (apiResponse.code() == 0) ? "default" : String.valueOf(apiResponse.code());
        if (operation.getResponses() != null && operation.getResponses().containsKey(key)) {
            continue;
        }
        addResponse(operation, apiResponse);
    }
    if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) {
        operation.setDeprecated(true);
    }
    // process parameters
    for (Parameter globalParameter : globalParameters) {
        operation.parameter(globalParameter);
    }
    Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method);
    if (annotatedMethod == null) {
        Type[] genericParameterTypes = method.getGenericParameterTypes();
        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);
            }
        }
    } else {
        for (int i = 0; i < annotatedMethod.getParameterCount(); i++) {
            AnnotatedParameter param = annotatedMethod.getParameter(i);
            final Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), 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);
    }
    processOperationDecorator(operation, method);
    return operation;
}
Also used : AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter) ArrayList(java.util.ArrayList) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.models.Operation) ApiResponse(io.swagger.annotations.ApiResponse) LinkedHashMap(java.util.LinkedHashMap) RefProperty(io.swagger.models.properties.RefProperty) Authorization(io.swagger.annotations.Authorization) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) MapProperty(io.swagger.models.properties.MapProperty) RefProperty(io.swagger.models.properties.RefProperty) ApiResponses(io.swagger.annotations.ApiResponses) Response(io.swagger.models.Response) ApiResponse(io.swagger.annotations.ApiResponse) Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) ParameterizedType(java.lang.reflect.ParameterizedType) Produces(javax.ws.rs.Produces) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) HeaderParameter(io.swagger.models.parameters.HeaderParameter) AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter) AuthorizationScope(io.swagger.annotations.AuthorizationScope) SecurityRequirement(io.swagger.models.SecurityRequirement)

Aggregations

RefProperty (io.swagger.models.properties.RefProperty)74 Property (io.swagger.models.properties.Property)50 ArrayProperty (io.swagger.models.properties.ArrayProperty)46 StringProperty (io.swagger.models.properties.StringProperty)35 Test (org.testng.annotations.Test)35 Model (io.swagger.models.Model)23 MapProperty (io.swagger.models.properties.MapProperty)20 ModelImpl (io.swagger.models.ModelImpl)18 Response (io.swagger.models.Response)18 IntegerProperty (io.swagger.models.properties.IntegerProperty)18 Operation (io.swagger.models.Operation)17 RefModel (io.swagger.models.RefModel)17 LongProperty (io.swagger.models.properties.LongProperty)14 Path (io.swagger.models.Path)12 Swagger (io.swagger.models.Swagger)12 ArrayList (java.util.ArrayList)12 HashMap (java.util.HashMap)12 ArrayModel (io.swagger.models.ArrayModel)11 BodyParameter (io.swagger.models.parameters.BodyParameter)11 Map (java.util.Map)11