RESTEASY How to get #PathParam to match a UUID? - java

I'm using RESTEasy and Jboss eap 6.1.
I have the following resource:
#Path("/sessions")
public class Sessions {
#DELETE
#Path("/{sessionId}/")
public Response logout(#PathParam("sessionId") String sessionId)
{
//sessions.remove(sessionId);
return Response.ok().build();
}
}
sessionId is a generated UUID which has the form like 9b3db022-84de-4ba2-8194-5ff7542bf86b
I made the following call from the client:
$.ajax({
url: "/sessions/" + javaRest.cookie.get("sessionId") + "/",
type: "DELETE",
success : //do something,
error : //do something;
)}
javaRest.cookie.get(cookieName) is a function to find the value of the given cookieName.
But I got the following response error header:
HTTP/1.1 403 Forbidden,
Server: Apache-Coyote/1.1,
Content-Type: text/html;charset=utf-8,
Content-Length: 1072,
Date: Mon, 01 Jul 2013 17:22:48 GMT
Then I made another #GET with the same setup as the #DELETE resource. However, this time the response header is 404 Not Found instead of 403.
I'm doubting it has something to do with the format of the UUID (which has various "-" in between). If it is, how could I fix this?

You can try encode your param in js with encodeURIComponent(param);

I found the answer to my problem. This is a small but very vital mistake on my part.
I wrote on the question that I used:
$.ajax({
url: "sessions/" + javaRest.cookie.get("sessionId") + "/",
type: "DELETE",
success : //do something,
error : //do something;
)}
But I myself did not type in exactly what I typed here.
Instead of using sessions/ , I used /sessions/ in my client code. Ajax resolves /sessions/ differently than sessions/ in a way that break the application.
When the application is deployed on JBoss server, its URL is something like http://localhost:8080/AppName/
with sessions/, ajax resolve the URL to http://localhost:8080/AppName/sessions/.
However, with /sessions/, the URL is resolved to http://localhost:8080/sessions/ and break the application.
I guess I made a fool out of myself here. But I want to thank Wilker Iceri for your fast response.
The decision to keep or to delete this question is entirely up to the staff.

Related

Adding extra server call on Springboot application causing issue with CORS

For context, I have been working on a springboot application with a ReactJS frontend. The ReactJS frontend connects to the springboot application, and the application makes calls to another server to get the requested data to display on the front end. I had gotten to a point where I was able to make a post request with a JSON payload, get the requested data in the form of another JSON payload, and display it to the frontend with no issues.
I had to implement a change, and add one more variable to the object that was being returned to the front end. And now the browser is telling me that:
Access to fetch at [url] been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
All that is different is the addition of the data to the object being returned, and the fact I am making another call to the server where the data is stored.
Here is the Response header when I dont make the additional call, and I get back the JSON payload
HTTP/1.1 200
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: *
Set-Cookie: [I erased the cookie after pasting]
Content-Type: text/plain;charset=ISO-8859-1
Content-Length: 83363
Date: Thu, 09 Jul 2020 18:05:40 GMT
Keep-Alive: timeout=60
Here is the Response Header when I make the additional call
HTTP/1.1 500
Connection: close
Date: Thu, 09 Jul 2020 18:13:24 GMT
Ive debugged the backend, and no errors are thrown on the server side, and nothing happens while processing the data. I have all of a sudden just started getting the issue with CORS.
The following is my post request that has been working so far
fetch(url, {
headers: {
'Content-Type': 'text/plain',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
},
method: 'post',
body: JSON.stringify(jsonData)
})
Im sure I have enabled everything I had to do on the Springboot side for CORS considering It works all the time except for when trying to get the extra data. If there is something I am missing I would like to know, and if this issue can be clarified by reading documentation on springboot and cors please point me in that direction.
Note:
I have also tried adding
#Configuration
#EnableWebMvc
public class SpringBootConfiguration implements WebMvcConfigurer{
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
to my application, but that does not seem to work either. This is all still fairly new to me, so I am unsure what is going wrong.
Thank you.
The header was too large now with the added data it seems. So all I had to do was increase the max-http-header-size in my application.properties. I can now get the full JSON payload with zero issues. I was too focused on the error on the frontend side that I neglected to go deep enough into the backend to see what was happening.
I added in my application.properties
server.max-http-header-size = 48000
I didnt actually set it to 48000, its much lower than that, I found the answer here
How to set max-http-header-size in spring boot 2.x application
I had issues with CORS andthe snippet you gave was something I had tried but it ended up breaking some other endpoints for unknown reasons. You can add #CrossOrigin(origins = "URL", allowedHeaders = "*") to your controllers.
Such as
#Controller
#CrossOrigin(origins = "localhost", allowedHeaders = "*")
public class Controller

HttpClientErrorException 406 null is thrown in rest template spring mvc [duplicate]

In my Ruby on Rails application I tried to upload an image through the POSTMAN REST client in Base64 format. When I POST the image I am getting a 406 Not Acceptable Response. When I checked my database, the image was there and was successfully saved.
What is the reason for this error, is there anything I need to specify in my header?
My request:
URL --- http://localhost:3000/exercises.json
Header:
Content-Type - application/json
Raw data:
{
"exercise": {
"subbodypart_ids": [
"1",
"2"
],
"name": "Exercise14"
},
"image_file_name": "Pressurebar Above.jpg",
"image":"******base64 Format*******"
}
Your operation did not fail.
Your backend service is saying that the response type it is returning is not provided in the Accept HTTP header in your Client request.
Ref: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Find out the response (content type) returned by Service.
Provide this (content type) in your request Accept header.
http://en.wikipedia.org/wiki/HTTP_status_code -> 406
406 Not Acceptable
The resource identified by the request is only capable of generating response entities which have content characteristics not
acceptable according to the accept headers sent in the request.
406 happens when the server cannot respond with the accept-header specified in the request.
In your case it seems application/json for the response may not be acceptable to the server.
You mentioned you're using Ruby on Rails as a backend. You didn't post the code for the relevant method, but my guess is that it looks something like this:
def create
post = Post.create params[:post]
respond_to do |format|
format.json { render :json => post }
end
end
Change it to:
def create
post = Post.create params[:post])
render :json => post
end
And it will solve your problem. It worked for me :)
"Sometimes" this can mean that the server had an internal error, and wanted to respond with an error message (ex: 500 with JSON payload) but since the request headers didn't say it accepted JSON, it returns a 406 instead. Go figure. (in this case: spring boot webapp).
In which case, your operation did fail. But the failure message was obscured by another.
You can also receive a 406 response when invalid cookies are stored or referenced in the browser - for example, when running a Rails server in Dev mode locally.
If you happened to run two different projects on the same port, the browser might reference a cookie from a different localhost session.
This has happened to me...tripped me up for a minute. Looking in browser > Developer Mode > Network showed it.
const request = require('request');
const headers = {
'Accept': '*/*',
'User-Agent': 'request',
};
const options = {
url: "https://example.com/users/6",
headers: headers
};
request.get(options, (error, response, body) => {
console.log(response.body);
});
Changing header to Accept: */* resolved my issue and make sure you don't have any other Accept Header
In my case, I added:
Content-Type: application/x-www-form-urlencoded
solved my problem completely.
If you are using 'request.js' you might use the following:
var options = {
url: 'localhost',
method: 'GET',
headers:{
Accept: '*/*'
}
}
request(options, function (error, response, body) {
...
})
In my case for a API in .NET-Core, the api is set to work with XML (by default is set to response with JSON), so I add this annotation in my Controller :
[Produces("application/xml")]
public class MyController : ControllerBase {...}
Thank you for putting me on the path !
It could also be due to a firewall blocking the request. In my case the request payload contained string properties - "like %abc%" and ampersand symbol "&" - which caused the firewall to think it is a security risk (eg. a sql injection attack) and it blocked the request. Note here the request does not actually go to the server but is returned at the firewall level itself.
In my case, there were no application server logs generated so I knew that the request did not actually reach the server and was blocked before that. The logs that helped me were Web application firewall (WAF) logs.

