I want to write following GET method without a QueryParam
Ideally it should return all the records.
#GET
#Produces( { MediaType.APPLICATION_JSON } )
Response getAircraft( #Context SecurityContext aSc, #QueryParam( ID_PARAM ) String aAircraftId );
Any Idea how to achieve that?
You just need to remove the QueryParam and the variable so it looks like this:
#GET
#Produces( { MediaType.APPLICATION_JSON } )
Response getAircraft( #Context SecurityContext aSc) {
//return something
}
The Jersey Documentation is pretty good so you can find most of the stuff you need there: https://jersey.github.io/documentation/latest/jaxrs-resources.html
Related
I'm trying to fetch value from db using JPA repository method
product findByIdNumberOrCifNumber(String idNumber , String cifNumber);
service class logic:-
public ResponseModel FindByCivIDOrCifNumber(String idNumber,String cifNumber) {
ResponseModel responseModel = new ResponseModel();
Optional<product> civId = Optional.ofNullable(productRepos.findByIdNumber(idNumber));
if (civId.isPresent()) {
responseModel.setResponse(productRepos.findByIdNumberOrCifNumber(idNumber,cifNumber));
} else {
errorModel errorModel1 = new errorModel();
enter image description here errorModel1.setErrorCode(productConstant.INVALID_REQUEST);
errorModel1.setErrorDescription("Requested Civil Id or CifNUmber is not present");
responseModel.setErrorModel(errorModel1);
}
return responseModel;
}
controller class:-
#GetMapping("/getByCifNoOrGetByIdNo")
public ResponseModel getProductByCifNoOrGetByIdNo(#RequestParam String idNumber,#RequestParam String cifNumber ) {
return productService.FindByCivIDOrCifNumber(idNumber,cifNumber);
}
post man:-
kindly help me out how to make it work:)
If you are looking for an answer to pass two or more path variables and test it with postman, you can try this.
#GetMapping("/api/mapping-name/{variable1}/{variable2}")
Here you will be getting two path variables which you can access by the syntax
#PathVariable("variable1") datatype variableName
Now in postman request url you can simply give the respective url, lets say:
https://localhost8080/api/mapping-name/:variable1/:variable2
which automaticaly will give you a key value section in the path variables section in the params with prepopulated key names as per the name you have given. In this case variable1 & variable2.
Give the respective value and it should work.
I've set up a route that when I get a name in my post body I will search the DB and return an ID value.
What I want to do is once there is no ID present in the DB return a 204 status code.
But should that be handled in the service or in my controller?
and
How do I return my specific status code?
#ResponseStatus(HttpStatus.OK)
#PostMapping("/ID_values/")
fun getID(
#RequestBody
name: String
): ResponseEntity<String> = ResponseEntity.ok(IDLookupService.lookupIDValue(name))
}
#Service
class EmailLookupService(
private val IDRepo: IDRepo
) : Logging {
fun lookupIDValue(name: String): String {
val IDLookupResult = IDRepo.findById(name)
return if (IDLookupResult.isPresent) {
IDLookupResult.get().ID.toString()
} else {
// return status code 204
}
}
}
First, you should omit the #ResponseStatus(HttpStatus.OK) annotation if you do not wish to always return a status code of 200. Using that annotation, it would suffice to only specify the response body as return value (i.e specify return type String and then return only result in your example), and Spring would automatically wrap that into a response entity with HTTP-status OK.
Second, you need some way to tell the caller of IDLookupService.lookupIDValue (which should probably be called on an instance of IDLookupService and not the class itself) that there was nothing found. This could be done for instance by changing the return type to String? and return null if nothing was found.
Then you can change getID to return
val result = idLookupService.lookupIDValue(name)
return if(result != null) ResponseEntity.ok(result)
else ResponseEntity("not found", HttpStatus.NO_CONTENT)
If you wish to return something different than a String in the case there was nothing found (like an error object with detailed information; in the example here it is simply the text "not found"), you can change the response type of getID to ResponseEntity<*>.
I made controller method.
I want the method to receive variable defined by own original Data type.
like Below,
data class UserId(
val value: UUID
)
#GetMapping("user/{userId}")
fun getUser(
#PathVariable userId: UserId
) {
userService.getUser(userId)
}
Of course, I know how to receive variable of String.
#GetMapping("user/{userId}")
fun getUser(
#PathVariable userId: String
) {
// I think this code is redundancy.
val id = UserId.fromString(userId)
userService.getUser(userId)
}
Can I receive variable defined own original Data Type?
Do you know any idea?
The main question is, how do you see this working? Would you receive the data class as a serializable JSON object? If so, shouldn't that be inputted as the request body?
If there's another way you envision this working, you can always manually serialize the object later, something like:
Controller:
#GetMapping("user/{userId}")
fun getUser(
#PathVariable userIdSerialized: String
) {
userService.getUser(userIdSerialized)
}
Service:
fun getUser(userIdSerialized: String) {
// Using Jackson
val deserialized: UserId = mapper.readValueFromString(userIdSerialized, UserId::class.java)
}
But again, this should really be a request body.
I am able to consume an API who returns a json object. What I am trying to do is to get a list of objects instead. Below is my code for the same:
ResponseEntity<List<Entity>> responseEntity = restTemplate.exchange(dataUrl, HttpMethod.GET, entity,new ParameterizedTypeReference<List<Entity>>() {});
where Entity of an object of which I am expecting a list to be populated with data from json. But when I print it, all fields from Entity has null value set. What am I missing?
Thanks
Sach
Can you try with this
ResponseEntity<List<Entity>> responseEntity = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, Entity.class);
p.s. sorry don't have reputation for comment :(
Why don't use restTemplate.getForEntity?
ResponseEntity<Entity[]> response = restTemplate.getForEntity(dataUrl, Entity[].class)
Entity[] entities = response.getBody();
The above case returns an object of type Entity[], which is an array.
If you want to use the List interface, you will need to create a wrapper class.
The wrapper:
public class EntityList {
private List<Entity> entities;
public EntityList() {
entities= new ArrayList<>();
}
// standard constructor and getter/setter
}
The RestTemplate call:
Here you will use restTemplate.getForObject
EntityList response = restTemplate.getForObject(dataUrl, EntityList.class);
List<Entity> entities = response.getEntities();
Even a simpler alternative is to use List.class as the return type of getForObject.
List<Entity> response= rest.getForObject(dataUrl, List.class);
It is hard to give a correct answer due to a missing json example. Could you please provide a sample of the json that will be returned.
RESOLVED
Below is the code change I did which was returning correct list of Entity objects.
ResponseEntity<Entity[]> responseEntity = restTemplate.exchange(dataUrl, HttpMethod.GET, entity, Entity[].class);
Even after making this change didnt really solved my issue. I also had to add
#JsonProperty("fieldName") on each field in Entity class which had to match Json properties.
In controller and gsp there are avaliable two variables:
params - tahat contains map of all params (both GET from Query String and POST from forms)
request - the HttpServletRequest object
How can I get POST only params or GET (query string) only params? I need both types of params but in different maps.
I know, that HttpServletRequest object contains information about Query String, but I'm looking for solution without implementing parser of query string.
I have solved this problem by parsing Query String with org.codehaus.groovy.grails.web.util.WebUtils and then I put these data into HttpServletRequest attribute.
Now I can use request.getAttribute('paramsGet') or request.getAttribute('paramsPost').
The Grails filters was very helpfull, so:
package com.selly.filters
import org.codehaus.groovy.grails.web.util.WebUtils
class ParamsFilters {
List globalParams = [
"controller",
"action",
"format"
]
def filters = {
all(controller:'*', action:'*') {
before = {
Map paramsRequest = params.findAll {
return !globalParams.contains(it.key)
}
Map paramsGet = WebUtils.fromQueryString(request.getQueryString() ?: "")
Map paramsPost = paramsRequest.minus(paramsGet)
request.setAttribute('paramsGet', paramsGet)
request.setAttribute('paramsPost', paramsPost)
//println request.getAttribute('paramsGet')
//println request.getAttribute('paramsPost')
}
after = { Map model ->
}
afterView = { Exception e ->
}
}
}
}
Even with Grails, you're working with Servlet which mix up POST and GET. And I don't remember seeing something (except for reparsing the Query String) which would help you.