How to handle Backgrid.js cell edition requests - java

I am working with Backgrid these days.
Trying to edit a row value and to persist the database object, I end up with the following HTTP error:
NetworkError: 405 Method Not Allowed - http:// localhost:8084/fsrtool/api/roles/5
My web application driven by a Java Spring backend.
The Backgrid frontend is supposed to call the following method:
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
#Override
public Role getById(#PathParam("id") Long id) {
LOG.info("get a role with its ID");
Role r = rds.getById(id);
return r;
}
I know that my service class is working, because I am able to create new 'Roles' from the Backgrid table and thanks to the following method:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Override
public Response create(final Role r) {
return Response.status(Status.CREATED).entity(rds.getOrSave(r)).build();
}
Investigating the problem, I figured out that backgrid sent the request with PUT method.
I then tried several changes into my service class in order to handle this request, but I have not been able to find the good way of setting this up.
Would you know how Backgrid cells should be edited?

So, as the application I'm working on seems to be designed, I actually was not using the good library...
The way I need my service method to be:
#PUT
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/{id}")
public Response update(final Role r, #PathParam("id") Long id) {
// do some processing... save to the db
}

Related

Is there a way to order #Path in Quarkus

I currently have a problem similar to this but in quarkus-resteasy. I have looked around and I cannot find a way to order the paths. The endpoint for getAllNotifications() is never selected, all requests go to getModel():
#Get
#Path("/cars/{brand}/{model}")
#Produces(MediaType.APPLICATION_JSON)
public Response getModel(#PathParam("brand") String brand, #PathParam("model") String model) {
...
}
#Get
#Path("/cars/notification/all")
#Produces(MediaType.APPLICATION_JSON)
public Response getAllNotifications() {
...
}
Is there a way to prioritize either endpoint 1 or 2 like it was done here

Finding a method exists in rest service or not in Java

Hi i am new to Rest Service in Java. First i want to explain my problem and then at the end i will be asking question.
I am using Mozilla rest CLIENT. My rest class looks like:
#Path("/api1")
public class RestService {
#POST
#Path("/v1")
#Consumes("application/json")
#Produces("application/json")
public String v1(String json){
//Some code here
}
#POST
#Path("/v2")
#Consumes("application/json")
#Produces("application/json")
public String v2(String json){
//Some code here
}
}
Now in this code i have two functions.
To access v1, call will be:
http://localhost:8080/project_name/package/api1/v1
To access v2 call will be:
http://localhost:8080/project_name/package/api1/v2
Question:
Now in my rest service class i want to add a patch of code which detects that whether any function which has been called either v1,v2 or v3 exists in this service or not?
Can i do this? Or anyother way to do this?
Thanks
Well, you could add a wildcard response:
#POST
#Path("/{what}")
#Consumes("application/json")
#Produces("application/json")
public String v2(String json, #PathParameter("what") String what){
return "The path "+what+" does not exist.";
}
However, since the user will never see the direct responses, you can answer with a customized 404:
#POST
#Path("/{what}")
#Consumes("application/json")
#Produces("application/json")
public Response v2(String json, #PathParameter("what") String what){
return Response.status(Status.NOT_FOUND).entity("The path "+what+" does not exist.");
}
This way you can also detect on the client side when something is incorrect.
The best approach for you is to add a fallback response. That will be called when somebody tries to access any non existing WS method.
#RequestMapping(value = {"*"})
public String getFallback()
{
return "This is a fallback response!";
}

How to get xml produced from jax-rs?

I would like to log the xml produced from this. How can I do this ?
#GET
#Path("add")
#Producse("application/xml")
public List<String>getCustomerList(....) {
}
}
UPDATE
why i need this is because , I want to have database logging with the request and response header, body etc
Not sure what you mean by log -- do you mean display on a web page?
So assuming the CustomerList is annotated and the Customer class is also annotated and each has getters and setters.
#GET
#Path("add")
#Produces(MediaType.APPLICATION_XML)
public Response returnListOfCustomers() {
CustomerList returnMe = this.getMyCustomerList(); // <-- Made this method up
return Response.ok(returnMe).build()
}
This is assuming you are trying to create a Restful service: JAX-RS.

How to perform previous process on a RESTful WebService call?

