diff --git a/src/main/java/io/sinistral/proteus/server/ServerRequest.java b/src/main/java/io/sinistral/proteus/server/ServerRequest.java index b4091d8..a595e2c 100644 --- a/src/main/java/io/sinistral/proteus/server/ServerRequest.java +++ b/src/main/java/io/sinistral/proteus/server/ServerRequest.java @@ -10,10 +10,6 @@ import java.util.Deque; import java.util.Map; import java.util.concurrent.Executor; -import java.util.concurrent.LinkedBlockingDeque; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import io.sinistral.proteus.server.predicates.ServerPredicates; import io.undertow.io.Receiver; @@ -33,6 +29,8 @@ * @author jbauer * */ + + public class ServerRequest { protected static final Receiver.ErrorCallback ERROR_CALLBACK = new Receiver.ErrorCallback() { diff --git a/src/main/java/io/sinistral/proteus/server/tools/oas/Reader.java b/src/main/java/io/sinistral/proteus/server/tools/oas/Reader.java index 093fc9e..6f41db2 100644 --- a/src/main/java/io/sinistral/proteus/server/tools/oas/Reader.java +++ b/src/main/java/io/sinistral/proteus/server/tools/oas/Reader.java @@ -46,6 +46,7 @@ import com.fasterxml.jackson.databind.introspect.AnnotatedParameter; import com.fasterxml.jackson.databind.type.TypeFactory; +import io.sinistral.proteus.server.ServerRequest; import io.sinistral.proteus.server.ServerResponse; import io.swagger.v3.core.converter.AnnotatedType; import io.swagger.v3.core.converter.ModelConverters; @@ -96,7 +97,7 @@ public class Reader extends io.swagger.v3.jaxrs2.Reader public static final String DEFAULT_DESCRIPTION = "default response"; protected OpenAPIConfiguration config; - + private Application application; private OpenAPI openAPI; private Components components; @@ -114,6 +115,8 @@ public class Reader extends io.swagger.v3.jaxrs2.Reader public Reader() { +// Json.mapper().addMixIn(ServerRequest.class, ServerRequestMixIn.class); + this.openAPI = new OpenAPI(); paths = new Paths(); openApiTags = new LinkedHashSet<>(); @@ -124,6 +127,7 @@ public Reader() public Reader(OpenAPI openAPI) { this(); + setConfiguration(new SwaggerConfiguration().openAPI(openAPI)); } @@ -448,6 +452,8 @@ public OpenAPI read(Class cls, Optional classExternalDocumentation = AnnotationsUtils.getExternalDocumentation(apiExternalDocs); JavaType classType = TypeFactory.defaultInstance().constructType(cls); + + BeanDescription bd = Json.mapper().getSerializationConfig().introspect(classType); final List globalParameters = new ArrayList<>(); @@ -466,7 +472,13 @@ public OpenAPI read(Class cls, { continue; } - AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes()); + + Class[] parameterTypes = Arrays.stream(method.getParameterTypes()).filter( p -> !p.isAssignableFrom(ServerRequest.class) ).toArray(Class[]::new); + + + AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), parameterTypes); + + javax.ws.rs.Produces methodProduces = ReflectionUtils.getAnnotation(method, javax.ws.rs.Produces.class); javax.ws.rs.Consumes methodConsumes = ReflectionUtils.getAnnotation(method, javax.ws.rs.Consumes.class); @@ -539,7 +551,8 @@ else if (StringUtils.isBlank(httpMethod) && subResource != null) classResponses); if (operation != null) { - + //LOGGER.debug("operation is not null"); + List operationParameters = new ArrayList<>(); List formParameters = new ArrayList<>(); Annotation[][] paramAnnotations = getParameterAnnotations(method); @@ -547,12 +560,24 @@ else if (StringUtils.isBlank(httpMethod) && subResource != null) { // annotatedMethod not null only when method with 0-2 // parameters Type[] genericParameterTypes = method.getGenericParameterTypes(); + + genericParameterTypes = Arrays.stream(genericParameterTypes).filter( t -> !t.getTypeName().contains("ServerRequest")).toArray(Type[]::new); +// +// for( Type t : genericParameterTypes ) +// { +// LOGGER.warn("Generic parameter type: " + t); +// } +// +// LOGGER.warn("paramAnnotations length: " + paramAnnotations.length + " genericParameterTypes length: " + genericParameterTypes.length); + for (int i = 0; i < genericParameterTypes.length; i++) { final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); io.swagger.v3.oas.annotations.Parameter paramAnnotation = AnnotationsUtils .getAnnotation(io.swagger.v3.oas.annotations.Parameter.class, paramAnnotations[i]); + Type paramType = ParameterProcessor.getParameterType(paramAnnotation, true); + if (paramType == null) { paramType = type; @@ -564,15 +589,21 @@ else if (StringUtils.isBlank(httpMethod) && subResource != null) paramType = type; } } + +// LOGGER.warn(i + " Arrays.asList(paramAnnotations[i]): " + Arrays.asList(paramAnnotations[i])); + ResolvedParameter resolvedParameter = getParameters( paramType, Arrays.asList(paramAnnotations[i]), operation, classConsumes, methodConsumes, jsonViewAnnotation); + + for (Parameter p : resolvedParameter.parameters) { operationParameters.add(p); } if (resolvedParameter.requestBody != null) { +// LOGGER.warn("Found request body param for " + paramType); processRequestBody( resolvedParameter.requestBody, operation, @@ -585,6 +616,8 @@ else if (StringUtils.isBlank(httpMethod) && subResource != null) } else if (resolvedParameter.formParameter != null) { +// LOGGER.warn("Found request form param for " + paramType); + // collect params to use together as request // Body formParameters.add(resolvedParameter.formParameter); @@ -596,7 +629,9 @@ else if (resolvedParameter.formParameter != null) for (int i = 0; i < annotatedMethod.getParameterCount(); i++) { AnnotatedParameter param = annotatedMethod.getParameter(i); + final Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls); + io.swagger.v3.oas.annotations.Parameter paramAnnotation = AnnotationsUtils .getAnnotation(io.swagger.v3.oas.annotations.Parameter.class, paramAnnotations[i]); Type paramType = ParameterProcessor.getParameterType(paramAnnotation, true); @@ -611,6 +646,7 @@ else if (resolvedParameter.formParameter != null) paramType = type; } } + ResolvedParameter resolvedParameter = getParameters( paramType, Arrays.asList(paramAnnotations[i]), operation, classConsumes, methodConsumes, jsonViewAnnotation); @@ -766,13 +802,23 @@ else if (resolvedParameter.formParameter != null) return openAPI; } + + public boolean isOptionalType(JavaType propType) { + return Arrays.asList("com.google.common.base.Optional", "java.util.Optional") + .contains(propType.getRawClass().getCanonicalName()); + } + public static Annotation[][] getParameterAnnotations(Method method) { Annotation[][] methodAnnotations = method.getParameterAnnotations(); + + LOGGER.warn("methodAnnotations length at start: " + methodAnnotations.length); java.lang.reflect.Parameter[] params = method.getParameters(); + + List filteredParameterIndices = new ArrayList<>(); for (int i = 0; i < params.length; i++) { @@ -780,15 +826,15 @@ public static Annotation[][] getParameterAnnotations(Method method) if (!params[i].getType().isAssignableFrom(io.sinistral.proteus.server.ServerRequest.class) && !params[i].getType().getName().startsWith("io.undertow")) { - String annotationStrings = Arrays.stream(paramAnnotations).map(a -> a.annotationType().getName()).collect(Collectors.joining(" ")); + // String annotationStrings = Arrays.stream(paramAnnotations).map(a -> a.annotationType().getName()).collect(Collectors.joining(" ")); - LOGGER.debug("\nparameter: " + params[i] + " | name: " + params[i].getName() + " type: " + params[i].getType() + " -> " + annotationStrings); +// LOGGER.debug("\nparameter: " + params[i] + " | name: " + params[i].getName() + " type: " + params[i].getType() + " -> " + annotationStrings); if (paramAnnotations.length == 0) { final String parameterName = params[i].getName(); - LOGGER.debug("creating query parameter for " + parameterName); + // LOGGER.debug("creating query parameter for " + parameterName); QueryParam queryParam = new QueryParam() { @@ -809,8 +855,20 @@ public Class annotationType() methodAnnotations[i] = new Annotation[] { queryParam }; } } - + else + { + filteredParameterIndices.add(i); + } } + + ArrayList annotations = Arrays.stream(methodAnnotations).collect(Collectors.toCollection(ArrayList::new)); + + for( int index : filteredParameterIndices ) + { + annotations.remove(index); + } + + methodAnnotations = annotations.stream().toArray(Annotation[][]::new); Method overriddenmethod = ReflectionUtils.getOverriddenMethod(method); @@ -876,6 +934,20 @@ protected void processRequestBody( Parameter requestBodyParameter, Operation ope JsonView jsonViewAnnotation) { + boolean isOptional = false; + + if(type != null) + { + JavaType classType = TypeFactory.defaultInstance().constructType(type); + + if(classType != null) + { + isOptional = isOptionalType(classType); + type = classType; + } + } + + io.swagger.v3.oas.annotations.parameters.RequestBody requestBodyAnnotation = getRequestBody(Arrays.asList(paramAnnotations)); if (requestBodyAnnotation != null) { @@ -918,6 +990,7 @@ else if (StringUtils.isBlank(requestBody.get$ref()) && } } } + requestBody.setRequired(!isOptional); operation.setRequestBody(requestBody); } } @@ -952,6 +1025,7 @@ else if (StringUtils.isBlank(requestBody.get$ref()) && if (!isRequestBodyEmpty) { // requestBody.setExtensions(extensions); + requestBody.setRequired(!isOptional); operation.setRequestBody(requestBody); } } @@ -1154,7 +1228,7 @@ private Operation parseMethod( } if (apiParameters != null) { - + getParametersListFromAnnotation( apiParameters.toArray(new io.swagger.v3.oas.annotations.Parameter[apiParameters.size()]), classConsumes, @@ -1166,6 +1240,7 @@ private Operation parseMethod( // RequestBody in Method if (apiRequestBody != null && operation.getRequestBody() == null) { + OperationParser.getRequestBody(apiRequestBody, classConsumes, methodConsumes, components, jsonViewAnnotation).ifPresent( operation::setRequestBody); } @@ -1179,6 +1254,7 @@ private Operation parseMethod( // classResponses if (classResponses != null && classResponses.length > 0) { + OperationParser.getApiResponses( classResponses, classProduces, diff --git a/src/main/java/io/sinistral/proteus/server/tools/oas/ServerParameterExtension.java b/src/main/java/io/sinistral/proteus/server/tools/oas/ServerParameterExtension.java index 6ceb330..f74d5a3 100644 --- a/src/main/java/io/sinistral/proteus/server/tools/oas/ServerParameterExtension.java +++ b/src/main/java/io/sinistral/proteus/server/tools/oas/ServerParameterExtension.java @@ -74,7 +74,7 @@ public ResolvedParameter extractParameters(List annotations, boolean isRequired = true; - if(_isOptionalType(javaType)) + if(isOptionalType(javaType)) { isRequired = false; } @@ -161,7 +161,6 @@ public ResolvedParameter extractParameters(List annotations, } for (Parameter p : parameters) { - Parameter processedParameter = ParameterProcessor.applyAnnotations( p, type, @@ -172,14 +171,16 @@ public ResolvedParameter extractParameters(List annotations, jsonViewAnnotation); if (processedParameter != null) { - processedParameter.setRequired(isRequired); + extractParametersResult.parameters.add(processedParameter); } } + + return extractParametersResult; } - protected boolean _isOptionalType(JavaType propType) { + public boolean isOptionalType(JavaType propType) { return Arrays.asList("com.google.common.base.Optional", "java.util.Optional") .contains(propType.getRawClass().getCanonicalName()); } diff --git a/src/main/java/io/sinistral/proteus/services/AssetsService.java b/src/main/java/io/sinistral/proteus/services/AssetsService.java index 8b3975d..440b4f1 100644 --- a/src/main/java/io/sinistral/proteus/services/AssetsService.java +++ b/src/main/java/io/sinistral/proteus/services/AssetsService.java @@ -58,7 +58,7 @@ public RoutingHandler get() .setCacheTime(assetsCacheTime) )); - this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withProduces("*/*").withPathTemplate(assetsPath).withControllerName("Assets").withMethod(Methods.GET).build()); + this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withProduces("*/*").withPathTemplate(assetsPath).withControllerName(this.getClass().getSimpleName()).withMethod(Methods.GET).build()); return router; } diff --git a/src/main/java/io/sinistral/proteus/services/SwaggerService.java b/src/main/java/io/sinistral/proteus/services/SwaggerService.java index 77e505f..eec538c 100644 --- a/src/main/java/io/sinistral/proteus/services/SwaggerService.java +++ b/src/main/java/io/sinistral/proteus/services/SwaggerService.java @@ -485,7 +485,7 @@ public void handleRequest(HttpServerExchange exchange) throws Exception }); - this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withPathTemplate(pathTemplate).withControllerName("Swagger").withMethod(Methods.GET).withProduces(MediaType.APPLICATION_JSON).build()); + this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withPathTemplate(pathTemplate).withControllerName(this.getClass().getSimpleName()).withMethod(Methods.GET).withProduces(MediaType.APPLICATION_JSON).build()); /* * YAML path @@ -520,7 +520,7 @@ public void handleRequest(HttpServerExchange exchange) throws Exception }); - this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withPathTemplate(pathTemplate).withControllerName("Swagger").withMethod(Methods.GET).withProduces(io.sinistral.proteus.server.MediaType.TEXT_YAML.contentType()).build()); + this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withPathTemplate(pathTemplate).withControllerName(this.getClass().getSimpleName()).withMethod(Methods.GET).withProduces(io.sinistral.proteus.server.MediaType.TEXT_YAML.contentType()).build()); pathTemplate = this.basePath + "/" + this.redocPath; @@ -538,7 +538,7 @@ public void handleRequest(HttpServerExchange exchange) throws Exception }); - this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withPathTemplate(pathTemplate).withControllerName("Swagger").withMethod(Methods.GET).withProduces(MediaType.TEXT_HTML).build()); + this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withPathTemplate(pathTemplate).withControllerName(this.getClass().getSimpleName()).withMethod(Methods.GET).withProduces(MediaType.TEXT_HTML).build()); pathTemplate = this.basePath; @@ -556,7 +556,7 @@ public void handleRequest(HttpServerExchange exchange) throws Exception }); - this.registeredEndpoints.add(EndpointInfo.builder().withConsumes(MediaType.WILDCARD).withProduces(MediaType.TEXT_HTML).withPathTemplate(pathTemplate).withControllerName("Swagger").withMethod(Methods.GET).build()); + this.registeredEndpoints.add(EndpointInfo.builder().withConsumes(MediaType.WILDCARD).withProduces(MediaType.TEXT_HTML).withPathTemplate(pathTemplate).withControllerName(this.getClass().getSimpleName()).withMethod(Methods.GET).build()); try @@ -610,7 +610,7 @@ public void handleRequest(HttpServerExchange exchange) throws Exception - this.registeredEndpoints.add(EndpointInfo.builder().withConsumes(MediaType.WILDCARD).withProduces(MediaType.WILDCARD).withPathTemplate(pathTemplate).withControllerName("Swagger").withMethod(Methods.GET).build()); + this.registeredEndpoints.add(EndpointInfo.builder().withConsumes(MediaType.WILDCARD).withProduces(MediaType.WILDCARD).withPathTemplate(pathTemplate).withControllerName(this.getClass().getSimpleName()).withMethod(Methods.GET).build()); diff --git a/src/test/java/io/sinistral/proteus/test/controllers/Tests.java b/src/test/java/io/sinistral/proteus/test/controllers/Tests.java index 91959aa..a619b38 100644 --- a/src/test/java/io/sinistral/proteus/test/controllers/Tests.java +++ b/src/test/java/io/sinistral/proteus/test/controllers/Tests.java @@ -34,13 +34,13 @@ import com.google.inject.Singleton; import io.sinistral.proteus.annotations.Blocking; -import io.sinistral.proteus.annotations.Debug; import io.sinistral.proteus.server.ServerRequest; import io.sinistral.proteus.server.ServerResponse; import io.sinistral.proteus.test.models.User; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; +import io.swagger.v3.oas.annotations.Operation; import io.undertow.server.HttpServerExchange; /** @@ -194,6 +194,23 @@ public ServerResponse responseUploadFilePath(ServerRequest request, return response(ByteBuffer.wrap(Files.toByteArray(file.toFile()))).applicationOctetStream(); } + @POST + @Path("/response/file/path/optional") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Consumes(MediaType.MULTIPART_FORM_DATA) + @ApiOperation(value = "Upload optional file path endpoint", httpMethod = "POST" ) + public ServerResponse responseUploadOptionalFilePath(ServerRequest request, @FormParam("file") Optional file ) throws Exception + { + if(file.isPresent()) + { + return response(ByteBuffer.wrap(Files.toByteArray(file.get().toFile()))).applicationOctetStream(); + } + else + { + return response().noContent(); + } + } + @POST @Path("/response/json/echo") @Produces(MediaType.APPLICATION_OCTET_STREAM) @@ -205,9 +222,9 @@ public ServerResponse responseEchoJson(ServerRequest request, @FormParam(" } @POST - @Path("/response/json/innerClass") + @Path("/response/json/beanparam") @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Consumes("*/*") + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Echo json inner class endpoint", httpMethod = "POST" ) public ServerResponse responseInnerClassTest(ServerRequest request, @BeanParam User user ) throws Exception { @@ -217,6 +234,7 @@ public ServerResponse responseInnerClassTest(ServerRequest request, @BeanP @GET @Path("/generic/set") + @Produces((MediaType.APPLICATION_JSON)) @ApiOperation(value = "Generic set endpoint", httpMethod = "GET" ) public ServerResponse> genericSet( ServerRequest request, @QueryParam("ids") Set ids ) throws Exception { @@ -226,6 +244,7 @@ public ServerResponse> genericSet( ServerRequest request, @QueryParam @GET @Path("/optional/set") + @Produces((MediaType.APPLICATION_JSON)) @ApiOperation(value = "Generic optional set endpoint", httpMethod = "GET" ) public ServerResponse> genericOptionalSet( ServerRequest request, @QueryParam("ids") Optional> ids ) throws Exception { @@ -256,7 +275,8 @@ public ServerResponse testRedirect() @Blocking @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Convert ids", httpMethod = "POST" ) + @ApiOperation(value = "Convert ids" ) + @Operation(description = "Convert ids") public ServerResponse> listConversion( ServerRequest request, @BeanParam List ids ) throws Exception { @@ -269,7 +289,8 @@ public ServerResponse> listConversion( ServerRequest request, @BeanPa @Path("/response/file/bytebuffer") @Produces(MediaType.APPLICATION_OCTET_STREAM) @Consumes("*/*") - @ApiOperation(value = "Upload file path endpoint", httpMethod = "POST" ) + @ApiOperation(value = "Upload file path endpoint" ) + @Operation(description = "Upload file path endpoint") public ServerResponse responseUploadByteBuffer(ServerRequest request, @FormParam("file") ByteBuffer file ) throws Exception { @@ -280,7 +301,8 @@ public ServerResponse responseUploadByteBuffer(ServerRequest request @GET @Path("/response/debug") - @ApiOperation(value = "Debug endpoint", httpMethod = "GET" ) + @ApiOperation(value = "Debug endpoint" ) + @Operation(description = "Debug endpoint") public ServerResponse> debugEndpoint(ServerRequest request) { try @@ -298,7 +320,8 @@ public ServerResponse> debugEndpoint(ServerRequest request) @GET @Path("/response/debug/blocking") @Blocking - @ApiOperation(value = "Debug blocking endpoint", httpMethod = "GET" ) + @ApiOperation(value = "Debug blocking endpoint" ) + @Operation(description="Debug blocking endpoint") public ServerResponse> debugBlockingEndpoint(ServerRequest request) { try @@ -314,7 +337,9 @@ public ServerResponse> debugBlockingEndpoint(ServerRequest re @GET @Path("/response/future/user") - @ApiOperation(value = "Future user endpoint", httpMethod = "GET" ) + @ApiOperation(value = "Future user endpoint" ) + @Operation(description="Future user endpoint") + @Produces((MediaType.APPLICATION_JSON)) public CompletableFuture> responseFutureUser() { return CompletableFuture.completedFuture(response( new User(123L) ).applicationJson() ); @@ -323,9 +348,10 @@ public CompletableFuture> responseFutureUser() @GET @Path("/response/parameters/complex/{pathLong}") @ApiOperation(value = "Complex parameters", httpMethod = "GET") + @Produces((MediaType.APPLICATION_JSON)) public ServerResponse> complexParameters( - final ServerRequest serverRequest, - @PathParam("pathLong") final Long pathLong, + ServerRequest serverRequest, + @PathParam("pathLong") Long pathLong, @QueryParam("optionalQueryString") Optional optionalQueryString, @QueryParam("optionalQueryLong") Optional optionalQueryLong, @QueryParam("optionalQueryDate") @ApiParam(format="date") Optional optionalQueryDate, diff --git a/src/test/java/io/sinistral/proteus/test/server/TestControllerEndpoints.java b/src/test/java/io/sinistral/proteus/test/server/TestControllerEndpoints.java index 960f5d2..c648ad5 100644 --- a/src/test/java/io/sinistral/proteus/test/server/TestControllerEndpoints.java +++ b/src/test/java/io/sinistral/proteus/test/server/TestControllerEndpoints.java @@ -5,7 +5,6 @@ import static io.restassured.RestAssured.given; import static io.restassured.RestAssured.when; - import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -15,7 +14,7 @@ import java.io.File; import java.io.InputStream; import java.nio.file.Files; -import java.util.Arrays; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -76,7 +75,7 @@ public void setUp() @Test public void testSwaggerDocs() { - given().accept(ContentType.JSON).log().uri().when().get("swagger.json").then().statusCode(200).and().body("basePath", is("/v1")); + given().accept(ContentType.JSON).when().get("swagger.json").then().statusCode(200).and().body("basePath", is("/v1")); } @Test @@ -88,72 +87,72 @@ public void testOpenAPIDocs() @Test public void testDebugEndpoint() { - given().accept(ContentType.JSON).log().uri().when().get("tests/response/debug").then().statusCode(200); + given().accept(ContentType.JSON).when().get("tests/response/debug").then().statusCode(200); } @Test public void testDebugBlockingEndpoint() { - given().accept(ContentType.JSON).log().uri().when().get("tests/response/debug/blocking").then().statusCode(200); + given().accept(ContentType.JSON).when().get("tests/response/debug/blocking").then().statusCode(200); } @Test public void exchangeUserJson() { - User user = given().accept(ContentType.JSON).log().uri().when().get("tests/exchange/user/json").as(User.class); + User user = given().accept(ContentType.JSON).when().get("tests/exchange/user/json").as(User.class); assertThat(user.getId(), CoreMatchers.is(123L)); } @Test public void genericSet() { - given().accept(ContentType.JSON).log().uri().when().queryParam("ids", idSet).get("tests/generic/set").then().statusCode(200).body(containsString("1")); + given().accept(ContentType.JSON).when().queryParam("ids", idSet).get("tests/generic/set").then().statusCode(200).body(containsString("1")); } @Test public void optionalGenericSet() { - given().accept(ContentType.JSON).log().uri().when().queryParam("ids",idSet).get("tests/optional/set").then().statusCode(200).body(containsString("1")); + given().accept(ContentType.JSON).when().queryParam("ids",idSet).get("tests/optional/set").then().statusCode(200).body(containsString("1")); } @Test public void exchangeUserXml() { - User user = given().accept(ContentType.XML).log().uri().when().get("tests/exchange/user/xml").as(User.class); + User user = given().accept(ContentType.XML).when().get("tests/exchange/user/xml").as(User.class); assertThat(user.getId(), CoreMatchers.is(123L)); } @Test public void responseUserJson() { - User user = given().accept(ContentType.JSON).log().uri().when().get("tests/response/user/json").as(User.class); + User user = given().accept(ContentType.JSON).when().get("tests/response/user/json").as(User.class); assertThat(user.getId(), CoreMatchers.is(123L)); } @Test public void responseUserXml() { - User user = given().accept(ContentType.XML).log().uri().when().get("tests/response/user/xml").as(User.class); + User user = given().accept(ContentType.XML).when().get("tests/response/user/xml").as(User.class); assertThat(user.getId(), CoreMatchers.is(123L)); } @Test public void exchangePlaintext() { - given().accept(ContentType.TEXT).log().uri().when().get("tests/exchange/plaintext").then().statusCode(200).and().body(containsString("Hello, World!")); + given().accept(ContentType.TEXT).when().get("tests/exchange/plaintext").then().statusCode(200).and().body(containsString("Hello, World!")); } @Test public void exchangePlaintext2() { - given().accept(ContentType.TEXT).log().uri().when().get("tests/exchange/plaintext2").then().statusCode(200).and().body(containsString("Hello, World!")); + given().accept(ContentType.TEXT).when().get("tests/exchange/plaintext2").then().statusCode(200).and().body(containsString("Hello, World!")); } @Test public void responsePlaintext() { - given().accept(ContentType.TEXT).log().uri().when().get("tests/response/plaintext").then().statusCode(200).and().body(containsString("Hello, World!")); + given().accept(ContentType.TEXT).when().get("tests/response/plaintext").then().statusCode(200).and().body(containsString("Hello, World!")); } @Test @@ -161,17 +160,17 @@ public void responseEchoModel() { User model = new User(101L,UserType.ADMIN); - given().contentType(ContentType.JSON).accept(ContentType.JSON).body(model).log().uri().when().post("tests/response/json/echo").then().statusCode(200).and().body(containsString("101")); + given().contentType(ContentType.JSON).accept(ContentType.JSON).body(model).when().post("tests/response/json/echo").then().statusCode(200).and().body(containsString("101")); } @Test - public void responseInnerClassModel() + public void responseBeanParam() { - User.InnerUserModel model = new User.InnerUserModel(); - model.id = 101L; + User model = new User(); + model.setId(101L); - given().contentType(ContentType.JSON).accept(ContentType.JSON).body(model).log().uri().when().post("tests/response/json/innerClass").then().statusCode(200).and().body(containsString("101")); + given().contentType(ContentType.JSON).accept(ContentType.JSON).body(model).when().post("tests/response/json/beanparam").then().statusCode(200).and().body(containsString("101")); } @@ -179,50 +178,80 @@ public void responseInnerClassModel() @Test public void responseFutureUser() { - given().accept(ContentType.JSON).log().uri().when().get("tests/response/future/user").then().statusCode(200).and().body(containsString("123")); + given().accept(ContentType.JSON).when().get("tests/response/future/user").then().statusCode(200).and().body(containsString("123")); } @Test public void responseMap() { - given().accept(ContentType.JSON).log().uri().when().get("tests/response/future/map").then().statusCode(200).and().body("message", is("success")); + given().accept(ContentType.JSON).when().get("tests/response/map").then().statusCode(200).and().body("message", is("success")); + } + + + @Test + public void responseFutureMap() + { + given().accept(ContentType.JSON).when().get("tests/response/future/map").then().statusCode(200).and().body("message", is("success")); } @Test public void testRedirect() { - given().log().uri().when().get("tests/redirect").then().statusCode(200).and().header("Server", "gws"); + given().when().get("tests/redirect").then().statusCode(200).and().header("Server", "gws"); } @Test public void testRedirectFoundCode() { - given().log().uri().when().redirects().follow(false).get("tests/redirect").then().statusCode(302); + given().when().redirects().follow(false).get("tests/redirect").then().statusCode(302); } @Test public void testRedirectMovedPermanentlyCode() { - given().log().uri().when().redirects().follow(false).get("tests/redirect/permanent").then().statusCode(301); + given().when().redirects().follow(false).get("tests/redirect/permanent").then().statusCode(301); } - @SuppressWarnings("resource") - @Test + @Test public void responseUploadFilePathParameter() { try { - final InputStream is = given().log().uri().multiPart("file", file).accept(ContentType.ANY).when().post("tests/response/file/path").asInputStream(); + final InputStream is = given().multiPart("file", file).accept(ContentType.ANY).when().post("tests/response/file/path").asInputStream(); - final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - IOUtils.copy(is, byteArrayOutputStream); - IOUtils.closeQuietly(byteArrayOutputStream); - IOUtils.closeQuietly(is); + try(final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) + { + IOUtils.copy(is, byteArrayOutputStream); + + assertThat(byteArrayOutputStream.size(), equalTo(Long.valueOf(file.length()).intValue())); + } - assertThat(byteArrayOutputStream.size(), equalTo(Long.valueOf(file.length()).intValue())); + } catch (Exception e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + @Test + public void responseUploadOptionalFilePathParameter() + { + + try + { + + final InputStream is = given().multiPart("file", file).accept(ContentType.ANY).when().post("tests/response/file/path/optional").asInputStream(); + + try(final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) + { + IOUtils.copy(is, byteArrayOutputStream); + + assertThat(byteArrayOutputStream.size(), equalTo(Long.valueOf(file.length()).intValue())); + } } catch (Exception e) { @@ -235,15 +264,11 @@ public void responseUploadFilePathParameter() @Test public void responseParseListParameter() { - try { - List values = new Random().longs(10, 0L, 20L).boxed().collect(Collectors.toList()); - - - - given().contentType(ContentType.JSON).accept(ContentType.JSON).body(values).log().all().when().post("tests/response/parse/ids").then().statusCode(200); + + given().contentType(ContentType.JSON).accept(ContentType.JSON).body(values).when().post("tests/response/parse/ids").then().statusCode(200); } catch (Exception e) @@ -262,7 +287,7 @@ public void responseUploadByteBufferParameter() try { - final InputStream is = given().multiPart("file", file).log().uri().accept(ContentType.ANY).when().post("tests/response/file/bytebuffer").asInputStream(); + final InputStream is = given().multiPart("file", file).accept(ContentType.ANY).when().post("tests/response/file/bytebuffer").asInputStream(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(is, byteArrayOutputStream); @@ -290,7 +315,7 @@ public void responseComplexParameters() Map map = given() - .log().uri() + .accept(ContentType.JSON) diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml index 55c9f2a..b1c6fff 100644 --- a/src/test/resources/logback-test.xml +++ b/src/test/resources/logback-test.xml @@ -15,10 +15,10 @@ - + - +