1
|
|
|
package com.hltech.pact.gen.domain.pact; |
2
|
|
|
|
3
|
|
|
import com.fasterxml.jackson.core.JsonProcessingException; |
4
|
|
|
import com.fasterxml.jackson.databind.JsonNode; |
5
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper; |
6
|
|
|
import com.hltech.pact.gen.PactGenerationException; |
7
|
|
|
import com.hltech.pact.gen.domain.client.model.Body; |
8
|
|
|
import lombok.extern.slf4j.Slf4j; |
9
|
|
|
import uk.co.jemos.podam.api.PodamFactory; |
10
|
|
|
|
11
|
|
|
import java.util.Optional; |
12
|
|
|
|
13
|
|
|
@Slf4j |
14
|
|
|
final class BodySerializer { |
15
|
|
|
|
16
|
|
|
private BodySerializer() { |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
static JsonNode serializeBody(Body body, ObjectMapper objectMapper, PodamFactory podamFactory) { |
20
|
|
|
String serializedBody = null; |
21
|
|
|
JsonNode bodyJsonNode = null; |
22
|
|
|
|
23
|
|
|
try { |
24
|
|
|
if (body.getType() != null && !body.getType().equals(Void.TYPE)) { |
25
|
|
|
serializedBody = objectMapper.writeValueAsString(populateRequestObject(body, podamFactory)); |
26
|
|
|
bodyJsonNode = objectMapper.readTree(serializedBody); |
27
|
|
|
} |
28
|
|
|
} catch (JsonProcessingException ex) { |
29
|
|
|
log.error("Unable to write {} to json. Original error message '{}'", |
30
|
|
|
body, ex.getMessage()); |
31
|
|
|
throw new PactGenerationException("Unable to serialize body", ex); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return bodyJsonNode; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
private static Object populateRequestObject(Body body, PodamFactory podamFactory) { |
38
|
|
|
Class<?>[] types = body.getGenericArgumentTypes().toArray(new Class<?>[0]); |
39
|
|
|
|
40
|
|
|
Object manufacturedPojo = Optional.class.equals(body.getType()) |
41
|
|
|
? podamFactory.manufacturePojo(types[0]) |
42
|
|
|
: podamFactory.manufacturePojo(body.getType(), types); |
43
|
|
|
|
44
|
|
|
if (manufacturedPojo == null) { |
45
|
|
|
throw new PactGenerationException("Podam manufacturing failed"); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return manufacturedPojo; |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|