Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions api/src/main/java/com/inrupt/client/ClientHttpException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright Inrupt Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.inrupt.client;

/**
* A runtime exception representing an HTTP error response carrying a structured representation of the problem. The
* problem description is embedded in a {@link ProblemDetails} instance.
*/
public class ClientHttpException extends InruptClientException {
private final ProblemDetails problemDetails;

/**
* Create a ClientHttpException.
* @param problemDetails the {@link ProblemDetails} instance
* @param message the exception message
*/
public ClientHttpException(final ProblemDetails problemDetails, final String message) {
super(message);
this.problemDetails = problemDetails;
}

/**
* Create a ClientHttpException.
* @param problemDetails the {@link ProblemDetails} instance
* @param message the exception message
* @param cause a wrapped exception cause
*/
public ClientHttpException(final ProblemDetails problemDetails, final String message, final Exception cause) {
super(message, cause);
this.problemDetails = problemDetails;
}

public ProblemDetails getProblemDetails() {
return this.problemDetails;
}
}
81 changes: 81 additions & 0 deletions api/src/main/java/com/inrupt/client/HttpStatus.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright Inrupt Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.inrupt.client;

import java.util.Arrays;

public final class HttpStatus {

public static final int BAD_REQUEST = 400;
public static final int UNAUTHORIZED = 401;
public static final int FORBIDDEN = 403;
public static final int NOT_FOUND = 404;
public static final int METHOD_NOT_ALLOWED = 405;
public static final int NOT_ACCEPTABLE = 406;
public static final int CONFLICT = 409;
public static final int GONE = 410;
public static final int PRECONDITION_FAILED = 412;
public static final int UNSUPPORTED_MEDIA_TYPE = 415;
public static final int TOO_MANY_REQUESTS = 429;
public static final int INTERNAL_SERVER_ERROR = 500;

enum StatusMessages {
BAD_REQUEST(HttpStatus.BAD_REQUEST, "Bad Request"),
UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "Unauthorized"),
FORBIDDEN(HttpStatus.FORBIDDEN, "Forbidden"),
NOT_FOUND(HttpStatus.NOT_FOUND, "Not Found"),
METHOD_NOT_ALLOWED(HttpStatus.METHOD_NOT_ALLOWED, "Method Not Allowed"),
NOT_ACCEPTABLE(HttpStatus.NOT_ACCEPTABLE, "Not Acceptable"),
CONFLICT(HttpStatus.CONFLICT, "Conflict"),
GONE(HttpStatus.GONE, "Gone"),
PRECONDITION_FAILED(HttpStatus.PRECONDITION_FAILED, "Precondition Failed"),
UNSUPPORTED_MEDIA_TYPE(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type"),
TOO_MANY_REQUESTS(HttpStatus.TOO_MANY_REQUESTS, "Too Many Requests"),
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error");

private final int code;
final String message;

StatusMessages(final int code, final String message) {
this.code = code;
this.message = message;
}

static String getStatusMessage(final int statusCode) {
return Arrays.stream(StatusMessages.values())
.filter(status -> status.code == statusCode)
.findFirst()
.map(knownStatus -> knownStatus.message)
.orElseGet(() -> {
// If the status is unknown, default to 400 for client errors and 500 for server errors
if (statusCode >= 400 && statusCode <= 499) {
return BAD_REQUEST.message;
}
return INTERNAL_SERVER_ERROR.message;
});
}
}

// Prevents instantiation.
private HttpStatus() {
/* no-op */
}
}
132 changes: 132 additions & 0 deletions api/src/main/java/com/inrupt/client/ProblemDetails.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
* Copyright Inrupt Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.inrupt.client;

