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.io.IOException; |
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) && !(body.getType().equals(Void.class))) { |
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
|
|
|
} catch (IOException ex) { |
33
|
|
|
log.error("Unable to convert {} to json node. Original error message '{}'", |
34
|
|
|
serializedBody, ex.getMessage()); |
35
|
|
|
throw new PactGenerationException("Unable to convert serialized body to json node", ex); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
return bodyJsonNode; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
private static Object populateRequestObject(Body body, PodamFactory podamFactory) { |
42
|
|
|
Class<?>[] types = body.getGenericArgumentTypes().toArray(new Class<?>[0]); |
43
|
|
|
Object manufacturedPojo = podamFactory.manufacturePojo(body.getType(), types); |
44
|
|
|
|
45
|
|
|
if (manufacturedPojo == null) { |
46
|
|
|
throw new PactGenerationException("Podam manufacturing failed"); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return manufacturedPojo; |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|