Spring Pageable object in get request from React using Axios - java

I have an endpoint looking like this
#GetMapping("/page") Page<Event> getEventPage( #PageableDefault(page = 0, size = 20) #SortDefault(sort = "createdDateTime", direction = Sort.Direction.DESC) Pageable pageable)
How am I supposed to pass the Pageable object from my React frontend using Axios, I got this so far:
fetchEvents(pageable) {
return axios.get("http://localhost:8080/api/events/page", pageable, this.setupAxiosInterceptors());
}
Where pageable is the last fetched page. Now it just resorts to the default values.

You simply do this by adding query parameters to the url. Like http://localhost:8080/api/events/page?page=1&size=20
The axios way to do this would be something like this:
const querystring = require('querystring');
axios.get('http://localhost:8080/api/events/page', querystring.stringify({ page: 1, size: 20 }));

Related

Using Object class as wrapper for input in spring boot RestController

I am bit new to spring boot and I am trying to design a search on user history which will provide 3 attributes to search user history {userId, searchKey, SearchValue}.
The search value datatype may differ based on search.
E.g
Userid=100, SearchKey=userAddress, searchValue='10 Downing Street'
Userid=100, SearchKey=external, searchValue=true
Userid=100, SearchKey=companyId, searchValue=25
I am trying to design a rest endpoint as below. This endpoint will integrate with react front end.
#GetMapping(value = "/searchUserHistoryByKeyValue")
public ResponseEntity<Object> searchUserHistoryByKeyValue(
#RequestParam(value = "userId") int userId,
#RequestParam(value = "searchKey") String searchKey,
#RequestBody Object searchValue) {
List<org.json.simple.JSONObject> entities =
userHistoryService.searchUserHisotryByKeyValue(userId, searchKey, searchValue);
return new ResponseEntity<>(entities, HttpStatus.OK);
}
I have implemented a dynamodb search on userhistory object which takes input as generic searchValue object as search filter as below.
Dynamo DB Querying - https://www.tutorialspoint.com/dynamodb/dynamodb_querying.htm
public List<JSONObject> searchUserHistoryByKeyValue(
int userId, String searchKey, Object searchValue) throws DataAccessException {
Table table = dynamoDB.getTable(userHistoryTable.getName());
Map<String, String> expressionAttributeNames =
DEFAULT_USER_FILTERS.stream()
.collect(
Collectors.toMap(attrib -> attrib, attrib -> attrib.substring(1), (a, b) -> b));
Optional<String> projectionExpression =
createProjectionExpression(
Collections.singletonList(searchKey), expressionAttributeNames);
Optional<String> filterProjectionExpression =
buildCustomProjectionExpression(
Collections.singletonList(searchKey), expressionAttributeNames);
QuerySpec querySpec =
new QuerySpec()
.withProjectionExpression(projectionExpression.orElse(StringUtils.EMPTY))
.withKeyConditionExpression("#userId = :userId")
.withFilterExpression(
String.format(
"%s = :searchValue",
filterProjectionExpression.orElseThrow(
() -> new IllegalArgumentException("Invalid Search Attributes"))))
.withNameMap(expressionAttributeNames)
.withValueMap(Map.of(":userId", userId, ":searchValue", searchValue))
.withScanIndexForward(false);
When I am trying use swagger or postman to test this endpoint , I am not able to pass in
#RequestBody Object searchValue . it just shows as empty braces - {}
Also it shows below error as -
'TypeError: Failed to execute 'fetch' on 'Window': Request with
GET/HEAD method cannot have body. '
I am not able to make this work? Appreciate your insights on this.
It's HTTP protocol.
You cannot pass any body object with the Get method. You have to use Post or Put method for using a body in HTTP request.
#RequestBody not for single value it is intended for your custom object that is used with POST or PUT but in you case you can #RequestParam also if #RequestParam take attribute required with boolean vlue which tell your endpoint caller which params is optional if you set it False and which is required if you set it True

Pageable compenent is passed as null even we pass page,size,sort object

I have a rest controller that takes pageable as a parameter
#GetMapping(value = "/user", produces = APPLICATION_JSON_VALUE,
consumes = APPLICATION_JSON_VALUE)
public BaseResponse getUsers(
Pageable pageRequest) {
System.out.println(pageRequest);
);
}
now if i hit the url http://localhost:8080/user?page=1&size=20&sort=userId
i can see the syso getting printed as : Page request [number: 1, size 20, sort: userId: ASC]
but if i change the controller method and make pageable as required = false
#RequestParam(required= false)Pageable pageRequest
and if i hit the same url this time my syso will print null. I want to make pageable object as not required. How to achieve it
Basically my requirement is if the user triggers the url like the below
http://localhost:8080/user?page=1&size=20&sort=userId
and when i print my Pageable object it should print
Page request [number: 1, size 20, sort: userId: ASC]
but if i trigger my url like this http://localhost:8080/user
then my pageable object should be printed as null and not some default values

How to pass a pageable null from a webService?

