Skip to content

Commit 93c3d38

Browse files
committed
Add specialized builder to ProblemDetails
1 parent f72eb30 commit 93c3d38

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

api/src/main/java/com/inrupt/client/ProblemDetails.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,13 @@
2020
*/
2121
package com.inrupt.client;
2222

23+
import com.inrupt.client.spi.JsonService;
24+
25+
import java.io.ByteArrayInputStream;
26+
import java.io.IOException;
2327
import java.net.URI;
28+
import java.util.HashMap;
29+
import java.util.Map;
2430

2531
/**
2632
* A data class representing a structured problem description sent by the server on error response.
@@ -75,4 +81,45 @@ public int getStatus() {
7581
public URI getInstance() {
7682
return this.instance;
7783
};
84+
85+
public static ProblemDetails fromErrorResponse(
86+
final int statusCode,
87+
final Headers headers,
88+
final byte[] body,
89+
final JsonService jsonService
90+
) {
91+
if (jsonService == null
92+
|| (headers != null && !headers.allValues("Content-Type").contains(ProblemDetails.MIME_TYPE))) {
93+
return new ProblemDetails(
94+
null,
95+
HttpStatus.StatusMessages.getStatusMessage(statusCode),
96+
null,
97+
statusCode,
98+
null
99+
);
100+
}
101+
try {
102+
// ProblemDetails doesn't have a default constructor, and we can't use JSON mapping annotations because
103+
// the JSON service is an abstraction over JSON-B and Jackson, so we deserialize the JSON object in a Map
104+
// and build the ProblemDetails from the Map values.
105+
final Map<String, Object> pdData = jsonService.fromJson(
106+
new ByteArrayInputStream(body),
107+
new HashMap<String, Object>(){}.getClass().getGenericSuperclass()
108+
);
109+
final String title = (String) pdData.get("title");
110+
final String details = (String) pdData.get("details");
111+
final URI type = URI.create((String) pdData.get("type"));
112+
final URI instance = URI.create((String) pdData.get("instance"));
113+
final int status = (int) pdData.get("status");
114+
return new ProblemDetails(type, title, details, status, instance);
115+
} catch (IOException e) {
116+
return new ProblemDetails(
117+
null,
118+
HttpStatus.StatusMessages.getStatusMessage(statusCode),
119+
null,
120+
statusCode,
121+
null
122+
);
123+
}
124+
}
78125
}

0 commit comments

Comments
 (0)