Which annotation from Jax-RS api was used to retrieve the cookie value?
I tried with the below code
public String getCookieValue(#Context HttpHeaders headers){
headers.getCookies()
}
above code snippet gives a Map. how to retrieve a specific cookie value from it..!
Thanks
According to javadoc, headers.getCookies() call retrieves you "a read-only map of cookie name (String) to Cookie".
Map<String, Cookie> cookies = hh.getCookies();
Cookie myCookie = cookies.get("your cookie name");
I believe you're looking for #CookieParam
Since you have mentioned to return String and you are returning a map object, it must not be working.
Try this:
public String getCookieValue(#Context HttpHeaders headers){
return headers.getCookies().toString;
}
Related
I want to fetch the roles stored as claim in JWT. I am using following code to do that:
DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC512(SecurityConstants.SECRET.getBytes()))
.build()
.verify(token.replace(SecurityConstants.TOKEN_PREFIX, ""));
String user = decodedJWT.getSubject();
Claim claims = decodedJWT.getClaims();
String roles = claims.get("roles").toString();
But this ends up giving object code:
(Value of roles)JSONNodeClaim#10091
I debugged the code and found claims like this:
How can i extract the "ROLE_ADMIN" ?
You can cast the claim to the Claim class and call the .asString() method to return it as a string:
String claims = ((Claim) decodedJWT.getClaim("roles")).asString();
You can use the chain method call to get the below:
String claims = decodedJWT.getClaim("roles").as(TextNode.class).asText();
The roles are always multiple, hence need to call with extraction as a collection
List<SimpleGrantedAuthority> simpleGrantedAuthorities = decodedJWT.getClaim("role").asList(SimpleGrantedAuthority.class);
I try to put data from the NewOrderRequest(pojo) class into the parameters :
#Query("params") NewOrderRequest params
but I get this result:
resultQueryString: params com.example.city.Model.NewOrderRequest#f45c8ad
expectation result:
resultQueryString: params +911
Data setting:
NewOrderRequest newOrderRequest = new NewOrderRequest();
newOrderRequest.setPhone("+911");
NetworkService.getInstance()
.service()
.newOrder(newOrderRequest)
Request:
#Headers({"Accept:application/json", "Content-Type:application/json;"})
#POST("RemoteCall?method=Taxi.WebAPI.NewOrder")
Call<RegResponse>newOrder(#Header("Cookie") String setCookie,#Query("params") NewOrderRequest params);
Please tell me how to pass the phone to the parameter?
You are sending an Object in #Query param, Only #Body accepts the object as its param. What you want is to convert your Object into JsonObject. I assume you're using Gson Library.
NewOrderRequest newOrderRequest = new NewOrderRequest();
newOrderRequest.setPhone("+911");
NetworkService.getInstance()
.service()
.newOrder(new Gson().toJson(newOrderRequest))
Try below code
#Headers({"Accept:application/json", "Content-Type:application/json;"})
#POST("RemoteCall?method=Taxi.WebAPI.NewOrder")
Call<RegResponse>newOrder(#Header("Cookie") String setCookie,#Query("params") String phone);
As it is a post request, and the intention is to send the data as an json object, the data is better sent in the request body rather than query param. Also any sensitive details should be part of request body.
I tried to get product from API with some parameters. I used WooCommerce API Java Wrapper. REST API with OAuth 1.0. Simple getAll method return list of one page (10 products). To get all i must set how much products must be in one page and use offset. To get third page must send this parameters: "per_page=10&offset=20". I test with query in get&post programm - all work. In Java, when i added parameters - i got error (401)- "Invalid signature - the provided signature did not match".
I changed WooCommerceAPI class:
private static final String API_URL_FORMAT = "%s/wp-json/wc/v2/%s";
private static final String API_URL_ONE_ENTITY_FORMAT = "%s/wp-json/wc/v2/%s/%d";
private HttpClient client;
private OAuthConfig config;
public List getAll(String endpointBase) {
String url = String.format(API_URL_FORMAT, config.getUrl(), endpointBase) + "?per_page=10&offset=20";
String signature = OAuthSignature.getAsQueryString(config, url, HttpMethod.GET);
String securedUrl = String.format("%s&%s", url, signature);
System.out.println("url="+url);
System.out.println("securedUrl="+securedUrl);
return client.getAll(securedUrl);
}
But I have got the same error.
I've just released a new version of wc-api-java library (version 1.2) and now you can use the method getAll with params argument where you can put additional request parameters. For example:
// Get all with request parameters
Map<String, String> params = new HashMap<>();
params.put("per_page","100");
params.put("offset","0");
List products = wooCommerce.getAll(EndpointBaseType.PRODUCTS.getValue(), params);
System.out.println(products.size());
As you noticed, you changed URL_SECURED_FORMAT from "%s?%s" to "%s&%s", as soon as you added query params. But problem is that signature is generated based on all query params, not only oauth_*, and your params offset and per_page are ignored while generating signature (as soon as lib author did not expect additional params).
Think that you need to modify this lib to support signature based on all params.
I'm testing API endpoints. The problem is when I check on Swagger, it returns a valid token, but in my testing it returns NULL. Can you point out where I'm doing the wrong thing?
public static void createOrganization() {
Map<String, String> org = new HashMap();
org.put("directorName", "name");
org.put("email", "email#gmail.com");
org.put("website", "www.site.com");
org.put("phoneNumber", "000111");
String registrationToken = given().
contentType("application/json").
body(org).
when().
post("/v3/organizations").
then().
extract().path("registrationToken");
System.out.println("Token: "+ registrationToken);
Output: Token: null
UPDATE:
Maybe I'm using extract() incorrectly, maybe there's a different solution to use the generated values later. Since for registerDevice() I'm getting NULL as well.
public static void registerDevice(){
String clientDeviceId =
given().
param("phoneNumber", "000111").
param("model", "samsung").
param("platform", "0").
param("push_token",SenimEnvironmentVars.testPushToken).
param("uuid", SenimEnvironmentVars.testUUID).
param("version", "7.1").
when().
post("/v3/user-devices").
then().
contentType("application/json").
extract().path("clientDeviceId");
System.out.println("Device ID: "+ clientDeviceId); //also prints NULL
}
Is there any other ways to generate tokens, device IDs etc. and use them later?
As documentation says
You can extract values from the response or return the response
instance itself after you've done validating the response by using the
extract method
So try to write after then some validating method like contentType(JSON).
I am trying to call this API via postman:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void printDetails(final MultivaluedMap<String, String> formParams) {
for(String key : formParams.keySet()) {
System.out.println(key + " " + formParams.get(key));
}
}
But the map turns out to be empty. Please help me with the same.
PS: This is the first time I am trying to pass variable number of parameters to the api. I have referred to
sending List/Map as POST parameter jersey and How to access parameters in a RESTful POST method.
I think my mistake is in the way I am passing the parameters in postman: postman image
Please help me with the same. Also please help with how to call this API via an ajax (in JS) call.
Set the request header as "application/x-www-form-urlencoded".
Request body - Select raw and provide values as mentioned below:-
{
"LOCATION": "Singapore"
}
I have found out one possible answer.
#POST
public void printDetails() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
Map<String, String[]> mapp = request.getParameterMap();
for(String key : mapp.keySet()) {
System.out.println(key + " " + mapp.get(key)[0]);
}
}
Still not sure how to do it by passing "final MultivaluedMap" in the arguments