Test putting badly formed json using JerseyInvocation builder - java

I'm trying to write an integration test to ensure that my dropwizard application is returning appropriate error codes. One of the scenarios includes ensuring that if the object being PUT is not deserialisable, I get a reasonable error response.
I can't find a way using JerseyInvocation.Builder to PUT a badly-formed JSON entity. The only way to create an Entity appears to be by having an object of the correct type, which obviously will deserialise. I want to be able to create an entity whose serialised value is an arbitrary string that I provide.
I've tried putting objects of the wrong type, but that doesn't test all of the edge cases I want to test. I also want to avoid creating a lot of types that are subtly different from the object the API is expecting.
Can anyone suggest a way of achieving what I want?
Update: this is the code I'm using at the moment:
JerseyInvocation.Builder request; // initialised elsewhere and not interesting
is = new ClassPathResource(nameOfFileContainingWellFormedJson, MyEntityClsss.class).getInputStream();
entity = Entity.entity(is, MediaType.APPLICATION_JSON);
request.put(entity);
This response should be returning 200 and is returning 400.
is = new ClassPathResource(nameOfFileContainingBadlyFormedJson, MyEntityClsss.class).getInputStream();
entity = Entity.entity(is, MediaType.APPLICATION_JSON);
request.put(entity);
This response is returning 400, but until the above is returning 200 it's not doing so for the right reasons.

You can use the Jersey Entity class, used for raw streams of any mime-type. Something like:
ByteArrayInputStream bais = new ByteArrayInputStream("{\"malformattedJson".getBytes());
builder.post(Entity.entity(bais, "application/json"));
Or load the malformed JSON from a file/classpath resource in your tests to ditch the double quote escaping 😉

Related

Convert Spring webclient error response body from string to object

In this method the msg variable is returning in string format..how can be conversion of it can be taken place into certain java pojo object.
Method image
In place of Mono I tried Mono but it didnt worked for me.
I just want to get the error response body in pojo object format rather then in string format.
Also tried in this manner, but no success.
Tried in this manner
do you know what class the response is in case of an error? ResponseEntity perhaps?
you need to use a JSON converter package to convert it into a POJO, but you first need to make a POJO class of your own with the relevant fields (and make sure to name them in case sensitive manner).
then, inside the .flatMap(...) turn the String into the POJO using the converter.

Java Spring #ResponseBody return XML with produce attribute

Recently, I'm trying to get the xml file under the resources file. Then all the questions come out.
I read so many articles say something like:
#ResponseBody tells a controller that the object returned is
automatically serialized into JSON and passed back into the
HttpResponse object.
So my question is: the produces attribute is used to narrow the mapping by the media types that can be produced by the mapped handler, not to declare the media types the mapped handler will produce, right? Then how should I return xml content in the condition of automatically serialized into JSON format? I guess I mess up the meaning of the content showing in the view with HTTP response body... Please someone explain to me nicely and patiently :"(

How to consume a Spring HAL/HATEOAS API in Java using purely Jackson, not Spring

