-
Notifications
You must be signed in to change notification settings - Fork 8
/
OcpiResponseBody.kt
164 lines (152 loc) · 6.47 KB
/
OcpiResponseBody.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
package com.izivia.ocpi.toolkit.common
import com.fasterxml.jackson.core.JsonProcessingException
import com.izivia.ocpi.toolkit.common.validation.toReadableString
import com.izivia.ocpi.toolkit.transport.domain.HttpException
import com.izivia.ocpi.toolkit.transport.domain.HttpRequest
import com.izivia.ocpi.toolkit.transport.domain.HttpResponse
import com.izivia.ocpi.toolkit.transport.domain.HttpStatus
import org.apache.logging.log4j.LogManager
import org.valiktor.ConstraintViolationException
import java.time.Instant
/**
* When the status code is in the success range (1xxx), the data field in the response message should contain the
* information as specified in the protocol. Otherwise the data field is unspecified and may be omitted, null or
* something else that could help to debug the problem from a programmer's perspective. For example, it could specify
* which fields contain an error or are missing.
*
* The content that is sent with all the response messages is an 'application/json' type and contains a JSON object with
* the following properties:
*
* @property data Contains the actual response data object or list of objects from each request, depending on the
* cardinality of the response data, this is an array (card. * or +), or a single object (card. 1 or ?)
* @property status_code Response code, as listed in Status Codes, indicates how the request was handled. To avoid
* confusion with HTTP codes, at least four digits are used.
* @property status_message An optional status message which may help when debugging.
* @property timestamp The time this message was generated.
*/
data class OcpiResponseBody<T>(
val data: T?,
val status_code: Int,
val status_message: String?,
val timestamp: Instant
) {
companion object {
// updating this function is done only for tests
// sadly, this is not thread safe, so tests cant be run in parallel
// but reviewing the API at this time would be too cumbersome
var now: () -> Instant = { Instant.now() }
fun <T> success(data: T) = OcpiResponseBody(
data = data,
status_code = OcpiStatus.SUCCESS.code,
status_message = "Success",
timestamp = now()
)
fun <T> invalid(message: String) = OcpiResponseBody<T>(
data = null,
status_code = OcpiStatus.CLIENT_INVALID_PARAMETERS.code,
status_message = message,
timestamp = now()
)
suspend fun <T> of(data: suspend () -> T) =
try {
success(data = data())
} catch (e: ConstraintViolationException) {
invalid(message = e.toReadableString())
}
}
}
private val logger = LogManager.getLogger(OcpiResponseBody::class.java)
/**
* Generates all required headers for a paginated response from a OcpiBody with a searchResult.
* @param request the request that generated the body.
* @return Map<String, String> the headers required for pagination
*/
fun OcpiResponseBody<SearchResult<*>>.getPaginatedHeaders(request: HttpRequest): Map<String, String> =
if (data != null) {
val nextPageOffset = (data.offset + data.limit).takeIf { it <= data.totalCount }
val queries = request
.queryParams
.filter { it.key != "offset" && it.value != null }
.plus("offset" to (data.limit + data.offset))
.map { "${it.key}=${it.value}" }
.joinToString("&", "?")
listOfNotNull(
nextPageOffset?.let { "Link" to "<${request.baseUrl}${request.path}$queries>; rel=\"next\"" },
"X-Total-Count" to data.totalCount.toString(),
"X-Limit" to data.limit.toString()
).toMap()
} else {
emptyMap()
}
/**
* Transforms an OcpiException to an HttpResponse. May be used in TransportServer implementation to handle
* OCPI exceptions.
*/
fun OcpiException.toHttpResponse(): HttpResponse =
HttpResponse(
status = httpStatus,
body = mapper.writeValueAsString(
OcpiResponseBody(
data = null,
status_code = ocpiStatus.code,
status_message = message,
timestamp = Instant.now()
)
),
headers = if (httpStatus == HttpStatus.UNAUTHORIZED) mapOf("WWW-Authenticate" to "Token") else emptyMap()
)
/**
* Used to handle errors & paginated responses when handling a request. fn() should contain the code generating the
* body. If an error is caught, everything will be handled here. If it's a paginated response, it will be automatically
* be handled too.
*
* @return the HttpResponse properly formatted according to the body generated by fn()
*/
@Suppress("UNCHECKED_CAST")
suspend fun <T> HttpRequest.httpResponse(fn: suspend () -> OcpiResponseBody<T>): HttpResponse =
try {
val ocpiResponseBody = fn()
val isPaginated = ocpiResponseBody.data is SearchResult<*>
HttpResponse(
status = when (ocpiResponseBody.status_code) {
OcpiStatus.SUCCESS.code -> if (ocpiResponseBody.data != null) HttpStatus.OK else HttpStatus.NOT_FOUND
OcpiStatus.CLIENT_INVALID_PARAMETERS.code -> HttpStatus.BAD_REQUEST
else -> HttpStatus.INTERNAL_SERVER_ERROR
},
body = mapper.writeValueAsString(
if (isPaginated) {
OcpiResponseBody(
data = (ocpiResponseBody.data as SearchResult<*>?)?.list,
status_code = ocpiResponseBody.status_code,
status_message = ocpiResponseBody.status_message,
timestamp = ocpiResponseBody.timestamp
)
} else {
ocpiResponseBody
}
),
headers = getDebugHeaders()
.plus(Header.CONTENT_TYPE to ContentType.APPLICATION_JSON)
).let {
if (isPaginated) {
it.copy(
headers = (ocpiResponseBody as OcpiResponseBody<SearchResult<*>>)
.getPaginatedHeaders(request = this)
)
} else {
it
}
}
} catch (e: OcpiException) {
e.toHttpResponse()
} catch (e: HttpException) {
logger.error(e)
HttpResponse(
status = e.status
)
} catch (e: JsonProcessingException) {
logger.error(e)
HttpResponse(
status = HttpStatus.BAD_REQUEST
)
}