Skip to content

Commit c7afad3

Browse files
committed
refactor(worker): minor improvements
1 parent a00eb81 commit c7afad3

File tree

3 files changed

+47
-58
lines changed

3 files changed

+47
-58
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ Example BPMN with service task:
2929
* `url` - the url to invoke
3030
* optional custom headers:
3131
* `method` - the HTTP method to use (default: `GET`, allowed: `post` | `get` | `put` | `delete` | `patch`)
32+
* `contentType` - the type of the request body (default: `application/json`, allowed: any valid HTTP content type)
33+
* `accept` - the type of the response body that is accepted (default: `application/json`, allowed: `application/json`, `text/plain`)
3234
* `statusCodeCompletion` - Status codes that lead to completion of the service task (default: `1xx,2xx`, allowed: comma separated list of codes including 1xx, 2xx, 3xx, 4xx and 5xx)
3335
* `statusCodeFailure` - Status codes that lead to the job failing (default: `3xx,4xx,5xx`, allowed: comma separated list of codes including 1xx, 2xx, 3xx, 4xx and 5xx)
3436
* `errorCodePath` - path expression (dot notation) to extract the error code of a failed response body (e.g. `error.code`). If the error code is present then a BPMN error is thrown with this code instead of failing the job. Otherwise, that leads to the job failing.

src/main/java/io/zeebe/http/HttpJobHandler.java

Lines changed: 33 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -127,54 +127,48 @@ private HttpRequest buildRequest(ConfigurationMaps configurationMaps) {
127127
final String method = getMethod(configurationMaps);
128128
final HttpRequest.BodyPublisher bodyPublisher = getBodyPublisher(configurationMaps);
129129

130+
final var contentType = getContentType(configurationMaps).orElse("application/json");
131+
final var accept = getAccept(configurationMaps).orElse("application/json");
132+
130133
final HttpRequest.Builder builder =
131134
HttpRequest.newBuilder()
132135
.uri(URI.create(url))
133136
.timeout(CONNECTION_TIMEOUT)
137+
.header("Content-Type", contentType)
138+
.header("Accept", accept)
134139
.method(method, bodyPublisher);
135140

136141
getAuthorization(configurationMaps).ifPresent(auth -> builder.header("Authorization", auth));
137142

138-
// if no accept or content type header then default to json
139-
getContentType(configurationMaps)
140-
.ifPresentOrElse(contentType -> builder.header("Content-Type", contentType),
141-
() -> builder.header("Content-Type", "application/json"));
142-
getAccept(configurationMaps)
143-
.ifPresentOrElse(accept -> builder.header("Accept", accept),
144-
() -> builder.header("Accept", "application/json"));
145-
146143
return builder.build();
147144
}
148145

