Convert from Map<Object,Object> to Map<String,TopTerminalsDTO> - java

I want to return JSON from Rest API endpoint as keys with values from DB table with data. Example:
{
"terminal 1":
{"date":"2018-10-06T00:00:00.000+0000","volume":111,"count":1},
"terminal 2":
{"date":"2018-11-06T00:00:00.000+0000","volume":122,"count":1}
}
I tried to convert the result from DB by getting the table column terminal and setting it as key. But I get error
#GetMapping("/terminals")
public ResponseEntity<Map<String, TopTerminalsDTO>> getTopTerminalsVolumes(
#RequestParam(value = "start_date", required = true) String start_date,
#RequestParam(value = "end_date", required = true) String end_date) {
LocalDateTime start_datel = LocalDateTime.now(Clock.systemUTC());
LocalDateTime end_datel = LocalDateTime.now(Clock.systemUTC());
final List<PaymentTransactionsDailyFacts> list = dashboardRepository.top_daily_transactions(start_datel, end_datel);
final Map<String, TopTerminalsDTO> map =
list.stream()
.collect(Collectors.toMap(dto -> dto.getTerminal(), dto -> dto));
return ResponseEntity.ok(map);
}
Do you know how I can solve the error Type mismatch: cannot convert from Map<Object,Object> to Map<String,TopTerminalsDTO>?

Related

Is it possible to add a description for request params in Swagger?

