Skip to content

Commit 0523b19

Browse files
committed
#49 - When no bodyAdapter is set, use a reasonable default if avaje-jsonb or jackson is detected
1 parent 4ff1bca commit 0523b19

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

client/src/main/java/io/avaje/http/client/DHttpClientContextBuilder.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,9 @@ public HttpClientContext build() {
159159
// register the builtin request/response logging
160160
requestListener(new RequestLogger());
161161
}
162+
if (bodyAdapter == null) {
163+
bodyAdapter = defaultBodyAdapter();
164+
}
162165
return new DHttpClientContext(client, baseUrl, requestTimeout, bodyAdapter, retryHandler, buildListener(), authTokenProvider, buildIntercept());
163166
}
164167

@@ -213,4 +216,35 @@ private HttpClient defaultClient() {
213216
return builder.build();
214217
}
215218

219+
/**
220+
* Create a reasonable default BodyAdapter if avaje-jsonb or Jackson are present.
221+
*/
222+
BodyAdapter defaultBodyAdapter() {
223+
try {
224+
return detectJsonb() ? new JsonbBodyAdapter()
225+
: detectJackson() ? new JacksonBodyAdapter()
226+
: null;
227+
} catch (IllegalAccessError e) {
228+
// not in module path
229+
return null;
230+
}
231+
}
232+
233+
boolean detectJsonb() {
234+
return detectTypeExists("io.avaje.jsonb.Jsonb");
235+
}
236+
237+
boolean detectJackson() {
238+
return detectTypeExists("com.fasterxml.jackson.databind.ObjectMapper");
239+
}
240+
241+
private boolean detectTypeExists(String className) {
242+
try {
243+
Class.forName(className);
244+
return true;
245+
} catch (ClassNotFoundException e) {
246+
return false;
247+
}
248+
}
249+
216250
}

0 commit comments

Comments
 (0)