Snake case in request body using JAX-RS - java

I have an API REST service, developed using JAX-RS. I need to make its request accept snake case as it currently only receives camel case.
NOTE:
I'm using the #Json_ignore property but it doesn't work
Controller
#POST
#Consumes("application/json")
public Response listarAcuerdos(ListarAcuerdosRequestType request) throws Exception {
...
return Response.ok().entity(result).build();
}
Request Bean
#XmlRootElement
public class ListarAcuerdosRequestType {
#JsonProperty("codigo_matv")
private String codigoMatv;
public String getCodigoMatv() {
return codigoMatv;
}
public void setCodigoMatv(String codigoMatv) {
this.codigoMatv = codigoMatv;
}
}

Related

I am trying to create an API using SpringBoot but I don't know how to handle json request/response

I am new to Java and Spring boot. I am creating a new API.
Using postman I am sending a request body which contains request header and request payload.
Then I have a controller which handles the request with the help of RequestPayload class. (And a service and dao file but I am sure those are ok.)
Kindly let me know what Am I missing here or what do I not know.
public class RequestPayload {
String pol_pkg_prod_code;
JSONObject checklist;
public JSONObject getCheckList() {
return checklist;
}
public void setCheckList(JSONObject checklist) {
this.checklist = checklist;
}
public String pol_pkg_prod_code() {
return pol_pkg_prod_code;
}
public void setpol_pkg_prod_code(String pol_pkg_prod_code) {
this.pol_pkg_prod_code = pol_pkg_prod_code;
}
You need a POJO class that will match the structure of your JSON payload, actually a few nested classes. Spring will automatically parse JSON into this POJO.
public class Request {
private RequestPayload reqPayload;
// Getter Setter
}
public class RequestPayload {
private Checklist checklist;
// Getter Setter
}
public class Checklist {
#JsonProperty("pol_pkg_prod_code")
private String polPkgProdCode;
}
Then add it to Controller as an argument like this:
#RequestBody Request request
This tutorial explains it well
https://www.baeldung.com/spring-request-response-body

JaxRS response general header

is there any way to set general header on response of all api paths in JaxRS ?
for example i have a api like this :
#Path("/api/v1")
public class JaxRsConfig extends Application {
}
and
#Path("/voucher")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class Voucher {
#POST
public Response add(...) {
return Response.ok().header("API_EXPIRE_DATE","2025/05/12").build();
}
#GET
public Response get(...) {
return Response.ok().header("API_EXPIRE_DATE","2025/05/12").build();
}
#GET
public Response list(...) {
return Response.ok().header("API_EXPIRE_DATE","2025/05/12").build();
}
}
and this:
#Path("/invoice")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class Invoice {
#POST
public Response add(...) {
return Response.ok().header("API_EXPIRE_DATE","2025/05/12").build();
}
#GET
public Response get(...) {
return Response.ok().header("API_EXPIRE_DATE","2025/05/12").build();
}
#GET
public Response list(...) {
return Response.ok().header("API_EXPIRE_DATE","2025/05/12").build();
}
}
I always have to put this header in the response .
JaxRs has any mechanism to set this header generally ?
Note: I use JavaEE-8 on Liberty Application Server
You can try to use a WriterInterceptor to add this header.
Some good examples explained here: https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd-edition/content/en/part1/chapter12/reader_and_writer_interceptors.html

Java spring REST controller: incomplete request body