I have an API endpoint meant to fetch appointment information. Among the parameters this endpoint takes are "from" and "to" dates, representing the date range for appointments that it will fetch. They currently show up in my Swagger like so:
I'm wondering if I might be able to augment the Swagger with a short description to explain that the endpoint will fetch appointments that have a start time that falls within this range and that the range is inclusive. Is this possible to do?
The current declaration for this endpoint in my controller looks like this
#Operation(summary = "Get the list of appointments")
#ApiResponses(value = {
#ApiResponse(
responseCode = "200", description = "List of appointments",
content = {#Content(mediaType = "application/json", schema = #Schema(implementation = AppointmentDTO.class))}
)
})
#GetMapping("/{businessId}/appointment")
public ResponseEntity<List<AppointmentDTO>> getAppointments(#PathVariable UUID businessId,
#RequestParam(required = false) List<UUID> providerIds,
#RequestParam(required = false) List<UUID> consumerIds,
#RequestParam(required = false) List<AppointmentStatus> status,
#RequestParam(required = false, name = "from") #DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") Date fromDate,
#RequestParam(required = false, name = "to") #DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") Date toDate,
Pageable pageable) {

How to get Page as result in Querydsl query with fetch or fetchResults properly?

Hi what i trying to achieve here is, i want to submit Pageable data into QueryDsl query and get the result as Page, how can i do it properly? here is what i do until now :
here is my controller :
#PostMapping("/view-latest-stock-by-product-codes")
public ResponseEntity<RequestResponseDTO<Page<StockAkhirResponseDto>>> findStockByProductCodes(
#RequestBody StockViewByProductCodesDto request) {
Page<StockAkhirResponseDto> stockAkhir = stockService.findByBulkProduct(request);
return ResponseEntity.ok(new RequestResponseDTO<>(PESAN_TAMPIL_BERHASIL, stockAkhir));
}
in my controller i submit StockViewByProductCodesDto which is looked like this :
#Data
public class StockViewByProductCodesDto implements Serializable {
private static final long serialVersionUID = -2530161364843162467L;
#Schema(description = "Kode gudang yang ingin di tampilkan", example = "GBKTJKT1", required = true)
private String warehouseCode;
#Schema(description = "id dari sebuah branch", example = "1", required = true)
private Long branchId;
#Schema(description = "Kode Branch", example = "JKT", required = true)
private String branchCode;
#Schema(description = "Kode Product yang merupakan kode yang di ambil dari master product", example = "[\"MCM-508\",\"TL-101\"]", required = true)
private List<String> productCodes;
#Schema(description = "Size of row per page", example = "15", required = true)
#NotNull
private int size;
#Schema(description = "Page number", example = "1", required = true)
#NotNull
private int page;
#Schema(description = "Sort by", example = "id", required = false)
private String sort;
}
and here is my service :
public Page<StockAkhirResponseDto> findByBulkProduct(StockViewByProductCodesDto request) {
String warehouseCode = request.getWarehouseCode();
Long branchId = request.getBranchId();
String branchCode = request.getBranchCode();
List<String> productCodes = request.getProductCodes();
Set<String> productCodesSet = new HashSet<String>(productCodes);
Pageable pageable = PageUtils.pageableUtils(request);
Page<StockAkhirResponseDto> stockAkhir = iStockQdslRepository.findBulkStockAkhirPage(warehouseCode, branchId, branchCode, productCodesSet, pageable);
return stockAkhir;
}
as you can see, i extract pageable information with PageUtils.pageableUtils(request), here is my pageableUtils function looked like :
public static Pageable pageableUtils(RequestKeyword request) {
int page = 0;
int size = 20;
if (request.getPage() > 0) {
page = request.getPage() - 1;
}
if (request.getSize() > 0) {
size = request.getSize();
}
if (!request.getSort().isEmpty()) {
return PageRequest.of(page, size, Sort.by(request.getSort()).descending());
} else {
return PageRequest.of(page, size);
}
}
after i got the Pageable data, i submit it into my repository, which is looked like this :
public Page<StockAkhirResponseDto> findBulkStockAkhirPage(String warehouseCode, Long branchId, String branchCode,
Set<String> productCodes, Pageable pageable) {
JPQLQuery<Tuple> query = new JPAQuery<>(em);
long offset = pageable.getOffset();
long limit = pageable.getPageSize();
QStock qStock = QStock.stock;
NumberExpression<Integer> totalQty = qStock.qty.sum().intValue();
query = query.select(qStock.productId, qStock.productCode, totalQty).from(qStock)
.where(qStock.warehouseCode.eq(warehouseCode), qStock.productCode.in(productCodes),
qStock.branchCode.eq(branchCode), qStock.branchId.eq(branchId))
.groupBy(qStock.productId, qStock.productCode);
query.limit(limit);
query.offset(offset);
QueryResults<Tuple> result = query.fetchResults();
long total = result.getTotal();
List<Tuple> rows = result.getResults();
List<StockAkhirResponseDto> stockAkhirDto = rows.stream()
.map(t -> new StockAkhirResponseDto(t.get(0, Long.class), t.get(1, String.class), t.get(2, Integer.class)))
.collect(Collectors.toList());
return new PageImpl<>(stockAkhirDto, pageable, total);
}
there is no error in my editor when viewing this my repository and i able to run my project, but when i execute my repository function, i got this error :
"org.hibernate.hql.internal.ast.QuerySyntaxException: expecting CLOSE,
found ',' near line 1, column 38 [select count(distinct
stock.productId, stock.productCode, stock.warehouseId,
stock.warehouseCode, stock.branchCode, stock.branchId)\nfrom
com.bit.microservices.b2b.warehouse.entity.Stock stock\nwhere
stock.warehouseCode = ?1 and stock.productCode in ?2 and
stock.branchCode = ?3 and stock.branchId = ?4]; nested exception is
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: expecting CLOSE,
found ',' near line 1, column 38 [select count(distinct
stock.productId, stock.productCode, stock.warehouseId,
stock.warehouseCode, stock.branchCode, stock.branchId)\nfrom
com.bit.microservices.b2b.warehouse.entity.Stock stock\nwhere
stock.warehouseCode = ?1 and stock.productCode in ?2 and
stock.branchCode = ?3 and stock.branchId = ?4]"
the problem is here, on this line :
QueryResults<Tuple> result = query.fetchResults();
when i execute that line, it give me that error, i try to get the fetchResult, because i want to get the .getTotal() for the total.
but if i execute the query with .fetch(), it worked fine, like this :
List<StockAkhirResponseDto> stockAkhirDto = query.fetch()
i got my sql result execute correctly, what did i missed here? how do i get Page result correctly?
Your problem could be related with an open QueryDSL issue. The documented issue has to do with the use of fetchCount but I think very likely could be also your case.
Consider the following comment in the mentioned issue:
fetchCount() uses a COUNT function, which is an aggregate function. Your query already has aggregate functions. You cant aggregate aggregate functions, unless a subquery is used (which is not available in JPA). Therefore this use case cannot be supported.
The issue also provides a temporary solution.
Basically, the idea is be able to perform the COUNT by creating a statement over the initial select. AFAIK it is not possible with QueryDsl and this is why in the indicated workarounds they access the underline mechanisms provided by Hibernate.
Perhaps, another thing that you can try to avoid the limitation is to create a database view for your query, the corresponding QueryDsl objects over it, and use these objects to perform the actual computation. I am aware that it is not an ideal solution, but it will bypass this current QueryDsl limitation.

Java REST API Complex Query

I have a table like this :
Now I want to create a a single REST API endpoint that returns filtered set of data:
It should correctly filter any combination of API parameters.
All parameters are optional
Look at this example : GET /api?type=s&max_price=1000&min_price=200&address=Berlin
I want to be able to filter based each parameter or combination of 2 or parameters.
How should I write my #RequestParam? This is a complex query. what is the strategy for this?
Try simple GET request like:
#GetMapping(value = "/api")
public ReturnDto test(
#RequestParam(required = false, value = "type", defaultValue = "0") String type,
#RequestParam(required = false, value = "max_price", defaultValue = "10000") int maxPrice,
#RequestParam(required = false, value = "min_price", defaultValue = "0 ") int minPrice,
#RequestParam(required = false, value = "address", defaultValue = "") int address
) {
}
If you don't need the default value, you can remove the defaultValue keyword, but then you need to change int to Integer, to allow null values.

MissingServelException SpringBoot

I gets an error in Spring Boot , It say that I don't send paramSelect but it is false, I send paramSelect.
I send
public filterResult(paramSelect: string, filterDateStart: string, filterDateEnd: string): Observable<any> {
filterDateStart = filterDateStart.replace(/\//g, '-');
filterDateEnd = filterDateEnd.replace(/\//g, '-');
const url = 'http://localhost:8080/filterResult/' + paramSelect + '/' + filterDateStart + '/' + filterDateEnd;
return this.http.get<any>(url);
Html ERROR->
zone.js:2969 GET http://localhost:8080/filterResult/EDU/04-07-2018/05-07-2018 400 ()
In my SpringBoot ->
#RequestMapping(method = RequestMethod.GET, value = "/filterResult/{paramSelect}/{dateStart}/{dateEnd}", produces = MediaType.APPLICATION_JSON_VALUE)
public List filterResult(#RequestParam("paramSelect") String paramSelect , #RequestParam("dateStart") String dateStart , #RequestParam("dateEnd") String dateEnd) {
System.out.println("llego");
List<Parameter> list = pgService.filterResult(paramSelect, dateStart, dateEnd);
return list;
}
I get an error:
Resolved exception caused by Handler execution: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'paramSelect' is not present
You should change to use #PathVariable instead of #RequestParam for path variables:
public List filterResult(#PathVariable("paramSelect") String paramSelect , #PathVariable("dateStart") String dateStart , #PathVariable("dateEnd") String dateEnd) {

Spring MVC - passing an Empty Date as param

I'm trying to realize a filter on one of my controllers.
This is the controller
#RequestMapping(value = "", method = RequestMethod.GET)
public String listSpots(ModelMap model, #RequestParam (value= "page", required = false) Integer page,
#RequestParam (value="numeroPosto", required = false) Integer numeroPosto,
#RequestParam(value="nomePosto", required = false) String nomePosto,
#RequestParam(value="occupied", required = false) Integer occupied,
#RequestParam(value="idPark", required = false) Integer idPark,
#RequestParam(value="idPiano", required = false) Integer idPiano,
#RequestParam(value="dateTime", required = false) Date dateTime) {
if (page == null) {
currentPage = 1;
} else {
currentPage = page;
}
int offset = (currentPage - 1) * elementsPerPage;
//creo la mappa dei criteri
Map<String, Object> criteri = new HashMap<String, Object>();
criteri.put("numeroPosto", numeroPosto);
criteri.put("nomePosto", nomePosto);
criteri.put("occupied", occupied);
Park park = null;
Piano piano = null;
if(idPark!=null){
park = parkService.findById(idPark);
}
if(idPiano!=null){
piano = pianoService.findById(idPiano);
}
criteri.put("park", park);
criteri.put("piano", piano);
criteri.put("dateTime", dateTime);
int numOfRows = postoService.showSpotsCount(criteri);
List<Posto> posti = postoService.showSpots(offset, criteri);
List<Posto> posto = new ArrayList<Posto>(posti.size());
for (Posto javaBean : posti){
Date date = new Date();
Date start = new Timestamp(date.getTime());
Date end = javaBean.getDateTime();
DateTime st = new DateTime(start);
DateTime en = new DateTime(end);
Long hours = postoService.getHours(st, en);
Long minutes = postoService.getMinutes(st, en);
javaBean.setHours(hours);
javaBean.setMinutes(minutes);
posto.add(javaBean);
}
int pages = 1+(numOfRows / elementsPerPage);
String pageTitle = messageSource.getMessage("spot.list", null, locale);
model.addAttribute("pageTitle", pageTitle);
model.addAttribute("cssActiveSpots", cssActiveSpots);
model.addAttribute("posto", posto);
model.addAttribute("currentPage", currentPage);
model.addAttribute("pages", pages);
model.addAttribute("numOfRows", numOfRows);
return path + "/posti";
}
I'm putting the params into a map, and then, at DAO level, this params will create the Restrictions to the query. I'm having a problem when leaving the dateTime field blank
I'm taking the query string from a simple form. Every other filed in the form works, and it also works if I put a correct date. When I leave it blank I get:
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [#org.springframework.web.bind.annotation.RequestParam java.util.Date] for value ''; nested exception is java.lang.IllegalArgumentException
I can I solve this?
Just add this to your controller and it should work.
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// change the format according to your need.
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

Categories