Getting the below exception in response to a get call with authToken.
Request:
Request request = new Request.Builder()
.url("https://sampleurlexample12345.com/api/apiname?param1=value1¶m2=value2")
.addHeader("Accept", "application/xyz.v1+json")
.addHeader(AUTHORIZATION_HEADER_VALUE,
BEARER_TOKEN + accessToken)
.build();
This is coming in response object of the get call, not getting an exception from our application, below is the full response object.
Response{protocol=h2, code=200, message=, url=https://sampleurlexample12345.com/api/apiname?param1=value1¶m2=value2}
java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.lang.String java.security.cert.Certificate.type accessible: module java.base does not "opens java.security.cert" to unnamed module
How to fix this issue?
Related
I'm trying to write tests for routes in a WebFlux application, but I encountered a problem. I got an error during parsing to JSON:
13:38:20.601 [parallel-1] DEBUG org.springframework.web.server.handler.ResponseStatusExceptionHandler - [248c6c90] Resolved [ServerWebInputException: "400 BAD_REQUEST "Failed to read HTTP message"; nested exception is org.springframework.core.codec.DecodingException: JSON decoding error: Cannot construct instance of `com.test.GetItemRequest` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.test.GetItemRequest` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)<EOL> at [Source: (org.springframework.core.io.buffer.DefaultDataBuffer$DefaultDataBufferInputStream); line: 1, column: 2]"] for HTTP POST /v1/download
I have a request that uses an inline class:
#JvmInline
value class ItemName(val rawValue: String)
data class GetItemRequest(val name: ItemName)
The test:
#Test
fun `Request is parsed successfully`() {
//...
val client = WebTestClient.bindToRouterFunction(router.eimApiRoutes()).build()
val request = """{"name":"item1"}"""
val resp = client
.post()
.uri(EimApiRouter.DOWNLOAD_PATH)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.body(Mono.just(request), String::class.java)
.exchange()
.expectStatus()
.isOk
.expectBody()
.returnResult()
.responseBody
val expectedResponse = "OK"
assertEquals(expectedResponse, String(resp!!))
}
I can work the problem around by adding a default constructor:
data class GetItemRequest(val name: ItemName) {
constructor() : this(ItemName(""))
}
When I change the type of the parameter to String, it works.
The question:
Could somebody give the real solution? Maybe there is something missing in the test web client configuration (I tried to configure the Kotlin codecs manually, but without success)?
MockMultipartFile file = new MockMultipartFile("files",
"Test.txt",
"text/plain",
this.getClass().getResourceAsStream("/Test.txt"));
webTestClient.post()
.uri("/foo").header("test", "1")
.header("test1", "1")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData("files", file))
.exchange()
.expectStatus().isOk();
Getting exception :
org.springframework.core.codec.CodecException:
Type definition error: [simple type, class java.io.ByteArrayInputStream];
nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer
(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
(through reference chain: org.springframework.mock.web.MockMultipartFile["inputStream"])
Where as it is working fine with my postman. Please find the attached screenshot of postmanenter image description here
webTestClient.post()
.uri("/foo").header("test", "1")
.header("test1", "1")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData("files", this.getClass().getResource("/Test.txt")))
.exchange()
.expectStatus().isOk();
I am getting exception while generating an Access Token using feign client. The same payload is working fine in the Postman.
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("grant_type", "client_credentials");
map.add("client_id", "67881e5b-f5d5-4085-8762-c35b7b6aeede");
map.add("client_secret", "D-85Pg3wN63dmznxa-puB_89Po~o5CsKhA");
map.add("scope", "https://graph.microsoft.com/.default");
AccessTokenResponse openIdTokenResponse = graphAPILoginFeignClient.getAccessIdToken("5494cc2e-fb14-4a2d-bb5e-bf164d9141cf",request);
Feignclient code:
#FeignClient(name = "GraphAPILoginFeignClient", url = "${graphApiLoginUrl}")
public interface GraphAPILoginFeignClient {
#PostMapping(value = "/{tenantID}/oauth2/v2.0/token",consumes = MediaType.APPLICATION_JSON_VALUE)
AccessTokenResponse getAccessIdToken(#PathVariable("tenantID") String tenantID,
#RequestBody MultiValueMap<String, Object> request);
}
Exception:
{
"timestamp": "2021-01-27T17:30:34.456+00:00",
"message": "[400 Bad Request] during [POST] to [https://login.microsoftonline.com/5494cc2e-fb14-4a2d-bb5e-bf164d9141cf/oauth2/v2.0/token] [GraphAPILoginFeignClient#getAccessIdToken(String,AuthorizationTokenRequest)]:
[{\"error\":\"invalid_request\",
\"error_description\":\"AADSTS900144: The request body must contain the
following parameter: 'grant_type'.\\r\\n
Trace ID: b8ef5f37-95f7-4427-8f0e-146a34b65000\\r\\n
Correlation ID: ... (503 bytes)]","details": "uri=/accessmanagement/allusers"
}
Same request payload working from Postman:
I had the same problem and the same code.
I was able to successfully execute the code by replacing the class method MultiValueMap::put with MultiValueMap::set.
In the LinkedMultiValueMap class, these methods are implemented differently.
In my project I have to create a chat box. For that I have to use Open-fire server. I am having the service for creating users in this server.
I am facing the problem when I am trying to access the openfire service from my spring boot application.
I am have created the model for the user also created the service and provided implementation to it.
This is my model class,
public class OpenFireUser {
private String firstname;
private String username;
private String password;
private String email;
<----getters and setters--->
}
This is my service,
public UserCreationResponse createOpenFireUser(String authorization,User createUser) {
OpenFireUser user= new OpenFireUser();
user.setEmail(createUser.getEmail());
user.setFirstname(createUser.getFirstname().toLowerCase());
user.setPassword("Passw0rd");
user.setUsername(createUser.getUsername().toLowerCase());
UserCreationResponse response=new UserCreationResponse();
RestTemplate restTemplate = new RestTemplate();
try{
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Authorization", authorization);
headers.add("Content-Type", "application/json");
headers.add("Accept", "application/json");
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<OpenFireUser> requestObject = new HttpEntity<OpenFireUser>(user, headers);
ResponseEntity<String> responseEntity=restTemplate.postForEntity(OPENFIRE_REST_ENDPOINT, requestObject,String.class);
int statusCode = responseEntity.getStatusCodeValue();
if(statusCode==201){
response.setResponseCode(statusCode);
return response;
}else{
response.setResponseCode(MessageConstant.ResponseCode.ProcessFail.value());}
return response;
}catch(HttpClientErrorException clientErr){
response.setUserMessage(clientErr.getMessage());
response.setResponseCode(clientErr.getStatusCode().value());
response.setResponseMessage(MessageConstant.CodeMessage.ProcessFail.value());
return response;
}
catch(Exception e)
{
response.setResponseCode(MessageConstant.ResponseCode.ProcessFail.value());
response.setResponseMessage(MessageConstant.CodeMessage.ProcessFail.value());
return response;
}
}
This is controller code for calling service,
#RequestMapping(value = "/createOpenFireUser", method = RequestMethod.POST, consumes = "application/json;charset=UTF-8",produces = "application/json;charset=UTF-8")
public UserCreationResponse createOpenFireUser(#RequestBody User createUser) {
logger.debug("Entering inside createOpenFireUser(#RequestBody OpenFireUser createUser) method");
//logger.debug("Create user request : {}" , createUserRequestEntity);
return userService.createOpenFireUser("authorizationKey",createUser);
}
while sending data from postman I am getting error like,
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of com.exelatech.printshop.model.User out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.exelatech.printshop.model.User out of START_ARRAY token
at [Source: java.io.PushbackInputStream#6c88daca; line: 1, column: 1]
2018-07-20 15:59:13.535 WARN 9988 --- [nio-9090-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize instance of model.User out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of model.User out of START_ARRAY token
at [Source: java.io.PushbackInputStream#6c88daca; line: 1, column: 1]
On postman I am getting response like,
"timestamp": 1532082553781,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not deserialize instance of model.User out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of model.User out of START_ARRAY token\n at [Source: java.io.PushbackInputStream#6c88daca; line: 1, column: 1]",
Can anyone help me to solve my issue?
Error was in sending object through postman.
Previously I was sending request object like,
[
{
"firstname" : "Jyoti",
"username" : "JyotiNH",
"password":"Passw0rd",
"email" : "jyoti.kanor#exelaonline.com"
}
]
which is object.
But my method receiving parameter as array of strings,
So when I sent request with object like following structure, it successfully created the user.
{
"firstname" : "Jyoti",
"username" : "JyotiNH",
"password":"Passw0rd",
"email" : "jyoti.kanor#exelaonline.com"
}
I have used to RestTemplate class to call a rest service, I am getting the below exception.
org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [UmlerUpdateRequest]
The below is my code snippet that I have tried:
RestTemplate restTemplate = new RestTemplate();
UmlerUpdateRequest obj= new UmlerUpdateRequest();
obj.setTrnspEqpId(equipId);
obj.setLstMaintId(lesseeScac);
obj.setRecLseScac(userId);
obj.setTareWgt(tareWeight);
obj.setBldD(builtDate);
String returns = restTemplate.postForObject(url, obj, String.class);
Can anyone help me on this?