Skip to content

Commit ce59b5f

Browse files
committed
Add exception handling
1 parent e22aa5e commit ce59b5f

File tree

7 files changed

+209
-2
lines changed

7 files changed

+209
-2
lines changed

.checkstyle

+1
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@
66
</local-check-config>
77
<fileset name="all" enabled="true" check-config-name="Shibboleth" local="true">
88
<file-match-pattern match-pattern="^src/main/java/" include-pattern="true"/>
9+
<file-match-pattern match-pattern="ValidatorsApi.java" include-pattern="false"/>
910
</fileset>
1011
</fileset-config>

.springBeans

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<beansProjectDescription>
3+
<version>1</version>
4+
<pluginVersion><![CDATA[3.9.4.201804120850-RELEASE]]></pluginVersion>
5+
<configSuffixes>
6+
<configSuffix><![CDATA[xml]]></configSuffix>
7+
</configSuffixes>
8+
<enableImports><![CDATA[false]]></enableImports>
9+
<configs>
10+
</configs>
11+
<autoconfigs>
12+
</autoconfigs>
13+
<configSets>
14+
</configSets>
15+
</beansProjectDescription>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package uk.org.iay.incommon.validator.api;
16+
17+
import java.util.HashMap;
18+
import java.util.Map;
19+
20+
import org.joda.time.DateTime;
21+
import org.springframework.http.HttpStatus;
22+
23+
/**
24+
* Exception class for use within the API.
25+
*/
26+
public class ApiException extends Exception {
27+
28+
/** Serial version UID. */
29+
private static final long serialVersionUID = -5046975083822313941L;
30+
31+
/** HTTP Status to be reported by this exception. */
32+
private final HttpStatus status;
33+
34+
/** When the exception was created. */
35+
private final DateTime when;
36+
37+
/**
38+
* Constructor.
39+
*
40+
* @param stat HTTP status
41+
* @param msg message
42+
*/
43+
public ApiException(final HttpStatus stat, final String msg) {
44+
super(msg);
45+
status = stat;
46+
when = DateTime.now();
47+
}
48+
49+
/**
50+
* Reuturns the wrapped {@link HttpStatus} value.
51+
*
52+
* @return an {@link HttpStatus}
53+
*/
54+
public HttpStatus getStatus() {
55+
return status;
56+
}
57+
58+
/**
59+
* Convert to a {@link Map} so that the data can be turned into
60+
* a JSON response.
61+
*
62+
* @return a new {@link Map} containing the exception information
63+
*/
64+
public Map<String, Object> toMap() {
65+
final Map<String, Object> m = new HashMap<>();
66+
m.put("status", Integer.valueOf(getStatus().value()));
67+
m.put("error", getStatus().getReasonPhrase());
68+
m.put("message", getMessage());
69+
m.put("exception", getClass().getName());
70+
m.put("timestamp", when);
71+
return m;
72+
}
73+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package uk.org.iay.incommon.validator.api;
16+
17+
import org.springframework.http.HttpStatus;
18+
19+
/**
20+
* {@link ApiException} representing a "not found" condition.
21+
*/
22+
public class NotFoundException extends ApiException {
23+
24+
/** Serial version UID. */
25+
private static final long serialVersionUID = 424520235843161978L;
26+
27+
/**
28+
* Constructor.
29+
*
30+
* @param msg message to be included in the exception
31+
*/
32+
public NotFoundException(final String msg) {
33+
super(HttpStatus.NOT_FOUND, msg);
34+
}
35+
36+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* NOTE: This class is auto generated by the swagger code generator program (2.3.1).
3+
* https://github.com/swagger-api/swagger-codegen
4+
* Do not edit the class manually.
5+
*
6+
* **IAY**: The only changes here from the generated file have been to clean up the imports
7+
* list and to add "throws ApiException" to the validate method.
8+
*/
9+
package uk.org.iay.incommon.validator.api;
10+
11+
import java.util.List;
12+
13+
import javax.validation.Valid;
14+
15+
import org.springframework.http.ResponseEntity;
16+
import org.springframework.web.bind.annotation.PathVariable;
17+
import org.springframework.web.bind.annotation.RequestBody;
18+
import org.springframework.web.bind.annotation.RequestMapping;
19+
import org.springframework.web.bind.annotation.RequestMethod;
20+
21+
import io.swagger.annotations.Api;
22+
import io.swagger.annotations.ApiOperation;
23+
import io.swagger.annotations.ApiParam;
24+
import io.swagger.annotations.ApiResponse;
25+
import io.swagger.annotations.ApiResponses;
26+
import uk.org.iay.incommon.validator.models.Status;
27+
import uk.org.iay.incommon.validator.models.Validator;
28+
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-05-12T13:33:10.546+01:00")
29+
30+
@Api(value = "validators", description = "the validators API")
31+
public interface ValidatorsApi {
32+
33+
@ApiOperation(value = "lists available validators", nickname = "getValidators", notes = "Lists all of the available validator pipelines. ", response = Validator.class, responseContainer = "List", tags={ "validation", })
34+
@ApiResponses(value = {
35+
@ApiResponse(code = 200, message = "list of validator identifiers and descriptions", response = Validator.class, responseContainer = "List") })
36+
@RequestMapping(value = "/validators",
37+
produces = { "application/json" },
38+
method = RequestMethod.GET)
39+
ResponseEntity<List<Validator>> getValidators();
40+
41+
42+
@ApiOperation(value = "performs a validation", nickname = "validate", notes = "", response = Status.class, responseContainer = "List", tags={ "validation", })
43+
@ApiResponses(value = {
44+
@ApiResponse(code = 200, message = "The result of a validation operation is a (possibly empty) array of `Status` objects derived from the `StatusMetadata` instances attached to the item being validated. These may include errors, and it is up to the client to determine what constitues a \"pass\" or \"fail\". ", response = Status.class, responseContainer = "List") })
45+
@RequestMapping(value = "/validators/{validator_id}/validate",
46+
produces = { "application/json" },
47+
consumes = { "application/xml+samlmetadata" },
48+
method = RequestMethod.POST)
49+
ResponseEntity<List<Status>> validate(@ApiParam(value = "An identifier for the validation to be performed. ",required=true) @PathVariable("validator_id") String validatorId,@ApiParam(value = "The metadata to be validated." ,required=true ) @Valid @RequestBody String metadata)
50+
throws ApiException;
51+
52+
}

src/main/java/uk/org/iay/incommon/validator/api/ValidatorsApiController.java

+21-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@
1616

1717
import java.util.ArrayList;
1818
import java.util.List;
19+
import java.util.Map;
1920

21+
import javax.servlet.http.HttpServletRequest;
2022
import javax.validation.Valid;
2123

2224
import org.slf4j.Logger;
@@ -25,6 +27,7 @@
2527
import org.springframework.http.HttpStatus;
2628
import org.springframework.http.ResponseEntity;
2729
import org.springframework.stereotype.Controller;
30+
import org.springframework.web.bind.annotation.ExceptionHandler;
2831
import org.springframework.web.bind.annotation.PathVariable;
2932
import org.springframework.web.bind.annotation.RequestBody;
3033

@@ -88,10 +91,26 @@ public ResponseEntity<List<Status>> validate(
8891
@PathVariable("validator_id")
8992
final String validatorId,
9093
@ApiParam(value = "The metadata to be validated.", required = true) @Valid @RequestBody
91-
final String metadata) {
94+
final String metadata) throws ApiException {
9295
final List<Status> statuses = new ArrayList<>();
9396
statuses.add(makeStatus(StatusEnum.ERROR, "component", "message"));
9497
statuses.add(makeStatus(StatusEnum.WARNING, "component/sub", "another message"));
95-
return new ResponseEntity<List<Status>>(statuses, HttpStatus.NOT_IMPLEMENTED);
98+
//return new ResponseEntity<List<Status>>(statuses, HttpStatus.NOT_IMPLEMENTED);
99+
throw new NotFoundException("bad validator identifier '" + validatorId + "'");
100+
}
101+
102+
/**
103+
* Handle an {@link ApiException} by converting it to a {@link Map}, which will
104+
* in turn be converted to a JSON object.
105+
*
106+
* @param req the {@link HttpServletRequest} being handled
107+
* @param ex the {@link ApiException} being handled
108+
* @return a {@link ResponseEntity} equivalent to the {@link ApiException}
109+
*/
110+
@ExceptionHandler(ApiException.class)
111+
public ResponseEntity<Map<String, Object>> handleApiException(final HttpServletRequest req, final ApiException ex) {
112+
final Map<String, Object> m = ex.toMap();
113+
m.put("path", req.getRequestURI());
114+
return new ResponseEntity<>(m, ex.getStatus());
96115
}
97116
}

swagger/.swagger-codegen-ignore

+11
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,14 @@ README.md
1515
# Don't generate dummy controllers once we have implemented them.
1616
#
1717
**/ValidatorsApiController.java
18+
19+
#
20+
# Turns out we need to make changes to the API classes as well, to
21+
# allow for exceptions.
22+
#
23+
**/ValidatorsApi.java
24+
25+
#
26+
# In turn, that means we don't need to generate the exception classes.
27+
#
28+
**/*Exception.java

0 commit comments

Comments
 (0)