149-
private String getUrl(ConfigurationMaps configMaps) {
146+
private Optional<String> getConfig(final ConfigurationMaps configMaps,
147+
final String parameterUrl) {
150148
return configMaps
151-
.getString(PARAMETER_URL)
152-
.map(url -> placeholderProcessor.process(url, configMaps.getConfig()))
149+
.getString(parameterUrl)
150+
.map(url -> placeholderProcessor.process(url, configMaps.getConfig()));
151+
}
152+
153+
private String getUrl(ConfigurationMaps configMaps) {
154+
return getConfig(configMaps, PARAMETER_URL)
153155
.orElseThrow(() -> new RuntimeException("Missing required parameter: " + PARAMETER_URL));
154156
}
155157

156158
private Optional<String> getAuthorization(ConfigurationMaps configMaps) {
157-
return configMaps
158-
.getString(PARAMETER_AUTHORIZATION)
159-
.map(auth -> placeholderProcessor.process(auth, configMaps.getConfig()));
159+
return getConfig(configMaps, PARAMETER_AUTHORIZATION);
160160
}
161161

162162
private Optional<String> getContentType(ConfigurationMaps configMaps) {
163-
return configMaps
164-
.getString(PARAMETER_CONTENT_TYPE)
165-
.map(contentType -> placeholderProcessor.process(contentType, configMaps.getConfig()));
163+
return getConfig(configMaps, PARAMETER_CONTENT_TYPE);
166164
}
167165

168166
private Optional<String> getAccept(ConfigurationMaps configMaps) {
169-
return configMaps
170-
.getString(PARAMETER_ACCEPT)
171-
.map(accept -> placeholderProcessor.process(accept, configMaps.getConfig()));
167+
return getConfig(configMaps, PARAMETER_ACCEPT);
172168
}
173169

174170
private String getMethod(ConfigurationMaps configMaps) {
175-
return configMaps
176-
.getString(PARAMETER_METHOD)
177-
.map(method -> placeholderProcessor.process(method, configMaps.getConfig()))
171+
return getConfig(configMaps, PARAMETER_METHOD)
178172
.map(String::toUpperCase)
179173
.orElse("GET");
180174
}
@@ -222,36 +216,27 @@ private boolean checkIfCodeMatches(String statusCode, String matchCodePattern) {
222216
|| (statusCode.startsWith("5") && matchCodePattern.contains("5xx"));
223217
}
224218

225-
private Map<String, Object> processResponse(ActivatedJob job,
226-
HttpResponse<String> response, HttpRequest request) {
219+
private Map<String, Object> processResponse(ActivatedJob job,
220+
HttpResponse<String> response, HttpRequest request) {
221+
227222
final Map<String, Object> result = new java.util.HashMap<>();
228223
int statusCode = response.statusCode();
229224
result.put("statusCode", statusCode);
230-
Optional<String> respBody = Optional.ofNullable(response.body())
231-
.filter(body -> !body.isEmpty());
232-
String acceptValue = request.headers().firstValue("Accept").orElse(null);
233-
// If accepting plain text
234-
if (hasContentTypeHeader(response.headers(), "text/plain") &&
235-
("text/plain".equals(acceptValue))) {
236-
respBody.ifPresent(body -> result.put("body", body));
237-
} else {
238-
// Assuming json by default
239-
respBody.map(this::bodyToObject)
225+
226+
Optional.ofNullable(response.body())
227+
.filter(body -> !body.isEmpty())
228+
.map(body -> {
229+
if (request.headers().allValues("Accept").contains("text/plain") &&
230+
response.headers().allValues("Content-Type").contains("text/plain")
231+
) {
232+
return body;
233+
} else {
234+
return bodyToObject(body);
235+
}
236+
})
240237
.ifPresent(body -> result.put("body", body));
241-
}
242-
return result;
243-
}
244238

245-
private boolean hasContentTypeHeader(HttpHeaders headers, String contentTypeHeader) {
246-
boolean hasContentTypeHeader = false;
247-
try {
248-
hasContentTypeHeader = Optional.ofNullable(headers.firstValue("Content-Type"))
249-
.filter(contentType -> contentType.get().contains(contentTypeHeader))
250-
.isPresent();
251-
}catch(Exception e) {
252-
System.out.println(e.toString());
253-
}
254-
return hasContentTypeHeader;
239+
return result;
255240
}
256241

257242
private Object bodyToObject(String body) {

src/test/java/io/zeebe/http/ProcessIntegrationTest.java

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -131,26 +131,28 @@ public void testGetAcceptPlainTextResponse() {
131131
}
132132

133133
@Test
134-
public void failsIfDoesNotAcceptResponseType() {
134+
public void testPostContentTypePlainText() {
135135
stubFor(
136136
post(urlEqualTo("/api"))
137-
.willReturn(aResponse().withHeader("Content-Type", "text/plain")
138-
.withBody("This is text")));
137+
.willReturn(aResponse().withStatus(200)));
139138

140139
final var processInstance =
141140
createInstance(
142141
serviceTask ->
143142
serviceTask
144143
.zeebeTaskHeader("url", WIRE_MOCK_RULE.baseUrl() + "/api")
145-
.zeebeTaskHeader("method", "POST"));
144+
.zeebeTaskHeader("method", "POST")
145+
.zeebeTaskHeader("contentType", "text/plain"),
146+
Map.of("body", "This is text"));
146147

147-
final var recorderJob =
148-
RecordingExporter.jobRecords(JobIntent.FAILED)
149-
.withProcessInstanceKey(processInstance.getProcessInstanceKey())
150-
.getFirst();
148+
ZeebeTestRule.assertThat(processInstance)
149+
.isEnded()
150+
.hasVariable("statusCode", 200);
151151

152-
assertThat(recorderJob.getValue().getErrorMessage()).isNotNull()
153-
.contains("Failed to deserialize response body from JSON");
152+
WIRE_MOCK_RULE.verify(
153+
postRequestedFor(urlEqualTo("/api"))
154+
.withHeader("Content-Type", equalTo("text/plain"))
155+
.withRequestBody(equalTo("This is text")));
154156
}
155157

156158
@Test

0 commit comments

Comments
 (0)