I have a problem with my REST Controller. If I sent a request with a RequestBody (json) some attributes doesn't arrive the controller, although they was sent and defined at model.
I could find out that it look like an old version of files will be used from the local java web server. As I changed the System.out.println Value at Constructor still the old value was outputed.
public RestController_ApiKey_2_0() {
System.out.println("RestController_ApiKey_2_0 init");
}
I tried the following things bootless:
deleted java web server and did a new installation
cleaned the project and started server again
clean install of project
Does anyone have an idea?
Please provide more code, how do you declare a controller, and what params it can take. Also show a sample request.
Here is an example of a simple controller:
A model
public class CustomRequestBody {
private String fieldA;
private String fieldB;
public String getFieldA() {
return fieldA;
}
public void setFieldA(final String fieldA) {
this.fieldA = fieldA;
}
public String getFieldB() {
return fieldB;
}
public void setFieldB(final String fieldB) {
this.fieldB = fieldB;
}
}
Controller:
#Controller
public class MyController {
#RequestMapping(value = "/some-path", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.ACCEPTED)
public ResponseEntity handleSomePath(#RequestBody final CustomRequestBody body, final HttpServletRequest request) {
// Do the job.
}
And request will be:
HTTP POST http://some.server.com/some-path
{
"fieldA":"first value",
"fieldB":"second value"
}
Read more at Spring documentation here

How CXF Handles APIs If those are not annotated with the #Path Variable?

Scenario-1 : During my work I encountered below scenario, On which : getText1, getText2,getText3,getText4,getText5,getText6 are without #Path annotations,
But when I call the API (http://localhost:8080/.../testqa/ )it always returns following result :
{
"name" : "Sumit1 Arora",
"age" : 21,
"address" : "Lakshay1 Arora"
}
SimpleQAImpl
#Service("qaservice")
#Path("/testqa")
public class SimpleQAImpl {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/simpleqa")
public Person getText() {
return new Person("Sumit Arora",21,"Lakshay Arora");
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public Person getText1() {
return new Person("Sumit1 Arora",21,"Lakshay1 Arora");
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public Person getText3() {
return new Person("Sumit3 Arora",21,"Lakshay3 Arora");
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public Person getText4() {
return new Person("Sumit4 Arora",21,"Lakshay4 Arora");
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public Person getText5() {
return new Person("Sumit5 Arora",21,"Lakshay5 Arora");
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public Person getText6() {
return new Person("Sumit6 Arora",21,"Lakshay6 Arora");
}
}
May you please tell me how Apache CXF works, if #Path not given like the case above or on other scenarios as well?
Is there any reference to understand such stuff?
Scenario-2 : On this scenario, No #Path variable defined on top of API Call, how all of these API would be called from URI ?
#Service
#Path("/customer")
public class CustomerResource {
private final Logger logger = LoggerFactory.getLogger(CustomerResource.class);
#Autowired
private CustomerService customerService;
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response create(Customer customer) {
if(customerService.createCustomer(customer).isPresent()) {
return Response.ok().build();
} else
return Response.status(Response.Status.BAD_REQUEST).entity(new Error(1,"test")).build();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getAll() {
logger.debug("Received request to fetch all the customers.");
List<Customer> customers = customerService.fetchAll();
GenericEntity<List<Customer>> customerEntities = new GenericEntity<List<Customer>>(customers) {};
return Response.ok(customerEntities).build();
}
#PUT
#Consumes(MediaType.APPLICATION_JSON)
public Response update(Customer customer) {
return Response.status(Response.Status.NO_CONTENT).build();
}
}
The documentation for how CXF selects which method is executed is here: CXF resource selection overview. The docs talks about which method it prefers by looking at which has more path parameters or more a more specific path but each method in your first scenario has the same path so the first one is chosen. To differentiate between them you could use a path parameter.
The Second scenario requires you to change the HTTP method used with the URL so:
POST /customer
GET /customer
PUT /customer
would each invoke the different methods.

In CXF RS, can I get the resource method in a request filter?

I want to authorize calls made to my rest api differently depending on which method is being called. But the RequestHandler looks like this:
public interface RequestHandler {
Response handleRequest(Message m,
ClassResourceInfo resourceClass);
}
I can't figure out how to get the Method that will be called from that resourceClass. Is this possible?
The ResponseHandler seems to have a parameter that can do this named OperationResourceInfo:
public interface ResponseHandler {
Response handleResponse(Message m,
OperationResourceInfo ori,
Response response);
}
But by that time, I will have already deleted something I had no permission to delete (as an example).
How do I figure out what method will be called in a request filter? FWIW, the reason I want the Method is because I want to search for a custom built annotation I will put on each method. If there is a better way to approach this, I'm open to the idea.
For completeness, here's the documentation on the topic: http://cxf.apache.org/docs/jax-rs-filters.html
You can use Interceptors, rather than RequestHandler filters as the request handlers are deprecated and replaced in JAXRS 2.0 with ContainerRequestFilter and ContainerResponseFilter
For Example
Say I've RestService shown below
#Service
#Path("/Course")
public class KPRestService {
private final Logger LOG = LoggerFactory.getLogger(KPRestService.class);
#POST
#Path("/create")
#Consumes(MediaType.APPLICATION_JSON)
public Response create(CourseType course){
LOG.info("You have selected {}", course.getCName());
return Response.ok().build();
}
#POST
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public CourseType get(#FormParam("cDate")Date date){
final CourseType course = new CourseType();
if(date.after(new Date())){
course.setCName("E&C");
course.setCDuration(4);
}else{
course.setCName("Mech");
course.setCDuration(3);
}
return course;
}
}
I prevent calling the get method using interceptor as shown below.
#Component
public class KPFilter extends AbstractPhaseInterceptor<Message> {
private final static Logger LOG = LoggerFactory.getLogger(KPFilter.class);
public KPFilter() {
super(Phase.PRE_LOGICAL);
}
public void handleMessage(Message message) throws Fault {
final Exchange exchange = message.getExchange();
exchange.put(Message.REST_MESSAGE, Boolean.TRUE);
OperationResourceInfo resourceInfo = exchange.get(OperationResourceInfo.class);
LOG.info("Method name is {}", resourceInfo.getMethodToInvoke().getName());
if (resourceInfo != null && resourceInfo.getMethodToInvoke().getName().equals("get")) {
Response response = Response.status(Response.Status.FORBIDDEN).entity("You are not authorised")
.type(MediaType.TEXT_XML).build();
exchange.put(Response.class, response);
}
}
}

Categories

Resources