Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
490a1f3
Data classes for HTTP Problem Details support
NSeydoux Apr 4, 2024
1147b3b
Use typed JSON deserialization
NSeydoux Apr 15, 2024
050f4a6
Move JSON service discovery in ProblemDetails²
NSeydoux Apr 15, 2024
374880e
Make JSON service singleton
NSeydoux Apr 15, 2024
914c153
fixup! Move JSON service discovery in ProblemDetails²
NSeydoux Apr 15, 2024
f753ff2
Change default ProblemDetails titles
NSeydoux Apr 15, 2024
67f6124
Fix ProblemDetails parsing tests
NSeydoux Apr 15, 2024
766eb95
Lift SolidClientExceptions members to parent
NSeydoux Apr 16, 2024
9cbf5e3
Fix typo in default HTTP status
NSeydoux Apr 16, 2024
ba883b7
Lint
NSeydoux Apr 16, 2024
17b8ce2
Refactor specialized exception constructors
NSeydoux Apr 10, 2024
6c8c766
fixup! Change default ProblemDetails titles
NSeydoux Apr 16, 2024
97f39c7
Remove default ProblemDetails title
NSeydoux Apr 16, 2024
662ad83
fixup! Remove default ProblemDetails title
NSeydoux Apr 16, 2024
540fe12
fixup! fixup! Remove default ProblemDetails title
NSeydoux Apr 16, 2024
2452b49
fixup! fixup! fixup! Remove default ProblemDetails title
NSeydoux Apr 16, 2024
80be1ac
Replace ProblemDetailsData with private setters
NSeydoux Apr 16, 2024
ca829b2
Revert "Replace ProblemDetailsData w prv. setters"
NSeydoux Apr 16, 2024
1832898
Make data class public
NSeydoux Apr 16, 2024
4638882
Add body handler to throw on HTTP error
NSeydoux Apr 16, 2024
6412895
fixup! Add body handler to throw on HTTP error
NSeydoux Apr 16, 2024
71d6302
Lint
NSeydoux Apr 16, 2024
d75f6e5
fixup! fixup! Add body handler to throw on HTTP error
NSeydoux Apr 16, 2024
d91de68
Rephrase comment
NSeydoux Apr 16, 2024
600bfdc
fixup! fixup! fixup! Remove default ProblemDetails title
NSeydoux Apr 16, 2024
5a1bd37
Add exception mapper to throwing body handler
NSeydoux Apr 17, 2024
aff5c70
Add Javadoc to inner ProblemDetails.Data class
NSeydoux Apr 17, 2024
3a5f981
Remove response URI from exception message
NSeydoux Apr 17, 2024
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
98 changes: 98 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,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;
}

}
149 changes: 149 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,149 @@
/*
* 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 <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;
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;
};

/**
* This inner class is only ever used for JSON deserialization. Please do not use in any other context.
*/
public static class Data {
public URI type;
public String title;
public String details;
public int status;
public URI instance;
}

private static JsonService getJsonService() {
Copy link
Contributor

Choose a reason for hiding this comment

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

This (and its two fields) might be simplified using an Optional field.

If the field is nut null then return its value (which might be null).
Otherwise try to get a service and set the field to an Optional.ofNullable with the service as value.

Might be nicer or not, I don't really know.
This looks OK otherwise.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I thought it would be nicer, but after having implemented some of it, it looks quite the same. One of my assumptions which causes the code to look like what it does here is that the SPI lookup is a relatively expensive operation that you only want to do once, so I want to have a clear separation between "this is null because we haven't initialized it" and "this is null because the lookup failed", so that I don't do a systematic lookup in the latter case assuming we might be in the former.

If I have understood what you are describing correctly, having the Optional doesn't change much to the overall structure, in particular because a lookup failure results in an exception, and not in null, so the try/catch needs to be there even when initializing the Optional (I think)

if (ProblemDetails.isJsonServiceInitialized) {
return ProblemDetails.jsonService;
}
// It is a legitimate use case that this is loaded in a context where no implementation of the JSON service is
// available. On SPI lookup failure, the ProblemDetails exceptions will fall back 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),
null,
null,
statusCode,
null
);
}
try {
final Data pdData = jsonService.fromJson(
new ByteArrayInputStream(body),
Data.class
);
final URI type = Optional.ofNullable(pdData.type)
.orElse(URI.create(ProblemDetails.DEFAULT_TYPE));
// JSON mappers map invalid integers to 0, which is an invalid value in our case anyway.
final int status = Optional.of(pdData.status).filter(s -> s != 0).orElse(statusCode);
return new ProblemDetails(
type,
pdData.title,
pdData.details,
status,
pdData.instance
);
} catch (IOException e) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Any chance we have a more specific exception for JSON parsing errors?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Unfortunately no, more specific exceptions are Jackson or JSON-B specific. Our abstraction layer doesn't define a specific exception beyond IOException (it might be a future improvement though, in the spirit of the ClientHttpException)

return new ProblemDetails(
URI.create(ProblemDetails.DEFAULT_TYPE),
null,
null,
statusCode,
null
);
}
}
}
47 changes: 47 additions & 0 deletions api/src/main/java/com/inrupt/client/Response.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import java.io.InputStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;

/**
* An HTTP Response.
Expand Down Expand Up @@ -152,6 +154,51 @@ public static BodyHandler<Void> discarding() {
return responseInfo -> null;
}

/**
* Throws on HTTP error using the provided mapper, or apply the provided body handler.
* @param handler the body handler to apply on non-error HTTP responses
* @param isSuccess a callback determining error cases
* @param exceptionMapper the exception mapper
* @return the body handler
* @param <T> the type of the body handler
*/
public static <T> Response.BodyHandler<T> throwOnError(
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This body handler can be used in the solid module, where we already have a specific mapping from HTTP errors to exceptions

final Response.BodyHandler<T> handler,
final Function<Response.ResponseInfo, Boolean> isSuccess,
final Function<Response.ResponseInfo, ClientHttpException> exceptionMapper
) {
return responseinfo -> {
if (!isSuccess.apply(responseinfo)) {
throw exceptionMapper.apply(responseinfo);
}
return handler.apply(responseinfo);
};
}

/**
* Throws on HTTP error, or apply the provided body handler.
* @param handler the body handler to apply on non-error HTTP responses
* @param isSuccess a callback determining error cases
* @return the body handler
* @param <T> the type of the body handler
*/
public static <T> Response.BodyHandler<T> throwOnError(
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This handler can be used in the jena and rdf4j modules, where we want to throw a generic HTTP exception.

final Response.BodyHandler<T> handler,
final Function<Response.ResponseInfo, Boolean> isSuccess
) {
final Function<Response.ResponseInfo, ClientHttpException> defaultMapper = responseInfo ->
new ClientHttpException(
"An HTTP error has been returned, with status code " + responseInfo.statusCode(),
responseInfo.uri(),
responseInfo.statusCode(),
responseInfo.headers(),
new String(responseInfo.body().array(), StandardCharsets.UTF_8)
);
return throwOnError(handler, isSuccess, defaultMapper);
}



private BodyHandlers() {
// Prevent instantiation
}
Expand Down
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
Loading