So I have a backEnd with java and spring boot, the problem is occurring in pageable of the following code from a webservice:
#GetMapping(produces = MediaType.APPLICATION_JSON)
public Page<AreaDto> search(
#RequestParam(value = "name", required = false) String name,
#RequestParam(value = "codOrg", required = false) Long codOrg,
#RequestParam(value = "codCar", required = false) Long codCar,
Pageable pageable
) {
...
...
but if I do not pass the pageable as parameter or pass with the itens ​​of the pageable all set to null it always comes with default values, which are as follows:
.
Page request [number: 0, size 20, sort: null]
.
for example, if I call this webservice in any of the ways below, the pageable will always come mounted with default values
resources/areas?page=null&size=null&sort=null
resources/areas?page=0&size=0
resources/areas
resources/areas?name='test'
So that's it, how to call this webservice with a pageable null?
What about implementing your own PageableHandlerMethodArgumentResolverCustomizer? If no arguments are provided, just return null?

get 400K data from tables in Spring MVC within some sec

I'm using Spring MVC and I need to get more than 400k datas by my table where i also using JOIN in mysql query.
What I actually have is a Controller that returns which contains a List. I call the Controller using AJAX.
The problem with my solution is that I'm not able to get the data of List with in seconds it take more than 5 minutes to load on JSP page.
In page Jquery..
$(document).ready(function ajaxPost() {
$.ajax({
type: "GET",
data: page,
url: "allListAjax",
success: function(list) {
//here i get responce list and page which takes 5 minutes
}//success
}//ajax
}//ready
In Controller..
#RequestMapping(value="/allListAjax")
public #ResponseBody IVRRouteReportWrapper dashoardAjax(Model model, #RequestParam(required = false) Integer page) {
IVRRouteReportWrapper wrappObj= new IVRRouteReportWrapper();
List<IVRRouteReport> list = ivrRouteServiceInterface.getAllIVRRouteReport(page);
wrappObj.setIVRouteReportList(list);
wrappObj.setPage(page);
return wrappObj;
}
here, IVRRouteReportWrapper is a Domain model which contains setters and getters of List and page.
In Service Implementation...
public List<IVRRouteReport> getAllIVRRouteReport(Integer page) {
return ivrRouteDAOInterface.getAllIVRRouteReport(page);
}
In Dao Implementation...
public List<IVRRouteReport> getAllIVRRouteReport(Integer page) {
if(page==null) {
page = 0;
}else {
page = page*200;
}
String strqry= "SELECT c.caller_id_number as caller_id_number, c.destination_number as destination_number,"
+" c.created_time as created_time, vbDtmf.digit as dtmf FROM VoiceBroadcastDTMF vbDtmf "
+"LEFT JOIN cdr c ON vbDtmf.uuid=c.orig_id ORDER BY c.created_time DESC";
Query query = getSession().createSQLQuery(strqry)
.addScalar("caller_id_number", new StringType())
.addScalar("destination_number", new StringType())
.addScalar("created_time", new StringType())
.addScalar("dtmf", new StringType())
.setResultTransformer(Transformers.aliasToBean(IVRRouteReport.class))
.setFirstResult(page)
.setMaxResults(200);
List<IVRRouteReport> ivrRouteReportList =(List<IVRRouteReport>) query.getResultList();
getSession().flush();
return ivrRouteReportList;
}
Is there any way to return this List Fast on jsp page ? Thanks in advance.
Index the "created_time" column and also omit not required fields by specifying only the required fields in the query as below
String strqry= "SELECT c.caller_id_number as caller_id_number, c.destination_number as destination_number,"
+" c.created_time as created_time, vbDtmf.digit as dtmf FROM VoiceBroadcastDTMF vbDtmf "
+"LEFT JOIN (SELECT caller_id_number , destination_number , created_time FROM cdr) as c ON vbDtmf.uuid=c.orig_id ORDER BY c.created_time DESC";
Go for pagination.
Refer spring-mvc-pagination

How to get the next page on spring pagination

I have a resource in my service with pagination and I would like to know how could I process the next request to get the second page.
Here is the java resource:
#GetMapping(value = "/partner/codes")
public Page<String> getCodes(#PageableDefault(size = 5) Pageable pageable) {
final List<String> userIds = service.getIds();
int start = pageable.getOffset();
int end = (start + pageable.getPageSize()) > userIds.size() ? userIds.size() : (start + pageable.getPageSize());
return new PageImpl<String>(userIds.subList(start, end), pageable, userIds.size());
}
And the response the response with 5 results:
{
"content":[
"4a136aa6-00d4-44f0-bb48-d192fd8bc010",
"bebebaf2-b881-4733-8a65-1ecf80b5192e",
"1a0f9d07-1393-48a8-8883-37d87681e84b",
"d2580fdc-db6c-4fa3-89d4-2b52898a20bf",
"2c90e683-4ed4-45a4-b70b-614a3339670b"
],
"last":false,
"totalPages":3,
"totalElements":57,
"size":20,
"number":0,
"sort":null,
"numberOfElements":20,
"first":true
}
I'm sorry, as there was nothing explicit in the documentation, I hadn't noticed that just passing the parameters in the query string.
?page=2&size=20
And the client should create the rule using the response message.

Categories

Resources