|
20 | 20 | */ |
21 | 21 | package com.inrupt.client; |
22 | 22 |
|
| 23 | +import com.inrupt.client.spi.JsonService; |
| 24 | + |
| 25 | +import java.io.ByteArrayInputStream; |
| 26 | +import java.io.IOException; |
23 | 27 | import java.net.URI; |
| 28 | +import java.util.HashMap; |
| 29 | +import java.util.Map; |
24 | 30 |
|
25 | 31 | /** |
26 | 32 | * A data class representing a structured problem description sent by the server on error response. |
@@ -75,4 +81,45 @@ public int getStatus() { |
75 | 81 | public URI getInstance() { |
76 | 82 | return this.instance; |
77 | 83 | }; |
| 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 | + } |
78 | 125 | } |
0 commit comments