We are trying to create a Java client for an API created with Spring Data.
Some endpoints return hal+json responses containing _embedded and _links attributes.
Our main problem at the moment is trying to wrap our heads around the following structure:
{
"_embedded": {
"plans": [
{
...
}
]
},
...
}
When you hit the plans endpoint you get a paginated response the content of which is within the _embedded object. So the logic is that you call plans and you get back a response containing an _embedded object that contains a plans attribute that holds an array of plan objects.
The content of the _embedded object can vary as well, and trying a solution using generics, like the example following, ended up returning us a List of LinkedHashMap Objects instead of the expected type.
class PaginatedResponse<T> {
#JsonProperty("_embedded")
Embedded<T> embedded;
....
}
class Embedded<T> {
#JsonAlias({"plans", "projects"})
List<T> content; // This instead of type T ends up deserialising as a List of LinkedHashMap objects
....
}
I am not sure if the above issue is relevant to this Jackson bug report dating from 2015.
The only solution we have so far is to either create a paginated response for each type of content, with explicitly defined types, or to include a List<type_here> for each type of object we expect to receive and make sure that we only read from the populated list and not the null ones.
So our main question to this quite spread out issue is, how one is supposed to navigate such an API without the use of Spring?
We do not consider using Spring in any form as an acceptable solution. At the same time, and I may be quite wrong here, but it looks like in the java world Spring is the only framework actively supporting/promoting HAL/HATEOAS?
I'm sorry if there are wrongly expressed concepts, assumptions and terminology in this question but we are trying to wrap our heads around the philosophy of such an implementation and how to deal with it from a Java point of view.
You can try consuming HATEOS API using super type tokens. A kind of generic way to handle all kind of hateos response.
For example
Below generic class to handle response
public class Resource<T> {
protected Resource() {
this.content = null;
}
public Resource(T content, Link... links) {
this(content, Arrays.asList(links));
}
}
Below code to read the response for various objects
ObjectMapper objectMapper = new ObjectMapper();
Resource<ObjectA> objectA = objectMapper.readValue(response, new TypeReference<Resource<ObjectA>>() {});
Resource<ObjectB> objectB = objectMapper.readValue(response, new TypeReference<Resource<ObjectB>>() {});
You can refer below
http://www.java-allandsundry.com/2012/12/json-deserialization-with-jackson-and.html
http://www.java-allandsundry.com/2014/01/consuming-spring-hateoas-rest-service.html

How can I handle a situation where I need to send JSON and multipart/form-data in Spring boot

I would like to know a simple solution for receiving images and simple data in a single post using Spring. I am a beginner in Java so I would like to know the easy way. I've used several backend frameworks and I've encountered this problem in all of them.
I have the following problem:
I was receiving a multipart/form-data like this
public CasaVenda storeCasaVendaOld(#RequestParam("dormitorios") Integer dormitorios, #RequestParam("preco") Double preco, #RequestParam("foto_1") MultipartFile foto_1){
I receive some numbers along with an image. This is a typical first attempt of beginner's implementation.Validate will require code to be writeen in the controller and I have to receive far more parameters than described here, so it's a bad implementation.
I thought about receiving a model
public CasaVenda storeCasaVenda(#Valid #RequestBody CasaVenda casa)
Now I can validate using annotations and so. The problem is with the file. Is there a simple solution to receive the file in one post request or should I split the process of seding the overall data and the files spareted? I mean I can make the process of the resource creation two steps, first it enters the overall data and afterwards it includes the photos.
Its pretty easy to define an object:
public class MyObject {
private Integer dormitorios;
private Double preco;
...
getters/setters/constructors/etc.
...
// I'm not sure whether you can place a MultipartFile here as well to process image,
// however it doesn't make sense to validate it anyway
}
Then you can use this object in the controller, it will map all the query params to the fields of the object automatically by spring:
public CasaVenda storeCasaVendaOld(MyObject myObject) {
}
Now, you can place Validation annotations inside MyObject and it will be validated, just do not use #RequestParam annotation before the object...

Consuming PagedResources in abstract class

I have a server that exposes data with the spring-data-rest project and now I am writing services to consume those data and I started with a generic service that will suit all the common needs, one of which is getting the Page object.
I configured my RestTemplate to use the Jackson2HalModule as suggested here.
I've tried a lot of combinations and I was only able to use consume it properly in a non-generic way like this:
PagedResources<Resource<Company>> response2 = restTemplate.exchange(getUrl(), HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference<PagedResources<Resource<Company>>>(){}).getBody();
But trying the same code with T didn't work (Resource links were deserialized but content of Resource object was null)
PagedResources<Resource<T>> response3 = restTemplate.exchange(getUrl(), HttpMethod.GET, HttpEntity.EMPTY, new ParameterizedTypeReference<PagedResources<Resource<T>>>(){}).getBody();
Generically I am only able to deserialize the Company data using the following code:
PagedResources<T> response1 = restTemplate.exchange(getUrl(), HttpMethod.GET, HttpEntity.EMPTY, PagedResources.class).getBody();
But this one doesn't deserialize the Resource object so the Company&Links data of what should be the Resource object are stored in a LinkedHashMap instead.
I also tried using the object mapper on the LinkedHashMap with data but I was unsuccessful. It's been a long day so I might be too close to see the correct way of doing this. I'll appreciate any help with this. Thank you.
The question: Is there a way of getting proper generics working in this case?

Categories