diff --git a/api/src/main/java/com/inrupt/client/ClientHttpException.java b/api/src/main/java/com/inrupt/client/ClientHttpException.java new file mode 100644 index 00000000000..38313f0d465 --- /dev/null +++ b/api/src/main/java/com/inrupt/client/ClientHttpException.java @@ -0,0 +1,98 @@ +/* + * 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.net.URI; + +/** + * 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; + private final URI uri; + private final int statusCode; + private final String body; + private final transient Headers headers; + + /** + * Create a ClientHttpException. + * @param message the exception message + * @param uri the error response URI + * @param statusCode the error response status code + * @param headers the error response headers + * @param body the error response body + */ + public ClientHttpException(final String message, final URI uri, final int statusCode, + final Headers headers, final String body) { + super(message); + this.uri = uri; + this.statusCode = statusCode; + this.headers = headers; + this.body = body; + this.problemDetails = ProblemDetails.fromErrorResponse(statusCode, headers, body.getBytes()); + } + + /** + * Retrieve the URI associated with this exception. + * + * @return the uri + */ + public URI getUri() { + return uri; + } + + /** + * Retrieve the status code associated with this exception. + * + * @return the status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Retrieve the headers associated with this exception. + * + * @return the headers + */ + public Headers getHeaders() { + return headers; + } + + /** + * Retrieve the body associated with this exception. + * + * @return the body + */ + public String getBody() { + return body; + } + + /** + * Retrieve the {@link ProblemDetails} instance describing the HTTP error response. + * @return the problem details object + */ + public ProblemDetails getProblemDetails() { + return this.problemDetails; + } + +} diff --git a/api/src/main/java/com/inrupt/client/HttpStatus.java b/api/src/main/java/com/inrupt/client/HttpStatus.java new file mode 100644 index 00000000000..6d7654eeaca --- /dev/null +++ b/api/src/main/java/com/inrupt/client/HttpStatus.java @@ -0,0 +1,80 @@ +/* + * 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 "Unknown Client Error"; + } + return "Unknown Server Error"; + }); + } + } + + private HttpStatus() { + // noop + } +} diff --git a/api/src/main/java/com/inrupt/client/ProblemDetails.java b/api/src/main/java/com/inrupt/client/ProblemDetails.java new file mode 100644 index 00000000000..43215292359 --- /dev/null +++ b/api/src/main/java/com/inrupt/client/ProblemDetails.java @@ -0,0 +1,140 @@ +/* + * 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 com.inrupt.client.spi.ServiceProvider; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.URI; +import java.util.Optional; + +/** + * A data class representing a structured problem description sent by the server on error response. + * + * @see RFC 9457 Problem Details for HTTP APIs + */ +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; + private static JsonService jsonService; + private static boolean isJsonServiceInitialized; + + public ProblemDetails( + final URI type, + final String title, + final String details, + final int status, + final URI instance + ) { + this.type = 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; + }; + + private static JsonService getJsonService() { + if (ProblemDetails.isJsonServiceInitialized) { + return ProblemDetails.jsonService; + } + // It is acceptable for a JenaBodyHandlers instance to be in a classpath without any implementation for + // JsonService, in which case the ProblemDetails exceptions will fallback to default and not be parsed. + try { + ProblemDetails.jsonService = ServiceProvider.getJsonService(); + } catch (IllegalStateException e) { + ProblemDetails.jsonService = null; + } + ProblemDetails.isJsonServiceInitialized = true; + return ProblemDetails.jsonService; + } + + public static ProblemDetails fromErrorResponse( + final int statusCode, + final Headers headers, + final byte[] body + ) { + final JsonService jsonService = getJsonService(); + if (jsonService == null + || (headers != null && !headers.allValues("Content-Type").contains(ProblemDetails.MIME_TYPE))) { + return new ProblemDetails( + URI.create(ProblemDetails.DEFAULT_TYPE), + HttpStatus.StatusMessages.getStatusMessage(statusCode), + null, + statusCode, + null + ); + } + try { + final ProblemDetailsData pdData = jsonService.fromJson( + new ByteArrayInputStream(body), + ProblemDetailsData.class + ); + final URI type = Optional.ofNullable(pdData.getType()) + .orElse(URI.create(ProblemDetails.DEFAULT_TYPE)); + final String title = Optional.ofNullable(pdData.getTitle()) + .orElse(HttpStatus.StatusMessages.getStatusMessage(statusCode)); + // JSON mappers map invalid integers to 0, which is an invalid value in our case anyway. + final int status = Optional.of(pdData.getStatus()).filter(s -> s != 0).orElse(statusCode); + return new ProblemDetails( + type, + title, + pdData.getDetails(), + status, + pdData.getInstance() + ); + } catch (IOException e) { + return new ProblemDetails( + URI.create(ProblemDetails.DEFAULT_TYPE), + HttpStatus.StatusMessages.getStatusMessage(statusCode), + null, + statusCode, + null + ); + } + } +} diff --git a/api/src/main/java/com/inrupt/client/ProblemDetailsData.java b/api/src/main/java/com/inrupt/client/ProblemDetailsData.java new file mode 100644 index 00000000000..876967eb1dc --- /dev/null +++ b/api/src/main/java/com/inrupt/client/ProblemDetailsData.java @@ -0,0 +1,55 @@ +package com.inrupt.client; + +import java.net.URI; + +/** + * This package-private mutable class is used for JSON deserialization. + * Once instantiated, it is used to build an immutable {@link ProblemDetails}. + */ +class ProblemDetailsData { + private URI type; + private String title; + private String details; + private int status; + private URI 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 void setType(final URI type) { + this.type = type; + } + + public void setTitle(final String title) { + this.title = title; + } + + public void setDetails(final String details) { + this.details = details; + } + + public void setStatus(final int status) { + this.status = status; + } + + public void setInstance(final URI instance) { + this.instance = instance; + } +} diff --git a/api/src/test/java/com/inrupt/client/HttpStatusTest.java b/api/src/test/java/com/inrupt/client/HttpStatusTest.java new file mode 100644 index 00000000000..35126cb23c0 --- /dev/null +++ b/api/src/test/java/com/inrupt/client/HttpStatusTest.java @@ -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 + ); + } +} diff --git a/solid/pom.xml b/solid/pom.xml index 15163ab2e65..3be4e20184b 100644 --- a/solid/pom.xml +++ b/solid/pom.xml @@ -79,6 +79,12 @@ ${project.version} test + + com.inrupt.client + inrupt-client-jackson + ${project.version} + test + org.slf4j slf4j-api diff --git a/solid/src/main/java/com/inrupt/client/solid/BadRequestException.java b/solid/src/main/java/com/inrupt/client/solid/BadRequestException.java index 3fc0ad547f1..0f380e5632c 100644 --- a/solid/src/main/java/com/inrupt/client/solid/BadRequestException.java +++ b/solid/src/main/java/com/inrupt/client/solid/BadRequestException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,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. @@ -47,6 +48,6 @@ public BadRequestException( final URI uri, final Headers headers, final String body) { - super(message, uri, STATUS_CODE, headers, body); + super(message, uri, HttpStatus.BAD_REQUEST, headers, body); } } diff --git a/solid/src/main/java/com/inrupt/client/solid/ConflictException.java b/solid/src/main/java/com/inrupt/client/solid/ConflictException.java index d88386eb724..fe2a15385f5 100644 --- a/solid/src/main/java/com/inrupt/client/solid/ConflictException.java +++ b/solid/src/main/java/com/inrupt/client/solid/ConflictException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class ConflictException extends SolidClientException { private static final long serialVersionUID = -203198307847520748L; - public static final int STATUS_CODE = 409; + public static final int STATUS_CODE = HttpStatus.CONFLICT; /** * Create a ConflictException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/ForbiddenException.java b/solid/src/main/java/com/inrupt/client/solid/ForbiddenException.java index 7aeb3219bec..20bf1fd32dc 100644 --- a/solid/src/main/java/com/inrupt/client/solid/ForbiddenException.java +++ b/solid/src/main/java/com/inrupt/client/solid/ForbiddenException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class ForbiddenException extends SolidClientException { private static final long serialVersionUID = 3299286274724874244L; - public static final int STATUS_CODE = 403; + public static final int STATUS_CODE = HttpStatus.FORBIDDEN; /** * Create a ForbiddenException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/GoneException.java b/solid/src/main/java/com/inrupt/client/solid/GoneException.java index 0882302e27b..2d247db4c87 100644 --- a/solid/src/main/java/com/inrupt/client/solid/GoneException.java +++ b/solid/src/main/java/com/inrupt/client/solid/GoneException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class GoneException extends SolidClientException { private static final long serialVersionUID = -6892345582498100242L; - public static final int STATUS_CODE = 410; + public static final int STATUS_CODE = HttpStatus.GONE; /** * Create a GoneException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/InternalServerErrorException.java b/solid/src/main/java/com/inrupt/client/solid/InternalServerErrorException.java index ea9acb1c56e..d57ac187d86 100644 --- a/solid/src/main/java/com/inrupt/client/solid/InternalServerErrorException.java +++ b/solid/src/main/java/com/inrupt/client/solid/InternalServerErrorException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class InternalServerErrorException extends SolidClientException { private static final long serialVersionUID = -6672490715281719330L; - public static final int STATUS_CODE = 500; + public static final int STATUS_CODE = HttpStatus.INTERNAL_SERVER_ERROR; /** * Create an InternalServerErrorException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/MethodNotAllowedException.java b/solid/src/main/java/com/inrupt/client/solid/MethodNotAllowedException.java index d472b5fcbd3..dbba0b6003c 100644 --- a/solid/src/main/java/com/inrupt/client/solid/MethodNotAllowedException.java +++ b/solid/src/main/java/com/inrupt/client/solid/MethodNotAllowedException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class MethodNotAllowedException extends SolidClientException { private static final long serialVersionUID = -9125437562813923030L; - public static final int STATUS_CODE = 405; + public static final int STATUS_CODE = HttpStatus.METHOD_NOT_ALLOWED; /** * Create a MethodNotAllowedException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/NotAcceptableException.java b/solid/src/main/java/com/inrupt/client/solid/NotAcceptableException.java index 53744c0b2e8..18b7bf929e5 100644 --- a/solid/src/main/java/com/inrupt/client/solid/NotAcceptableException.java +++ b/solid/src/main/java/com/inrupt/client/solid/NotAcceptableException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class NotAcceptableException extends SolidClientException { private static final long serialVersionUID = 6594993822477388733L; - public static final int STATUS_CODE = 406; + public static final int STATUS_CODE = HttpStatus.NOT_ACCEPTABLE; /** * Create a NotAcceptableException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/NotFoundException.java b/solid/src/main/java/com/inrupt/client/solid/NotFoundException.java index 466bed74894..f0cf9ef7164 100644 --- a/solid/src/main/java/com/inrupt/client/solid/NotFoundException.java +++ b/solid/src/main/java/com/inrupt/client/solid/NotFoundException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class NotFoundException extends SolidClientException { private static final long serialVersionUID = -2256628528500739683L; - public static final int STATUS_CODE = 404; + public static final int STATUS_CODE = HttpStatus.NOT_FOUND; /** * Create a NotFoundException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/PreconditionFailedException.java b/solid/src/main/java/com/inrupt/client/solid/PreconditionFailedException.java index 461c937a0eb..4584bac47b9 100644 --- a/solid/src/main/java/com/inrupt/client/solid/PreconditionFailedException.java +++ b/solid/src/main/java/com/inrupt/client/solid/PreconditionFailedException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class PreconditionFailedException extends SolidClientException { private static final long serialVersionUID = 4205761003697773528L; - public static final int STATUS_CODE = 412; + public static final int STATUS_CODE = HttpStatus.PRECONDITION_FAILED; /** * Create a PreconditionFailedException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/SolidClientException.java b/solid/src/main/java/com/inrupt/client/solid/SolidClientException.java index 668df265d3d..bf6decd11ee 100644 --- a/solid/src/main/java/com/inrupt/client/solid/SolidClientException.java +++ b/solid/src/main/java/com/inrupt/client/solid/SolidClientException.java @@ -20,23 +20,18 @@ */ package com.inrupt.client.solid; +import com.inrupt.client.ClientHttpException; import com.inrupt.client.Headers; -import com.inrupt.client.InruptClientException; import java.net.URI; /** * A runtime exception for use with SolidClient HTTP operations. */ -public class SolidClientException extends InruptClientException { +public class SolidClientException extends ClientHttpException { private static final long serialVersionUID = 2868432164225689934L; - private final URI uri; - private final int statusCode; - private final String body; - private final transient Headers headers; - /** * Create a SolidClient exception. * @@ -48,49 +43,18 @@ public class SolidClientException extends InruptClientException { */ public SolidClientException(final String message, final URI uri, final int statusCode, final Headers headers, final String body) { - super(message); - this.uri = uri; - this.statusCode = statusCode; - this.headers = headers; - this.body = body; - } - - /** - * Retrieve the URI associated with this exception. - * - * @return the uri - */ - public URI getUri() { - return uri; - } - - /** - * Retrieve the status code associated with this exception. - * - * @return the status code - */ - public int getStatusCode() { - return statusCode; + super(message, uri, statusCode, headers, body); } /** - * Retrieve the headers associated with this exception. * - * @return the headers + * @param message the resulting exception message + * @param uri the request URL + * @param statusCode the response status code + * @param headers the response {@link Headers} + * @param body the response body + * @return an appropriate exception based on the status code. */ - public Headers getHeaders() { - return headers; - } - - /** - * Retrieve the body associated with this exception. - * - * @return the body - */ - public String getBody() { - return body; - } - public static SolidClientException handle( final String message, final URI uri, diff --git a/solid/src/main/java/com/inrupt/client/solid/TooManyRequestsException.java b/solid/src/main/java/com/inrupt/client/solid/TooManyRequestsException.java index 4f299fc9492..018a95e1e8f 100644 --- a/solid/src/main/java/com/inrupt/client/solid/TooManyRequestsException.java +++ b/solid/src/main/java/com/inrupt/client/solid/TooManyRequestsException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class TooManyRequestsException extends SolidClientException { private static final long serialVersionUID = -1798491190232642824L; - public static final int STATUS_CODE = 429; + public static final int STATUS_CODE = HttpStatus.TOO_MANY_REQUESTS; /** * Create a TooManyRequestsException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/UnauthorizedException.java b/solid/src/main/java/com/inrupt/client/solid/UnauthorizedException.java index db8615df958..7ad2d425137 100644 --- a/solid/src/main/java/com/inrupt/client/solid/UnauthorizedException.java +++ b/solid/src/main/java/com/inrupt/client/solid/UnauthorizedException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class UnauthorizedException extends SolidClientException { private static final long serialVersionUID = -3219668517323678497L; - public static final int STATUS_CODE = 401; + public static final int STATUS_CODE = HttpStatus.UNAUTHORIZED; /** * Create an UnauthorizedException exception. diff --git a/solid/src/main/java/com/inrupt/client/solid/UnsupportedMediaTypeException.java b/solid/src/main/java/com/inrupt/client/solid/UnsupportedMediaTypeException.java index 27e9c96953d..866fe70cf7d 100644 --- a/solid/src/main/java/com/inrupt/client/solid/UnsupportedMediaTypeException.java +++ b/solid/src/main/java/com/inrupt/client/solid/UnsupportedMediaTypeException.java @@ -21,6 +21,7 @@ package com.inrupt.client.solid; import com.inrupt.client.Headers; +import com.inrupt.client.HttpStatus; import java.net.URI; @@ -32,7 +33,7 @@ public class UnsupportedMediaTypeException extends SolidClientException { private static final long serialVersionUID = 1312856145838280673L; - public static final int STATUS_CODE = 415; + public static final int STATUS_CODE = HttpStatus.UNSUPPORTED_MEDIA_TYPE; /** * Create an UnsupportedMediaTypeException exception. diff --git a/solid/src/test/java/com/inrupt/client/solid/ProblemDetailsTest.java b/solid/src/test/java/com/inrupt/client/solid/ProblemDetailsTest.java new file mode 100644 index 00000000000..227ea50d4ae --- /dev/null +++ b/solid/src/test/java/com/inrupt/client/solid/ProblemDetailsTest.java @@ -0,0 +1,154 @@ +/* + * 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.solid; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import com.inrupt.client.Headers; +import com.inrupt.client.ProblemDetails; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +// Ideally, this class should be in the api module, but it creates +// a circular dependency with the JSON module implementation. +public class ProblemDetailsTest { + Headers mockProblemDetailsHeader() { + final List headerValues = new ArrayList<>(); + headerValues.add("application/problem+json"); + final Map> headerMap = new HashMap<>(); + headerMap.put("Content-Type", headerValues); + return Headers.of(headerMap); + } + + @Test + void testEmptyProblemDetails() { + final int statusCode = 400; + final ProblemDetails pd = ProblemDetails.fromErrorResponse( + statusCode, + mockProblemDetailsHeader(), + "{}".getBytes() + ); + assertEquals(ProblemDetails.DEFAULT_TYPE, pd.getType().toString()); + assertEquals(statusCode, pd.getStatus()); + Assertions.assertEquals("Bad Request", pd.getTitle()); + assertNull(pd.getDetails()); + assertNull(pd.getInstance()); + } + @Test + void testCompleteProblemDetails() { + final int statusCode = 400; + final ProblemDetails pd = ProblemDetails.fromErrorResponse( + statusCode, + mockProblemDetailsHeader(), + ("{" + + "\"title\":\"Some title\"," + + "\"status\":400," + + "\"details\":\"Some details\"," + + "\"instance\":\"https://example.org/instance\"," + + "\"type\":\"https://example.org/type\"" + + "}").getBytes() + ); + assertEquals("https://example.org/type", pd.getType().toString()); + assertEquals(statusCode, pd.getStatus()); + Assertions.assertEquals("Some title", pd.getTitle()); + assertEquals("Some details", pd.getDetails()); + assertEquals("https://example.org/instance", pd.getInstance().toString()); + } + + @Test + void testIgnoreUnknownProblemDetails() { + final int statusCode = 400; + final ProblemDetails pd = ProblemDetails.fromErrorResponse( + statusCode, + mockProblemDetailsHeader(), + ("{" + + "\"title\":\"Some title\"," + + "\"status\":400," + + "\"details\":\"Some details\"," + + "\"instance\":\"https://example.org/instance\"," + + "\"type\":\"https://example.org/type\"," + + "\"unknown\":\"Some unknown property\"" + + "}").getBytes() + ); + assertEquals("https://example.org/type", pd.getType().toString()); + assertEquals(statusCode, pd.getStatus()); + Assertions.assertEquals("Some title", pd.getTitle()); + assertEquals("Some details", pd.getDetails()); + assertEquals("https://example.org/instance", pd.getInstance().toString()); + } + + @Test + void testInvalidStatusProblemDetails() { + final int statusCode = 400; + final ProblemDetails pd = ProblemDetails.fromErrorResponse( + statusCode, + mockProblemDetailsHeader(), + ("{" + + "\"status\":\"Some invalid status\"" + + "}").getBytes() + ); + assertEquals(statusCode, pd.getStatus()); + } + + @Test + void testMismatchingStatusProblemDetails() { + final int statusCode = 400; + final ProblemDetails pd = ProblemDetails.fromErrorResponse( + statusCode, + mockProblemDetailsHeader(), + ("{" + + "\"status\":500" + + "}").getBytes() + ); + assertEquals(500, pd.getStatus()); + } + + @Test + void testInvalidTypeProblemDetails() { + final ProblemDetails pd = ProblemDetails.fromErrorResponse( + 400, + mockProblemDetailsHeader(), + ("{" + + "\"type\":\"Some invalid type\"" + + "}").getBytes() + ); + assertEquals(ProblemDetails.DEFAULT_TYPE, pd.getType().toString()); + } + + @Test + void testInvalidInstanceProblemDetails() { + final ProblemDetails pd = ProblemDetails.fromErrorResponse( + 400, + mockProblemDetailsHeader(), + ("{" + + "\"instance\":\"Some invalid instance\"" + + "}").getBytes() + ); + assertNull(pd.getInstance()); + } +} diff --git a/solid/src/test/java/com/inrupt/client/solid/SolidExceptionTest.java b/solid/src/test/java/com/inrupt/client/solid/SolidExceptionTest.java index 15220345d68..147b48fb094 100644 --- a/solid/src/test/java/com/inrupt/client/solid/SolidExceptionTest.java +++ b/solid/src/test/java/com/inrupt/client/solid/SolidExceptionTest.java @@ -22,6 +22,8 @@ import static org.junit.jupiter.api.Assertions.*; +import java.net.URI; + import org.junit.jupiter.api.Test; class SolidExceptionTest { @@ -41,4 +43,14 @@ void checkSolidWrappedException() { assertEquals(upstream, err.getCause()); assertEquals(msg, err.getMessage()); } + + @Test + void checkSolidClientException() { + final String msg = "Error"; + final SolidClientException err = new SolidClientException( + msg, URI.create("https://example.org/request"), 123, null, "some body" + ); + assertEquals(msg, err.getMessage()); + assertEquals(123, err.getProblemDetails().getStatus()); + } }