HTTP Delete, Response Status: 405 (Method Not Allowed)

when sending http delete to my server this happens
Response Status: 405 (Method Not Allowed)
header look like this
Date: Sat, 31 Jan 2015 19:17:47 GMT
Server: WildFly/8
Connection: keep-alive
X-Powered-By: Undertow/1
Content-Length: 0
Allow: HEAD, POST, GET, OPTIONS, PUT
I suspect that I have to enable access to http delete method, but don't know how.
this is my delete method
#DELETE
#Path("/{id}")
public boolean deleteItem(#PathParam("id") long itemId);
this is the url for delete
wrong: http://192.168.2.101:8080/DataAccessRemoteWebapp/rest/dataitem/id=1
right: http://192.168.2.101:8080/DataAccessRemoteWebapp/rest/dataitem/1
I am using jax-rs
import javax.ws.rs.DELETE;
The annotation #Path("/{id})" requires the id directly after the / and so it won't match your test URL
http://192.168.2.101:8080/DataAccessRemoteWebapp/rest/dataitem/id=1
Instead, remove the id=:
http://192.168.2.101:8080/DataAccessRemoteWebapp/rest/dataitem/1
This old post on stackoverflow can respond to you question :
URL = /contacts/delete/contactname
405 because
It seems delete is always behave as submit (Post method) and you are
trying >to call as like get method from the URL. This is not possible
to call the >post method as like get. if you really want to call this
web service from >the browser to test, just download a Mozilla plugin
(Poster) which will help >you to submit the web service in your all
method types.

Get parameters of the POST request with ZK Framework

I want to pass data from one application (Spring MVC) to another application written with ZK Framework using POST request.
One of the parameters of the post method will be a file. Let's call it id.
So, what I do have now is Composer with the following code:
public class PictureComposer extends SelectorComposer<Component> {
#Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
Execution e = Executions.getCurrent();
System.out.println("post param: " + Executions.getCurrent().getParameterMap().get("id"));
HttpServletRequest request = (HttpServletRequest) e.getNativeRequest();
String idd = request.getParameter("id");
System.out.println("id: " + idd);
}
}
And, when I try to make a POST request to this composer, Executions.getCurrent().getParameterMap().get("id") seems to return null.
Same thing with the second approach (using HttpServletRequest).
On the other hand, I get some value for id, when I use GET request and pass this value as a parameter in the URL. But, unfortunately, I cannot pass my file in the URL.
So, the main question is how I can retrieve the variable from the POST request?
UPD: (for now I try to retrieve a plain string parameter, just as simplified example) My POST request looks like this:
POST /zssessentials/picture.zul HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="id"
wooooow
----WebKitFormBoundaryE19zNvXGzXaLvS5C
In order to retrieve an uploaded file, you should set enctype property of your <form> element to multipart/form-data, as below:
<form method="POST" action="your/zk/address" enctype="multipart/form-data" >
...
</form>
Then you can use the getPart method of HttpServletRequest class to access the uploaded file. So your code should be changed to something like this:
Part filePart = request.getPart("id");
InputStream filecontent = filePart.getInputStream();
I've figured out.
The reason was that the servlet didn't parse the multipart requests on its own.
I had been sending requests with this line in the header (even if it was plain string or integer values):
Content-type: multipart/form-data
and that was the reason.
So, I was expected to use the third-party library in the PictureComposer class.
In my case Streaming API from Apache came in handy.
Also, this StackOverflow answer helped me a lot in resolving my problem.

