How to customized and Override Parameter Values from POJO? - spring-boot

I am working on Spring Boot v2.2.6.RELEASE and Open API Integration example. This example has capability to search using 20 different parameters. So this POJO class holds CustomSearchDto these 20 different values.
In the POJO I used orgName, but #parameter(in = ParameterIn.QUERY, name = "orgizationName", and somehow I wanted to override the variable name. I must do that. Is there any way to do it ?
#Parameter(in = ParameterIn.QUERY, name = "orgizationName", schema = #Schema(type = "string"))
#Parameter(in = ParameterIn.QUERY, name = "employeeId", schema = #Schema(type = "string"))
#Parameter(in = ParameterIn.QUERY, name = "emailId", schema = #Schema(type = "string"))
#Parameter(in=ParameterIn.QUERY, name="page", description="Results page you want to retrieve (0..N)", schema=#Schema(defaultValue = "0"))
#Parameter(in=ParameterIn.QUERY, name="size", description="Number of records per page.", schema=#Schema(defaultValue = "30"))
#GetMapping(value = "/employees/organizations")
public ResponseEntity<PagedModel<Employees>> search(CustomSearchDto requestparams,
#Parameter(hidden=true) Pageable pageRequest) {
......
........
return new ResponseEntity<>(model, HttpStatus.OK);
}
Here is my custom DTO class
public class CustomSearchDto {
#Schema(description = "", type = "string", example = " ")
private String orgName;
#Schema(description = "", type = "string", example = " ")
private String empId;
#Schema(description = "", type = "integer", example = "null")
private Integer email;
.........
..............
.............
}

You can pass directly you object CustomSearchDto with the annotation #ParameterObject.
Here is the link for the documentation:
https://springdoc.org/faq.html#how-can-i-extract-fields-from-parameter-object-

Related

Mapstruct ignore method generation

Is there a way to ignore the generation of the mapper for the 3rd method in this code sample using mapstruct?
#Mapper(unmappedSourcePolicy = ReportingPolicy.IGNORE, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface EmployeeMapper {
EmployeeMapper MAPPER = Mappers.getMapper( EmployeeMapper.class );
#Mapping(source = "id", target = "id")
#Mapping(source = "firstName", target = "firstname")
#Mapping(source = "surname", target = "surname")
#Mapping(source = "employmentses", target = "employmentDTOList")
EmployeeDTO employee2dto(Employees employees);
#Mapping(source = "id", target = "id")
#Mapping(source = "firstName", target = "firstname")
#Mapping(source = "surname", target = "surname")
#Mapping(target = "employmentDTOList", ignore = true)
EmployeeDTO domainView2dto(EmployeeView employeeView);
//to be ignored by Mapstruct
EmployeePageDTO domainPage2dto(Page<EmployeeView> employeeViewPage);
}
You can simply define a default method inside the interface as stated here:
#Mapper(unmappedSourcePolicy = ReportingPolicy.IGNORE, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface EmployeeMapper {
EmployeeMapper MAPPER = Mappers.getMapper( EmployeeMapper.class );
//.....
//to be ignored by Mapstruct
default EmployeePageDTO domainPage2dto(Page<EmployeeView> employeeViewPage) {
//.... insert body here
}
}

#valid #requestBody kotlin with entity into entity

I have a problem with valid request in kotlin because I currently have an object composed of a list of integers and another entity called emailData, when I send incomplete or in error format emaildata, the validation does not happen and let me enter the controller. my code this and my request in postman these
fun sendMessage(#Valid #RequestBody notificationData: NotificationData) {
this.notificationManager.sendNotificationByType(notificationData)
}
data class NotificationData(
#get:NotEmpty
#get:NotNull
#field:NotNull
#Size(min = 2, max = 14)
#get:JsonProperty("notification_type")
var notificationType : List<Int> = listOf(),
#Valid
//# #field:NotEmpty(message = "SRTERST enter id")
#get:JsonProperty("email_data")
var emailData : EmailData = EmailData())
data class EmailData(
#NotNull
#get:NotEmpty
#get:JsonProperty("email_receiver")
var emailReceiver : List<String> = listOf(),
#NotNull
#get:NotEmpty
#get:JsonProperty("subject")
var subject : String = "",
#get:NotEmpty
#NotNull
#get:JsonProperty("template_id")
var templateId : String = "",
#get:NotEmpty
#NotNull
#get:JsonProperty("template_params")
var templateParams : HashMap<String, String> = HashMap())
when i send
{
"notification_type":["0"],
"email_data":{
"subject":"test",
"template_id":"d-1860fd6fa461449b88c578b124a0b331"
}
}
the validation for the emailData no work.

