Postman Request to GET query with Multiple List<String> Parameters - spring

I am trying to test a Multi Module Spring WebMVC API endpoint using Postman. This is Spring-MVC web app & using other frameworks too.
I want to know how to make a request to this URL.
My Controller File looks like this.
#Controller
#RequestMapping(value = "/xyz")
public class XyzWebController {
#CrossOrigin(origins = "*")
#RequestMapping(value = "", method = RequestMethod.GET)
#ResponseBody
public List<XyzChild> getProperties(#RequestParam XyzQueryDTO query) {
return childService.getAll(query);
}
...
}
XyzQueryDTO.java looks like this.
public class XyzQueryDTO {
List<String> properties;
List<String> applications;
public XyzQueryDTO() {
}
public XyzQueryDTO(List<String> properties,
List<String> applications) {
super();
this.properties = properties;
this.applications = applications;
}
...
}
Please assist me with the URL with which i can test this API.
Thanks in Advance.

It's more simple and correct to use RequestMethod.POST instead of RequestMethod.GET and #RequestBody instead of #RequestParam
#RequestMapping(value = "", method = RequestMethod.POST)
#ResponseBody
public List<XyzChild> getProperties(#RequestBody XyzQueryDTO query) {
return childService.getAll(query);
}
And you can use #RestController instead of #Controller and remove #ResponseBody
For data type conversion use jackson librairy.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
In Postman you can fill your XyzQueryDTO in the BODY as json

Related

Custom Schema for Spring Boot 2 OpenAPI 3 Documentation

I have a requirement to integrate OpenAPI 3 documentation for my Spring Boot 2 project. We did not used modals/DTOs on controllers.
Here is the sample controller:
#RestController
#RequestMapping(value = "/pet")
public class PetController {
#RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<Map<String, Object>> savePet(
#RequestBody Map<String, Object> petObj, HttpServletRequest request)
throws Exception {
String petResponse = petDAO.savePet(petObj, request, true);
return new ResponseEntity<Map<String, Object>>(petResponse, HttpStatus.OK);
}
}
Request body:
{
"name":"Test",
"category":"school"
}
My response:
{
"petId":"1",
"petName":"Test",
"petCategory":"school",
"petStaus":"active"
}
I am not able to find a way to add the OpenAPI doc for my custom Map object. I want to add key, description, type, example(s) for each property in my Map manually.
Can anyone suggest how to do this?
This is the default behaviour of the springdoc-openapi library in order to ignore other injectable parameters supported by Spring MVC.
https://docs.spring.io/spring/docs/5.1.x/spring-framework-reference/web.html#mvc-ann-arguments
If you want to change this behaviour, you can just exlcude it as follow:
SpringDocUtils.getConfig().removeRequestWrapperToIgnore(Map.class);

How to unit test a multipart POST request with Spring MVC Test?

