How to filter invalid parameters in the curl command data using Jersey framework - jersey

My resource class:
#POST
#Path("/add")
#Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Object add(Flow flow){
Object obj = fun(flow.getParam1(),flow.getParam2());
return obj;
}
Flow is a JAXB class, all params are its member variables.
Commands used:
curl -X POST -HContent-type:application/xml -k --data "<rootElementName param1=\"val1\" param2=\"val2\"/>" https://<ip>:8443/xxxx/add
curl -X POST -HContent-type:application/json -k --data "{\"#param1\":\"val1\",\"#param2\":\"val2\"}" https://<ip>:8443/xxxx/add
My requirement is to identify invalid parameter name and through error.
Ex:
curl -X POST -HContent-type:application/xml -k --data "<rootElementName invalidParam1=\"val1\" param2=\"val2\"/>" https://<ip>:8443/xxxx/add
Resource class has to validate this data and return message Invalid param: invalidParam1
For HTTP GET method, I have done this by iterating the multi valued map uriInfo.getQueryParameters()
Please suggest better way to do this invalid param validation for POST method (if possible by reusing the multi valued map validation code)

Related

playframework - Can't read cookie from request

How can I get the cookie from a request in playframework?
I have the following test endpoint
def home = Action.async { implicit request =>
println(request)
println(request.session)
println(request.flash)
request.session.get("session") match {
case Some(cookie) => Future(Ok(cookie))
case None =>
Future(BadRequest(Json.obj("message" -> "missing session cookie")))
}
}
When submitting the following request:
curl 'http://local.example.com:9000/home' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Connection: keep-alive' -H 'Cookie: session=eyJhbGciOiJSUzI1NiIsImtpZCI...' -H 'Upgrade-Insecure-Requests: 1' -H 'Cache-Control: max-age=0'
I unfortunately get the "missing session cookie" response. and the following printout on the console
GET /home
Session(Map())
Flash(Map())
I don't know what I'm doing wrong. Any help is much appreciated.
Edit: I set the cookie using the following method:
def tokenLogin = Action(parse.json).async { implicit request =>
val loginRequest = request.body.validate[LoginRequest]
loginRequest.fold(
errors =>
{
println(errors)
Future(BadRequest(Json.obj("message" -> JsError.toJson(errors))))
},
request => {
println("in success")
firebaseAdminService
.createSessionCookie(request.idToken)
.map(sessionCookie =>
Ok("success")
.withNewSession
.withCookies(Cookie(name = "session", value = sessionCookie))
)
}
)
}
By default, the session cookie in Play is called "PLAY_SESSION" (configuration play.http.session.cookieName).
So, you would need to use -H "Cookie: PLAY_SESSION=..." with curl.
But note, this won't work with arbitrary data since Play uses JWT and signs the information contained in the session cookie using its crypto secret.
The only thing expected to work is using a session cookie received in a Set-Cookie header from your Play service in another request to the same service (having the same secret).
update after your edit:
When using request.session, you are accessing the session cookie, which is called PLAY_SESSION and the information stored inside it.
But, you are setting a cookie of your own. This is something else.
You can access "normal" cookies with
request.cookies.get("session")
Oh, and in case you really wanted to make use of the session cookie, you can set it like this:
Ok("success").withSession("session" -> sessionCookie)

Spring WebFlux not streaming response

I was expecting this code to stream events to the client (code is in Kotlin but Java is very similar)
#RestController
object CustomerController {
#GetMapping("/load", produces = arrayOf("application/stream+json"))
fun load(): Flux<String> {
var flux = Flux.fromIterable(ResultIterable())
flux.subscribe({println(it)})
return flux
}
}
ResultIterable is an iterable that generates a string on regular intervals. An infinite stream basically.
I don't see any output, it hangs forever.
I do see the string being printed on regular intervals (println(it)).
I am using the following curl:
curl -X GET http://localhost:8080/load -H 'accept: application/stream+json' -H 'cache-control: no-cache' -H 'content-type: application/stream+json'
Your error is here:
flux.subscribe({println(it)})
You subscribe to the Flux and consume it directly in the method.
When this Flux reaches the Reactor Netty HTTP container, there is nothing to consume already.
If you really would like println() each item, consider to use doOnNext() instead and really leave that subscribe() to the container.
Also you have to really follow Server Side Events rules:
The server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream".
https://www.w3schools.com/html/html5_serversentevents.asp
So, when I do this:
#GetMapping("/load", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
fun load() =
Flux.just("foo", "bar", "baz")
.doOnNext({ println(it) })
I start to get Server Side Events in my connected client:
C:\tmp\so50823339>curl -X GET http://localhost:8080/load
data:foo
data:bar
data:baz
C:\tmp\so50823339>
where at the same time I get logs on the server for the mentioned doOnNext():
2018-06-12 17:33:37.453 INFO 6800 --- [ main] c.e.s.s.So50823339ApplicationKt : Started So50823339ApplicationKt in 3.112 seconds (JVM running for 3.924)
foo
bar
baz