How to send a JSON string with an HTTP request using in Java using HTTPClient

This is my first question. I love stackOverflow but I've always been a reader, not a writer. Now here goes nothing:
So I've seen a LOT of different questions like this, believe me, I looked... but none of them seemed to answer my question exactly. I'm designing a test harness to test an API, and it involves sending HTTP requests using HttpClient (in Java). For some of the requests, such as POST requests, a JSON string or an XML string must be sent with the request. (I'm only asking about JSON here, if anyone had the answer of how to do the XML as well, I'd love that, but I'll save it for another question.)
Anyways, I have the following code so far which seems like it SHOULD do what I want... but I'm getting 400 error. I'm going to assume that I've properly created an instance of an HttpClient and an HttpPost, applied appropriate headers, etc... the pertinent part is below:
JSONObject JSONpayload = new JSONObject();
JSONpayload.put("quantity", 1);
JSONpayload.put("sku", "21-53429");
String JSONstring = JSONpayload.toString();
System.out.println("JSON PAYLOAD BEING SENT: " + JSONstring);
request.setEntity(new StringEntity(JSONstring));
response = client.execute(request);
System.out.println("SERVER RESPONSE STRING: " + response.toString());
And I receive the following output:
JSON PAYLOAD BEING SENT: {"quantity":1,"sku":"21-53429"}
SERVER RESPONSE STRING: HTTP/1.1 401 Unauthorized
[Date: Thu, 27 Jun 2013 19:57:29 GMT,
Server: Mule Core/3.3.1,
Set-Cookie: sid=h8jumUyMxMztmB1AHtbvmUzzc9WchbiR9dQahD6Q; Version=1;
Domain=192.168.235.9;
Path=/,
http.status: 401,
X-MULE_SESSION: rO0ABXNyACNvcmcubXVsZS5zZXNzaW9uLkRlZmF1bHRNdWxlU2Vzc2lvbi7rdtEW7GGKAwAEWgAFdmFsaWRMAA1mbG93Q29uc3RydWN0dAAmTG9yZy9tdWxlL2FwaS9jb25zdHJ1Y3QvRmxvd0NvbnN0cnVjdDtMAAJpZHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wAD3NlY3VyaXR5Q29udGV4dHQAJ0xvcmcvbXVsZS9hcGkvc2VjdXJpdHkvU2VjdXJpdHlDb250ZXh0O3hwAXB0ACRjYzQwMmMwNy1kZjYzLTExZTItOGY1Yi1kOTk2MTM2MzZkZjJwc3IAJWphdmEudXRpbC5Db2xsZWN0aW9ucyRTeW5jaHJvbml6ZWRNYXAbc/kJS0s5ewMAAkwAAW10AA9MamF2YS91dGlsL01hcDtMAAVtdXRleHQAEkxqYXZhL2xhbmcvT2JqZWN0O3hwc3IAJG9yZy5tdWxlLnV0aWwuQ2FzZUluc2Vuc2l0aXZlSGFzaE1hcJ3R2e9nRc4AAwAAeHB3DD9AAAAAAAAQAAAAB3QABWR1bW15dAAYOU9WX0FBQUJHQmdBQUFFX0lTQVFBNGMydAAJUm91dGVkVVJMdABhaHR0cDovLzE5Mi4xNjguMjM1Ljk6MzA4MC9nc2kvcmVzdC9XRlMvVE1TTkEtVE1TVVMtU2l0ZS9yZXN0L2NhcnRzLzlPVl9BQUFCR0JnQUFBRV9JU0FRQTRjMi9pdGVtc3QAC0NvbnRleHRQYXRodAATZ3NpLWV3cy1zZXJ2aWNlL3N2Y3QAC291dHB1dC10eXBldAAQYXBwbGljYXRpb24vanNvbnQAClJlcXVlc3RVUkx0AEsvZ3NpLWV3cy1zZXJ2aWNlL3N2Yy92MS4wL3N0b3Jlcy9UTVNVUy9jYXJ0cy85T1ZfQUFBQkdCZ0FBQUVfSVNBUUE0YzIvaXRlbXN0AAdTdG9yZUlEdAAMc3RvcmVzL1RNU1VTdAAKaW5wdXQtdHlwZXEAfgATeHEAfgAJeHg=,
X-MULE_ENCODING: UTF-8,
Content-Type: text/plain,
Transfer-Encoding: chunked]
Now, I know the basic things and I'm pretty sure I've taken care of them... like setting the headers Accept application/json, Content-Type application/json, etc..
Any advice would be greatly appreciated. I'm new to using HttpClient and I'm a little lost haha. Thanks guys!
The problem is that this server requires authentication and you're not providing it (or using invalid credentials). I can tell that because the response code was 401 (Unauthorized).
401: Similar to 403 Forbidden, but specifically for use when authentication
is required and has failed or has not yet been provided [...]
HTTPClient's home page has a lot of information regarding authentication. You can check how to do that here also check some code examples here.

Categories

Resources