I am trying to create unit test for REST APi but having big trouble with the uploading excel method.
Here is the method on the controller side
#RestController()
#RequestMapping(path = "/upload")
#CrossOrigin(origins = "http://localhost:4200")
public class FileController {
#Autowired
FileService fileService;
#PostMapping(value = "/{managerId}/project/{projectId}")
public List<Task> importExcelFile(#RequestParam("file") MultipartFile files, #PathVariable int managerId,
#PathVariable int projectId) throws IOException, ParseException {
return fileService.getTasksFromExcel(files, managerId, projectId);
}
Whatever I try I get a lot of errors and evidently I don't really understand what I am supposed to do.
The main error I get is
current request is not a multipart request
You can do the following.
I just simplified your example a tiny bit.
So, here's the controller that returns the file size of the file it receives.
#RestController
#RequestMapping(path = "/upload")
public class FileController {
#PostMapping(value = "/file")
public ResponseEntity<Object> importExcelFile(#RequestParam("file") MultipartFile files) {
return ResponseEntity.ok(files.getSize());
}
}
and this one is the test of it. There is a class called MockMvc that Spring provides to easily unit test your controllers and controller advices. There is a method called multipart that you can use to simulate file upload cases.
class FileControllerTest {
private final MockMvc mockMvc = MockMvcBuilders
.standaloneSetup(new FileController())
.build();
#Test
#SneakyThrows
void importExcelFile() {
final byte[] bytes = Files.readAllBytes(Paths.get("TEST_FILE_URL_HERE"));
mockMvc.perform(multipart("/upload/file")
.file("file", bytes))
.andExpect(status().isOk())
.andExpect(content().string("2037")); // size of the test input file
}
}
Generally Multipart uploads can be tested via MockMultipartFile:
https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/file-upload-test.html

How to call Spring Boot RESt api using Spring MVC?

I have created REST api using Spring Boot.
So, that is the fragment of it:
#RestController
#RequestMapping("/api/employee")
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#GetMapping(value = "/all", produces = "application/json")
public ResponseEntity<List<Employee>> getAllEmployees() {
return ResponseEntity.ok(employeeService.findall());
}
Now, I would like to create more like MVC application part - simple view that shows all Employees using thymeleaf. (Just simple UI to use this app more convinient than sending curl requests)
#Controller
public class MainPageController {
#GetMapping("/employees")
public String showEmployees() {
// i don't know what to do here
return "employeesPage";
}
What is the appropriate way to do so? Is there a more simple way to do it?
Looking forward for your answers!
So you do exactly the same you did on your EmployeeController but instead of a JSON, you return a view.
Get your employes through EmployeeService and put them on a collection
Create your employee view under /templates folder (many tutorials of how to do it)
return this view with your collection of employees
Example:
#GetMapping(value = "employees")
public ModelAndView showEmployees() {
ModelAndView mav = new ModelAndView("employeesPage");
mav.addObject("employees", employeeService.findall());
return mav;
}
Check here for more detailed info:
https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html

How can I add textbox/textfield in my swagger page built in Spring boot?

I am trying to auto-generate the swagger page for a RestAPI in Spring Boot using annotations.
Code of Controller:
#RestController
#Api(value="UserManagementAPI", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserManagementController {
#RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
#ApiOperation(value="add a pro",consumes="application/json")
#RequestMapping(value = "/getUser", method = RequestMethod.GET, produces="application/json")
public static List<UserDetails> getUser(#PathVariable(name="id") String id) throws UserException
{
return UserHelper.getUserByEmail(id);
}
Application.java
#SpringBootApplication
#EnableSwagger2
#Configuration
#ComponentScan({ "userManagement"})
#EnableAutoConfiguration
public class Application {
#Bean
public Docket simpleDiffServiceApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("userManagement").apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.any())
// .paths(PathSelectors.any())
// Will also include the basic error controllers by default
.paths(Predicates.not(PathSelectors.regex("/error")))
// Exclude basic error controllers
.build().pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Business Location Service")
.description("Spring Boot REST APIs for Business Location Service")
.contact(new Contact("EntSol-IoT (Niche Technology Delivery Group)", "http://somewebsite.com",
"some#mail.com"))
.version("1.0").build();
}
In the swagger page, I can see all my APIs. But there are more. It is showing all possible method type (e.g POST, GET, PUT etc.) though in Controller I only wrote GET method.
Another issue is that there is no Textbox in the swagger page under the API where I can search for the id. May be I am missing something. I have been trying to resolve it for past two days. But couldn't help myself. Thanks in advance.
I got the problem. Your getUser method is declared as static. Please remove static, for it to work.
public List<UserDetails> getUser(#PathVariable(name="id") String id) throws UserException { }

Can not get param from json request when using spring aop

I am using spring AOP to check permission
#Component
#Aspect
public class PermissionManager {
#Around(value = "#annotation(requiredPermission) && args(id,..)", argNames = "id,requiredPermission")
public Object checkCanViewFile(ProceedingJoinPoint pjp, String id, RequiredPermission permission) throws Throwable {
...
}
}
Controller
#RequiredPermission(RequiredPermission.OperationType.editProject)
#RequestMapping("/searchFile")
public #ResponseBody
WebFile search(String id, String word) throws TokenExpiredException, FetchException {
...
}
It works on spring mvc test but can not working on real environment. the value of 'id' is null, I doubt spring AOP get this method before jackson objectmapper, is it right? How can fix it?

Resources