Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mapping spring RequestPart annotation to micronaut Part annotation #525

Merged
merged 2 commits into from
Feb 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.spring.web.annotation;

import io.micronaut.http.annotation.Part;

/**
* Maps Spring RequestParam to Micronaut.
*
* @since 5.4.1
*/
public class RequestPartAnnotationMapper extends WebBindAnnotationMapper<Part> {

@Override
public String getName() {
return "org.springframework.web.bind.annotation.RequestPart";
}

@Override
Class<Part> annotationType() {
return Part.class;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
io.micronaut.spring.web.annotation.RequestParamAnnotationMapper
io.micronaut.spring.web.annotation.RequestPartAnnotationMapper
io.micronaut.spring.web.annotation.RestControllerAnnotationMapper
io.micronaut.spring.web.annotation.CookieValueAnnotationMapper
io.micronaut.spring.web.annotation.RequestHeaderAnnotationMapper
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, Server
final String view = body.toString();
final Model model = attribute.get();
final MutableHttpResponse<Object> res = (MutableHttpResponse<Object>) mutableHttpResponse;
res.body(new ModelAndView(
res.body(new ModelAndView<>(
view,
model.asMap()
));
Expand All @@ -82,10 +82,9 @@ public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, Server
if (modelMap.isPresent()) {
final String view = body.toString();
Object o = modelMap.get();
if (o instanceof Model) {
final Model model = (Model) o;
if (o instanceof Model model) {
final MutableHttpResponse<Object> res = (MutableHttpResponse<Object>) mutableHttpResponse;
res.body(new ModelAndView(
res.body(new ModelAndView<>(
view,
model
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,15 @@
*/
@Filter("/**")
public class ResponseEntityServerFilter implements HttpServerFilter {

@Override
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
final Publisher<MutableHttpResponse<?>> responsePublisher = chain.proceed(request);
return Publishers.map(responsePublisher, mutableHttpResponse -> {
final Object body = mutableHttpResponse.body();
if (body instanceof HttpEntity) {
HttpEntity entity = (HttpEntity) body;
if (entity instanceof ResponseEntity) {
mutableHttpResponse.status(((ResponseEntity) entity).getStatusCodeValue());
if (body instanceof HttpEntity<?> entity) {
if (entity instanceof ResponseEntity<?> responseEntity) {
mutableHttpResponse.status(responseEntity.getStatusCode().value());
}
final HttpHeaders headers = entity.getHeaders();
final MutableHttpHeaders micronautHeaders = mutableHttpResponse.getHeaders();
Expand All @@ -59,10 +59,9 @@ public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, Server
}
final Object b = entity.getBody();
if (b != null) {
((MutableHttpResponse<Object>) mutableHttpResponse).body(b);
mutableHttpResponse.body(b);
}
} else if (body instanceof HttpHeaders) {
HttpHeaders httpHeaders = (HttpHeaders) body;
} else if (body instanceof HttpHeaders httpHeaders) {
mutableHttpResponse.body(null);
httpHeaders.forEach((s, strings) -> {
final MutableHttpHeaders headers = mutableHttpResponse.getHeaders();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package io.micronaut.spring.web.annotation
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.http.client.multipart.MultipartBody
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification
Expand Down Expand Up @@ -65,4 +66,18 @@ class RestControllerSpec extends Specification {
then:
greeting != null
}

void "test RequestPart argument"() {

when:
def json = """{"prop1": "val1", "prop2": 12}"""
def fileContent = "this is file content"
def response = greetingClient.multipartRequest(MultipartBody.builder()
.addPart("json", json)
.addPart("myFile", "myFileName", fileContent.bytes)
.build())

then:
response == json + '#' + fileContent
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.client.annotation.Client;
import org.springframework.web.bind.annotation.*;
import io.micronaut.http.client.multipart.MultipartBody;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@Client("/")
public interface GreetingClient {
Expand All @@ -45,4 +51,7 @@ public interface GreetingClient {

@GetMapping("/greeting-status{?name}")
HttpResponse<Greeting> greetWithStatus(@Nullable String name);

@PostMapping(value = "/multipart-request", consumes = MediaType.TEXT_PLAIN_VALUE, produces = MediaType.MULTIPART_FORM_DATA_VALUE)
String multipartRequest(@RequestBody MultipartBody body);
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,42 @@
*/
package io.micronaut.spring.web.annotation;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicLong;

import io.micronaut.http.multipart.CompletedFileUpload;
import io.micronaut.validation.Validated;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.constraints.Pattern;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicLong;
import reactor.core.publisher.Flux;

import static org.junit.Assert.assertEquals;

@RestController
@Validated
public class GreetingController {

private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
private static final String TEMPLATE = "Hello, %s!";

private final AtomicLong counter = new AtomicLong();

@GetMapping("/")
public String home(Model model) {
Expand All @@ -60,29 +72,33 @@ public Flux<String> request(ServerHttpRequest request, HttpMethod method) {
}

@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") @Pattern(regexp = "\\D+") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") @Pattern(regexp = "\\D+") String name) {
return new Greeting(counter.incrementAndGet(), TEMPLATE.formatted(name));
}

@PostMapping("/greeting")
public Greeting greetingByPost(@RequestBody Greeting greeting) {
return new Greeting(counter.incrementAndGet(),
String.format(template, greeting.getContent()));
return new Greeting(counter.incrementAndGet(), TEMPLATE.formatted(greeting.getContent()));
}

@DeleteMapping("/greeting")
public ResponseEntity<?> deleteGreeting() {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
var headers = new LinkedMultiValueMap<String, String>();
headers.add("Foo", "Bar");
return new ResponseEntity<>(headers, HttpStatus.NO_CONTENT);
}


@RequestMapping("/greeting-status")
@ResponseStatus(code = HttpStatus.CREATED)
public Greeting greetingWithStatus(@RequestParam(value="name", defaultValue="World") @Pattern(regexp = "\\D+") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
public Greeting greetingWithStatus(@RequestParam(value = "name", defaultValue = "World") @Pattern(regexp = "\\D+") String name) {
return new Greeting(counter.incrementAndGet(), TEMPLATE.formatted(name));
}

@PostMapping(value = "/multipart-request", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
public String multipartRequest(@RequestPart String json,
@RequestPart("myFile") CompletedFileUpload file) throws IOException {

return json + '#' + new String(file.getInputStream().readAllBytes());
}

}
4 changes: 4 additions & 0 deletions src/main/docs/guide/springToMicronaut/springMvc.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ The following Spring MVC annotations are supported:
|link:{micronautapi}http/annotation/Body.html[@Body]
|Example: `@RequestBody`

|link:{springapi}org/springframework/web/bind/annotation/RequestPart.html[@RequestPart]
|link:{micronautapi}http/annotation/Part.html[@Part]
|Example: `@RequestPart("my-part)`

|link:{springapi}org/springframework/web/bind/annotation/RequestParam.html[@RequestParam]
|link:{micronautapi}http/annotation/QueryValue.html[@QueryValue]
|Example: `@RequestParam("myParam")`
Expand Down
Loading