import com.inrupt.client.spi.JsonService;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* A data class representing a structured problem description sent by the server on error response.
*
* @see <a href="https://www.rfc-editor.org/rfc/rfc9457">RFC 9457 Problem Details for HTTP APIs</a>
*/
public class ProblemDetails {
public static final String MIME_TYPE = "application/problem+json";
public static final String DEFAULT_TYPE = "about:blank";
private final URI type;
private final String title;
private final String details;
private final int status;
private final URI instance;

public ProblemDetails(
final URI type,
final String title,
final String details,
final int status,
final URI instance
) {
// The `type` is not mandatory in RFC9457, so we want to set
// a default value here even when deserializing from JSON.
if (type != null) {
this.type = type;
} else {
this.type = URI.create(DEFAULT_TYPE);
}
this.title = title;
this.details = details;
this.status = status;
this.instance = instance;
}

public URI getType() {
return this.type;
};

public String getTitle() {
return this.title;
};

public String getDetails() {
return this.details;
};

public int getStatus() {
return this.status;
};

public URI getInstance() {
return this.instance;
};

public static ProblemDetails fromErrorResponse(
final int statusCode,
final Headers headers,
final byte[] body,
final JsonService jsonService
) {
if (jsonService == null
|| (headers != null && !headers.allValues("Content-Type").contains(ProblemDetails.MIME_TYPE))) {
return new ProblemDetails(
null,
HttpStatus.StatusMessages.getStatusMessage(statusCode),
null,
statusCode,
null
);
}
try {
// ProblemDetails doesn't have a default constructor, and we can't use JSON mapping annotations because
// the JSON service is an abstraction over JSON-B and Jackson, so we deserialize the JSON object in a Map
// and build the ProblemDetails from the Map values.
final Map<String, Object> pdData = jsonService.fromJson(
new ByteArrayInputStream(body),
new HashMap<String, Object>(){}.getClass().getGenericSuperclass()
);
final String title = Optional.ofNullable((String) pdData.get("title"))
.orElse(HttpStatus.StatusMessages.getStatusMessage(statusCode));
final String details = (String) pdData.get("details");
final URI type = Optional.ofNullable(pdData.get("type"))
.map(t -> URI.create((String) t))
.orElse(null);
final URI instance = Optional.ofNullable(pdData.get("instance"))
.map(i -> URI.create((String) i))
.orElse(null);
// Note that the status code is disregarded from the body, and reused from the HTTP response directly,
// as they must be the same as per https://www.rfc-editor.org/rfc/rfc9457.html#name-status.
return new ProblemDetails(type, title, details, statusCode, instance);
} catch (IOException e) {
return new ProblemDetails(
null,
HttpStatus.StatusMessages.getStatusMessage(statusCode),
null,
statusCode,
null
);
}
}
}
63 changes: 63 additions & 0 deletions api/src/test/java/com/inrupt/client/HttpStatusTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright Inrupt Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.inrupt.client;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class HttpStatusTest {
@Test
void checkHttpStatusSearchKnownStatus() {
assertEquals(
HttpStatus.StatusMessages.getStatusMessage(HttpStatus.NOT_FOUND),
HttpStatus.StatusMessages.NOT_FOUND.message
);
}

@Test
void checkHttpStatusSearchUnknownClientError () {
assertEquals(
HttpStatus.StatusMessages.getStatusMessage(418),
HttpStatus.StatusMessages.BAD_REQUEST.message
);
}

@Test
void checkHttpStatusSearchUnknownServerError () {
assertEquals(
HttpStatus.StatusMessages.getStatusMessage(555),
HttpStatus.StatusMessages.INTERNAL_SERVER_ERROR.message
);
assertEquals(
HttpStatus.StatusMessages.getStatusMessage(999),
HttpStatus.StatusMessages.INTERNAL_SERVER_ERROR.message
);
assertEquals(
HttpStatus.StatusMessages.getStatusMessage(-1),
HttpStatus.StatusMessages.INTERNAL_SERVER_ERROR.message
);
assertEquals(
HttpStatus.StatusMessages.getStatusMessage(15),
HttpStatus.StatusMessages.INTERNAL_SERVER_ERROR.message
);
}
}
6 changes: 6 additions & 0 deletions solid/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,12 @@
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.inrupt.client</groupId>
<artifactId>inrupt-client-jackson</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
package com.inrupt.client.solid;

import com.inrupt.client.Headers;
import com.inrupt.client.HttpStatus;
import com.inrupt.client.ProblemDetails;

import java.net.URI;

Expand All @@ -32,7 +34,7 @@
public class BadRequestException extends SolidClientException {
private static final long serialVersionUID = -3379457428921025570L;

public static final int STATUS_CODE = 400;
public static final int STATUS_CODE = HttpStatus.BAD_REQUEST;

/**
* Create a BadRequestException exception.
Expand All @@ -41,6 +43,7 @@ public class BadRequestException extends SolidClientException {
* @param uri the uri
* @param headers the response headers
* @param body the body
* @deprecated
*/
public BadRequestException(
final String message,
Expand All @@ -49,4 +52,22 @@ public BadRequestException(
final String body) {
super(message, uri, STATUS_CODE, headers, body);
}

/**
* Create a BadRequestException exception.
*
* @param message the message
* @param pd the ProblemDetails instance
* @param uri the uri
* @param headers the response headers
* @param body the body
*/
public BadRequestException(
final String message,
final ProblemDetails pd,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of these exceptions that represent HTTP error statuses now have problem details.
But there is also an exception dedicated to carrying problem details introduced above.

Would it make sense to derive these HTTP error exceptions from the new ClientHttpException?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I missed the fact that they do in fact already derive.

final URI uri,
final Headers headers,
final String body) {
super(message, pd, uri, headers, body);
}
}
Loading