RestTemplate and variable number of variable - java

I have to post json to api_url for login.
{
"username":"testre","password":"password"
}
When I use postman to check this api, it reply successful authentication like below.
{
"status": "success",
"code": 200,
"message": "username, password validated.",
"data": [
{
"password": "password",
"username": "testre"
}
],
"links": [
{
"rel": "self",
"link": "http://localhost:2222/pizza-shefu/api/v1.0/customers/login/"
},
{
"rel": "profile",
"link": "http://localhost:2222/pizza-shefu/api/v1.0/customers/testre"
}
]
}
For an unauthorized json like below.
{
"status": "unauthorized",
"code": 401,
"errorMessage": "HTTP_UNAUTHORIZED",
"description": "credentials provided are not authorized."
}
Previously I code to retrieve it using java. But now I want to refactor it using RestTemplate in spring. The problem is every example I read is written for fixed number of variables https://spring.io/guides/gs/consuming-rest/. Here I get different numbers of variable according to the login success status. I am new to spring so I'm confused in creating the class for login reply which we get from rest template. (Such as this in the example Quote quote = restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); But I need to return a json object). I couldn't figure out how to write the RestTemplate part.

As suggested by #Andreas:
Add the superset of all fields for all possible responses
Identify the set of fields that are mandatory for every response and make them required
Make the rest of the fields as optional
Upon receveiving a response, check the status code and implement your logic accordingly.
If you are using Jackson for Deserialization, all fields are optional by default (see this question)

Related

Do I need admin consent on Microsoft Graph Api?

I'm working on a project in which I need to create events in my calendar, for this I am using the GRAPH API and there should be no user interaction. I'm using my personal account.
As a test I am making a call in Postman to which I add the token I got from the URL
https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token
https://graph.microsoft.com/v1.0/users/me/events
{
"subject": "My event",
"start": {
"dateTime": "2020-06-22T13:32:53.037Z",
"timeZone": "UTC"
},
"end": {
"dateTime": "2020-06-29T13:32:53.037Z",
"timeZone": "UTC"
}
}
But I'm getting this error
{ "error": { "code": "NoPermissionsInAccessToken", "message": "The token contains no permissions, or permissions can not be understood.", "innerError": { "requestId": "b4ffb07b-8a7b-4893-93ae-1a3bb8be8f28", "date": "2020-06-23T03:14:49", "request-id": "b4ffb07b-8a7b-4893-93ae-1a3bb8be8f28" } } }
This is my token's body
These are the app permissions
Is this error because I don't have the admin consent or l'm doing something wrong?
Did you register your app in Azure AD?
Please follow steps described here:
https://learn.microsoft.com/en-us/graph/auth-v2-service?context=graph%2Fapi%2F1.0&view=graph-rest-1.0
Permission level you need is Calendar.ReadWrite

How to parse FirebaseAuthException exception message (Admin SDK Java)?

I'm using Firebase Admin SDK Java API v6.12.2.
I call FirebaseAuth.getInstance().generatePasswordResetLink(email, actionCodeSettings) to generate a password reset link for users. If the email isn't registered, I get a big blob of text with embedded JSON from e.getMessage().
The looked at the FirebaseAuthException doc and it only exposes one method e.getErrorCode(), which in this case returns internal-error.
I can certainly parse this text to look for "EMAIL_NOT_FOUND" and translate it into a user-friendly message. But isn't that a very clumsy error message? At least, there should have been methods to return the error code 400, and a simple String message, and the details could go into a JSON object.
What is the recommended approach here by the Firebase team and how are other developers handling it?
Output of e.getMessage():
Unexpected HTTP response with status: 400; body: {
"error": {
"code": 400,
"message": "EMAIL_NOT_FOUND",
"errors": [
{
"message": "EMAIL_NOT_FOUND",
"domain": "global",
"reason": "invalid"
}
]
}
}

Spring Cloud config throws NPE empty for array in the file