Spring API #RequestParam Input conversion

I am creating a method for an API. In this method i have some parameters that are optional. those are filters for searching an event. when i try to run it and type the following url:
http://localhost:8181/api/events?id=gRDHzDh9TdiLDAZgrZc2wg==
i get this error message:
Failed to convert value of type 'java.lang.String' to required type 'java.util.UUID'; nested exception is java.lang.IllegalArgumentException: Invalid UUID string: gRDHzDh9TdiLDAZgrZc2wg==
So i understand that i insert a String in my url and expect a UUID in code, but how do i convert this? Below here is my code:
#RequestMapping(
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity getEvents(#RequestParam(value = "id", required = false) UUID eventId,
#RequestParam(value = "title", required = false) String title,
#RequestParam(value = "playtype", required = false) PlayType playType,
#RequestParam(value = "skilllevel", required = false) SkillLevel skillLevel,
#RequestParam(value = "sporttype", required = false) SportType sportType,
#RequestParam(value = "long", required = false) String _long,
#RequestParam(value = "lat", required = false) String lat) {
try {
List<Event> events = eventService.getEvents(eventId, title, playType, skillLevel, sportType, _long, lat);
if (events.size() == 0) {
return new ResponseEntity("No events found", HttpStatus.OK);
}
return new ResponseEntity(events, HttpStatus.OK);
} catch (Exception ex){
return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}
So here are my 2 questions:
How do i convert the string to a valid UUID input in the RequestParam?
How do i convert the string to a valid enum in the RequestParam? (because with the enums i have the same error)
EDIT
my code is now like this:
#RequestMapping(
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity getEvents(#RequestParam(value = "id", required = false) String eventId,
#RequestParam(value = "title", required = false) String title,
#RequestParam(value = "playtype", required = false) String playType,
#RequestParam(value = "skilllevel", required = false) String skillLevel,
#RequestParam(value = "sporttype", required = false) String sportType,
#RequestParam(value = "long", required = false) String _long,
#RequestParam(value = "lat", required = false) String lat) {
UUID id = null;
PlayType playType1 = null;
SkillLevel skillLevel1 = null;
SportType sportType1 = null;
try {
if (eventId != null){
id = UUID.fromString(eventId);
}
if (playType != null){
playType1 = PlayType.valueOf(playType);
}
if (skillLevel != null){
skillLevel1 = SkillLevel.valueOf(skillLevel);
}
if (sportType != null){
sportType1 = SportType.valueOf(sportType);
}
List<Event> events = eventService.getEvents(id, title, playType1, skillLevel1, sportType1, _long, lat);
if (events.size() == 0) {
return new ResponseEntity("No events found", HttpStatus.OK);
}
return new ResponseEntity(events, HttpStatus.OK);
} catch (Exception ex){
return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}
but i still get an error:
Invalid UUID string: gRDHzDh9TdiLDAZgrZc2wg==
How do I convert the string to a valid UUID input?
You need to use UUID.fromString() API, see here
How do i convert the string to a valid enum?
You need to use Enum.valueOf() API, see here

mapping list source to target

I have an object organization that contains a contact objects list.
The conacts list exists already in the database.
To test with postman, when i need to add an organization i have to add the list of contacts id
{
"name": "ce",
"contactsId": [1, 3]
}
In the contact class i have
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "contact_organization", joinColumns = #JoinColumn(name = "contacts_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "organizations_id", referencedColumnName = "id"))
private Set<Organization> organizations = new HashSet<>();
In the Organization class i have
#ManyToMany(mappedBy = "organizations")
private Set<Contact> contacts = new HashSet<>();
and in the organisationDTO class i have
private Set<Long> contactsId = new HashSet<>();
In the mapping class i did the mapping this way but it doesn't seem to be working
#Mapper(componentModel = "spring", uses = { ContactMapper.class }))
public interface OrganizationMapper extends EntityMapper<OrganizationDTO, Organization> {
#Mapping(source = "contacts", target = "contactsId")
OrganizationDTO toDto(Organization organization);
#Mapping(source = "contactsId", target = "contacts")
Organization toEntity(OrganizationDTO organizationDTO);
default Organization fromId(Long id) {
if (id == null) {
return null;
}
Organization organization = new Organization();
organization.setId(id);
return organization;
}
default Long fromContact(Contact contact) {
return contact == null ? null : contact.getId();
}
}
#Mapper(componentModel = "spring", uses = { OrganizationMapper.class })
public interface ContactMapper extends EntityMapper<ContactDTO, Contact> {
ContactDTO toDto(Contact contact);
Contact toEntity(ContactDTO contactDTO);
default Contact fromId(Long id) {
if (id == null) {
return null;
}
Contact contact = new Contact();
contact.setId(id);
return contact;
}
}
the problem here it shows me the id and the label is null, and in the data base it adds the organization but does not add the contacts
Organization organization = organizationMapper.toEntity(organizationDTO);
for(Contact item : organization.getContacts()) {
log.info("******************************************" + item.getId());
log.info("++++++++++++++++++++++++++++++++++++++++++" + item.getLabel());
}
organization = organizationRepository.save(organization);
This currently is not supported. You are trying to map a property id from the list contacts into the contactsId list.
In order to achieve what you are looking forward you need to provide a way of mapping from Contact to Long.
Your mapper can look like:
#Mapper
public interface MyMapper {
#Mapping(source = "contacts", target = "contactsId")
OrganizationDTO toDto(Organization organization);
default Long fromContact(Contact contact) {
return contact == null ? null : contact.getId();
}
}

How to hide a session parameters in Swagger with Springfox

#ApiOperation(value = "获取打卡信息", notes = "获取打卡信息")
#RequestMapping(method = RequestMethod.GET, value = "/{mPhone}/{mPassword}/{date}")
#ApiImplicitParams({
#ApiImplicitParam(name = "mPhone", value = "手机号", required = true, dataType = "String",defaultValue="13268690268",paramType="Path"),
#ApiImplicitParam(name = "mPassword", value = "密码", required = true, dataType = "String",defaultValue="111111",paramType="Path"),
#ApiImplicitParam(name = "date", value = "日期", required = true, dataType = "String",defaultValue="2017-07-04",paramType="Path"),
#ApiImplicitParam(name = "httpSession", value = "Session", required = false)})
public #ResponseBody String getSignInfo(#PathVariable String mPhone, #PathVariable String mPassword,
#PathVariable String date,
HttpSession httpSession) {
.......
}
enter image description here
I want to remove this parameter (httpSession) from the document, and I need help。
Springfox won't show these values by default. The reason why httpSession is visible in your case, is because you added it by yourself as an implicit parameter:
#ApiImplicitParam(name = "httpSession", value = "Session", required = false)
If you don't want the httpSession to pop up, remove that from your implicit parameters. Additionally, you don't even have to use #ApiImplicitParam in your case, you can use #ApiParam:
#ApiOperation(value = "获取打卡信息", notes = "获取打卡信息")
#RequestMapping(method = RequestMethod.GET, value = "/{mPhone}/{mPassword}/{date}")
public #ResponseBody String getSignInfo(
#ApiParam(value = "手机号", required = true, dataType = "String",defaultValue="13268690268")
#PathVariable String mPhone,
#ApiParam(value = "密码", required = true, dataType = "String",defaultValue="111111")
#PathVariable String mPassword,
#ApiParam(value = "日期", required = true, dataType = "String",defaultValue="2017-07-04")
#PathVariable String date,
HttpSession httpSession) {
// ...
}

Resources