im developing a WebApplication based on RESTful WebServices. I used the NetBeans "New File Manager" to automatically generate my "Entity Classes from database" and the "RESTful Web Services fom Entity Classes" so everything is fine and I get something like:
#Stateless
#Path("usuario")
public class UsuarioFacadeREST extends AbstractFacade<Usuario> {
#PersistenceContext(unitName = "TSERMEXeCommercePU")
private EntityManager em;
public UsuarioFacadeREST() {
super(Usuario.class);
}
#POST
#Override
#Consumes({"application/xml", "application/json"})
public void create(Usuario entity) {
super.create(entity);
}
#PUT
#Override
#Consumes({"application/xml", "application/json"})
public void edit(Usuario entity) {
super.edit(entity);
}
#DELETE
#Path("{id}")
public void remove(#PathParam("id") Integer id) {
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({"application/xml", "application/json"})
public Usuario find(#PathParam("id") Integer id) {
return super.find(id);
}
#GET
#Override
#Produces({"application/xml", "application/json"})
public List<Usuario> findAll() {
return super.findAll();
}
I have REST services for every entity on my DB. So everything is going good so far.
But I have a little problem, I need every service call to check if the user is loged in and if he has the permission to call that service, for example:
Im going to have an extra service on my UsuarioFacadeREST called logIn() that receive a user, password, and if is it correct, im going to add a "logedIn:true" parametter to his HTTPSession so i can always know if he has already loged in, something like:
#GET
#Path("login/{user}/{pass}")
#Produces({"application/xml"})
public String logIn(#PathParam("user") String user, #PathParam("pass") String pass, #Context HttpServletRequest request) {
Usuario userEntity;
if( (userEntity = getUserFromDB(user, pass)) != null ) {
HttpSession session = request.getSession();
session.setAttribute("logedIn", true);
session.setAttribute("priviledges", loadPrivilegdesList(userEntity));
return "<logedIn>true</logedIn>";
} else {
return "<logedIn>false</logedIn>";
}
}
So, once he has loged in, I load his priviledges list on his session.
These privilegdes are Strings like "VIEW_CUSTOMER_LIST", "ADD_CUSTOMER", "EDIT_CUSTOMER", "DELETE_CUSTOMER", "ADD_PRODUCT", "EDIT_PRODUCT", etc, etc.
What does this means? this means that on my CustomerFacadeREST service, for every REST service(every function call), i will nedd to check the user loggedIn status and his privilegdes list. By this way i will be able to know if i can offer the user this service or i have to deny it to him.
The problem is that i think is not a good practice to edit all the autogenerated RESTful Web Services to check in every function if the HttpSession has the attribute logedIn.
So, i wish to know if is there any way to have a pre-service-call function for all the RESTful web services that check, on every service call, befor call it, the logedIn attribute of the HttpSession. I mean, I want to lock all the webServices calls and redirect them to this function so it check the things that I need to be checked and then it call the original function called by the user.
Is there any way to solve this?
Thanks so much for reading. Please tell me if I am not clear enough.

How to detect if a call to a REST server in java was from a mobile device?

I have developed a REST based server in java for Android devices and Desktop Devices and now I want to make a difference between those two entities.
I want to know when an Android device is accessing the methods(Create/Read/Update/Delete) and when Desktop Web App.
Here is a snapshot of my code:
#Path("/v2")
public class RESTfulGeneric {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/get")
public Response Get() {
ResponseBuilder builder = Response.status(Response.Status.OK);
....
return builder.build();
}
#POST
#Consumes({MediaType.APPLICATION_JSON })
#Path("/create/{Name}")
public Response Post(String Table, #PathParam("Name") String Name) {
ResponseBuilder builder = Response.status(Response.Status.OK);
..........
return builder.build();
}
}
How can I know, or what should verify in order to know that an Android device is calling those methods?
I know that there is this request.getHeader("User-Agent") that could help me, but this request is availabe only in Servlets.
Any idea?
You can grab the user-agent header from the request by adding a parameter to your request handling methods i.e.
public Response Post(String Table, #PathParam("Name") String Name, #HeaderParam("user-agent") String userAgent) {
if (userAgent.contains("Android")) {
// mobile specific logic
}
}
Here's a useful list of Android user-agents...
http://www.gtrifonov.com/2011/04/15/google-android-user-agent-strings-2/
In case of using spring mvc you can use #RequestHeader annotation

Categories