We used Spring Cloud Config version 2.1 and it worked.
We updated to Spring Cloud Config 2.2, and now it does not work.
More details are
https://github.com/spring-cloud/spring-cloud-config/issues/1599
I reported the issue to accelerate the process as well, or maybe it is not an issue. I do not know, so I am asking you to help.
Our config file: python-service.yml
resources:
- resource1
- resource2
newResources: []
As I learned, Spring Cloud config client makes requests to fetch configuration, and it passes header
Accept: application/vnd.spring-cloud.config-server.v2+json.
In Spring Cloud config v 2.1
Note, Spring Cloud version 2.1 does not send such header; instead, it sends Accept: application/json
HTTP http://localhost:8888/python-service/dev
Accept: application/vnd.spring-cloud.config-server.v2+json
Returns
{
"name": "python-service",
"profiles": [
"dev"
],
"label": null,
"version": null,
"state": null,
"propertySources": [
{
"name": "file:/configuration/python-service.yml",
"source": {
"resources[0]": "resource1",
"resources[1]": "resource2",
"newResources": []
}
}
]
}
However, it Spring Cloud Config v 2.2, it fails
{
"timestamp": "2020-04-24T08:38:19.803+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Could not construct context for config=python-service profile=dev label=null includeOrigin=true; nested exception is java.lang.NullPointerException",
"path": "/python-service/dev"
}
The funny thing is that there is no exception log output in config-service logs!
If I remove the accept header, I will get (version 2.2)
{
"name": "python-service",
"profiles": [
"dev"
],
"label": null,
"version": null,
"state": null,
"propertySources": [
{
"name": "file:/configuration/python-service.yml",
"source": {
"resources[0]": "resource1",
"resources[1]": "resource2",
"newResources": ""
}
}
]
}
Here, why "newResources": "" became an empty String, if it is expected to be an empty array - another question.
To sum up
1) How to use empty array in Spring Cloud config.
2) Why there is no log message about the NPE in Spring config-service logs.
3) Without the accept header, why "newResources": "" became an empty String, if I expected an empty array.
As for now, I can remove empty array from my config, but it is very scary because our config is used in many services! This breaks backward compatibility.
It turns out, it is a bug in Spring Boot.
https://github.com/spring-cloud/spring-cloud-config/issues/1572#issuecomment-620496235
https://github.com/spring-projects/spring-boot/issues/20506
Possible options:
1) Wait until it is fixed and update libraries.
2) What we did. We replaced empty array with empty element.
newResources:
anotherField: value
alternatively, use null. However, make sure, your code can handle it. Also, emptyArray can be treated as an emptyString. I found this out in debugger.

Generate valid Authorization:Basic

I'm trying to generate correct string for Authorization:Basic [string] but i fail because i'm not really sure what info should i encode.
First request that client sends is sign_up request which doesn't include Authorization.Response for that request looks like this:
{
"user": {
"name": "Genome",
"id": 2417370297
},
"identifier": "OFpDN0VJU3UxM1B1dTZTWDNMS1hqYWNwbmFjM3Zib0lBaTJYbTdUUWVWRkhTUUdYVWJyK0FobnppY1pkZEFwTG1OQkpoQjBGOVY5RmVtN0RtQ1BsUEE9PTpZaTc1SFZBeDFsWGxZaUZNeDZxTTZRPT0="
}
After that,the next request client should send is sign_in which includes Authroization:Basic.This is how Authorization looks:
Authorization: Basic WWk3NUhWQXgxbFhsWWlGTXg2cU02UT09OjhaQzdFSVN1MTNQdXU2U1gzTEtYamFjcG5hYzN2Ym9JQWkyWG03VFFlVkZIU1FHWFVicitBaG56aWNaZGRBcExtTkJKaEIwRjlWOUZlbTdEbUNQbFBBPT0=
Problem is i don't know how to generate that string after "Basic" .If you need any info ask here
Basic authentication is name:password encoded in Base64.

using google api explorer to upload data to google cloud storage

i am trying to use google api explorer to first try to insert an object to google cloud storage.
the request looks like
POST https://www.googleapis.com/storage/v1/b/visionapibucket/o?key={YOUR_API_KEY}
{
"contentType": "image/jpeg",
"uploadType": "media",
"path": "/upload/storage/v1/b/visionapibucket/o"
}
but i see the error as
400 HTTP/2.0 400
- Show headers -
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required"
},
{
"domain": "global",
"reason": "wrongUrlForUpload",
"message": "Upload requests must include an uploadType URL parameter and a URL path beginning with /upload/",
"extendedHelp": "https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload"
}
],
"code": 400,
"message": "Required"
}
}
not sure what i am missing. please advise
Looks like a bug on the website. It doesn't seem like the explorer supports media.
The request it generated looks like:
POST https://www.googleapis.com/storage/v1/b/visionapibucket/o?key={YOUR_API_KEY}
But a proper upload request would look like:
POST https://www.googleapis.com/upload/storage/v1/b/visionapibucket/o?key={YOUR_API_KEY}&uploadType=media&name=myfile.jpeg
You'll also want to include a "Content-Type" header specifying that it's a JPEG image.
There's a guide on the various ways to upload objects using the JSON API here. The specific type you're looking for is like a simple upload.

Categories