parse.com cloud code GET function with parameters?

I'm writing a cloud code function in parse and I'm trying to figure out how to handle parameters in the GET url.
So I have a simple function like this:
Parse.Cloud.define("someFunction", function(request, response) {
// how can I use GET parameters here??
});
How to I rename the "someFunction" to handle GET parameters so I can use them in my cloud code function logic?
so for example I want to be able to pass in a name string: "myName" in the GET
https://api.parse.com/1/functions/someFunction?name=myName
Any simple example? I searched for a while I couldn't find one.
Thank you
EDIT:
So I modified my function to look like this:
Parse.Cloud.define("someFunction", function(request, response) {
// how can I use GET parameters here??
var name = request.params.name
response.success("the name = " + name)
});
then I call it like this:
https://api.parse.com/1/functions/someFunction?name=someName
what I get back is this:
{"result":"the name = **undefined**"}
Cloud Functions are called with a POST request, not a GET request. Here is a simple example for cURL I took from the documentation [1].
curl -X POST \
-H "X-Parse-Application-Id: YOUR_APP_ID" \
-H "X-Parse-REST-API-Key: YOUR_REST_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"John Doe"}' \
https://api.parse.com/1/functions/someFunction
[1] https://www.parse.com/docs/cloud_code_guide#functions
try calling the Cloud from JS layer...
Parse.initialize(appId, jsId);
p = Parse.Cloud.run('someFunc', {"name":refToName}).then(function(result) {

reading parameters on Sinatra post

I'm working on my first Sinatra app and I have an hard time getting parameters from a post request.
I'm using MiniTest::Spec and my spec looks like
payload = File.read("./spec/support/fixtures/payload.json")
post "/api/v1/verify_payload", { payload: payload }, { "CONTENT_TYPE" => "application/json" }
last_response.body.must_eql payload
And this is my route
namespace '/api/v1' do
post '/verify_payload' do
MultiJson.load(params[:payload])
end
end
The spec fails because last_response.body is empty.
Am I missing something here?
I also tried to return the entire params from verify_payload but also in that case it returned an empty string.
Update
curl -X POST -H "Content-Type: application/json" -d '{"payload":"xyz"}' http://localhost:9292/api/v1/verify_payload
does not return anything and no error on the server log
[2014-01-06 01:16:25] INFO WEBrick::HTTPServer#start: pid=10449 port=9292
127.0.0.1 - - [06/Jan/2014 01:16:27] "POST /api/v1/verify_payload HTTP/1.1" 200 6 0.0220
Thanks
Sinatra just doesn't parse this data, because they are not form parameters.
Form parameter would look like this
curl -X POST 127.1:4567/ -d "foo=bar"
Instead of params you can just use request.body.read or use rack contrib.
rack-contrib
Install it with gem install rack-contrib
require it
require 'rack'
require 'rack/contrib'
load it use Rack::PostBodyContentTypeParser
with this you can use params as normal for json post data. Something like this:
curl -X POST -H "Content-Type: application/json" -d '{"payload":"xyz"}' 127.1:4567/
source for this: Sinatra controller params method coming in empty on JSON post request, http://jaywiggins.com/2010/03/using-rack-middleware-to-parse-json/

JAX-RS How to choose image mimetype?

Is there any way to select the very best Accept mimetype for image manipulation?
I have a resource looks like this.
#GET
#Produces({"image/jpeg", "image/png"})
public Response readResizedImage(
#Context Request request,
#Context HttpHeaders httpHeaders,
#QueryParam("width") final int width,
#QueryParam("height") final int height) {
final List<Variant> variants = Variant.mediaTypes(
new MediaType("image", "jpeg"), new MediaType("image", "png")).build();
// Why on earth variants is empty?
if (!variants.isEmpty()) {
final Variant variant = request.selectVariant(variants);
LOGGER.log(Level.INFO, "{0}", variant.getMediaType().toString());
}
final List<MediaType> acceptableMediaTypes =
httpHeaders.getAcceptableMediaTypes();
for (MediaType acceptableMediaType : acceptableMediaTypes) {
LOGGER.log(Level.INFO, "acceptableMediaType:{0}/{1}",
new Object[]{acceptableMediaType.getType(),
acceptableMediaType.getSubtype()});
}
return null;
}
I tried this resource with following command.
$ curl -v -H "Accept: */*" \
-H "Accept: image/*;q=0.2" \
-H "Accept: image/jpeg;q=0.5" \
-H "Accept: image/png;q=1.0" \
http://.............
And server prints
acceptableMediaType:image/png
acceptableMediaType:*/*
acceptableMediaType:image/jpeg
acceptableMediaType:image/*
QUESTION:
How can I select a proper (not wildcarded) mime type?
I must have one for manipulating image bytes for re-sizing.
It is easiest if you leave this up to Jersey - i.e. have 2 methods, one producing image/png, other producing image/jpeg. Jersey will call the right one depending on the quality parameter of individual media types in the accept header of the incoming request.

Resources