5e4c3ee51f81e4ea194f5f4163e3d9a60b2a9886
[policy/api.git] / main / src / main / java / org / onap / policy / api / main / rest / CommonRestController.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP Policy API\r
4  * ================================================================================\r
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
6  * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.\r
7  * Modifications Copyright (C) 2022 Nordix Foundation.\r
8  * ================================================================================\r
9  * Licensed under the Apache License, Version 2.0 (the "License");\r
10  * you may not use this file except in compliance with the License.\r
11  * You may obtain a copy of the License at\r
12  *\r
13  *      http://www.apache.org/licenses/LICENSE-2.0\r
14  *\r
15  * Unless required by applicable law or agreed to in writing, software\r
16  * distributed under the License is distributed on an "AS IS" BASIS,\r
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
18  * See the License for the specific language governing permissions and\r
19  * limitations under the License.\r
20  *\r
21  * SPDX-License-Identifier: Apache-2.0\r
22  * ============LICENSE_END=========================================================\r
23  */\r
24 \r
25 package org.onap.policy.api.main.rest;\r
26 \r
27 import java.util.UUID;\r
28 import org.onap.policy.api.main.exception.PolicyApiRuntimeException;\r
29 import org.onap.policy.common.utils.coder.Coder;\r
30 import org.onap.policy.common.utils.coder.CoderException;\r
31 import org.onap.policy.common.utils.coder.StandardCoder;\r
32 import org.slf4j.Logger;\r
33 import org.slf4j.LoggerFactory;\r
34 import org.springframework.http.HttpHeaders;\r
35 import org.springframework.http.ResponseEntity;\r
36 import org.springframework.web.bind.annotation.ExceptionHandler;\r
37 \r
38 /**\r
39  * Super class from which REST controllers are derived.\r
40  */\r
41 public class CommonRestController {\r
42 \r
43     private static final Logger LOGGER = LoggerFactory.getLogger(CommonRestController.class);\r
44 \r
45     protected static final String EXTENSION_NAME = "interface info";\r
46 \r
47     protected static final String API_VERSION_NAME = "api-version";\r
48     protected static final String API_VERSION = "1.0.0";\r
49 \r
50     protected static final String LAST_MOD_NAME = "last-mod-release";\r
51 \r
52     protected static final String AUTHORIZATION_TYPE = "basicAuth";\r
53 \r
54     protected static final String VERSION_MINOR_NAME = "X-MinorVersion";\r
55     protected static final String VERSION_MINOR_DESCRIPTION =\r
56         "Used to request or communicate a MINOR version back from the client"\r
57             + " to the server, and from the server back to the client";\r
58 \r
59     protected static final String VERSION_PATCH_NAME = "X-PatchVersion";\r
60     protected static final String VERSION_PATCH_DESCRIPTION = "Used only to communicate a PATCH version in a "\r
61         + "response for troubleshooting purposes only, and will not be provided by" + " the client on request";\r
62 \r
63     protected static final String VERSION_LATEST_NAME = "X-LatestVersion";\r
64     protected static final String VERSION_LATEST_DESCRIPTION = "Used only to communicate an API's latest version";\r
65 \r
66     protected static final String REQUEST_ID_NAME = "X-ONAP-RequestID";\r
67     protected static final String REQUEST_ID_HDR_DESCRIPTION = "Used to track REST transactions for logging purpose";\r
68     protected static final String REQUEST_ID_PARAM_DESCRIPTION = "RequestID for http transaction";\r
69 \r
70     protected static final String AUTHENTICATION_ERROR_MESSAGE = "Authentication Error";\r
71     protected static final String AUTHORIZATION_ERROR_MESSAGE = "Authorization Error";\r
72     protected static final String SERVER_ERROR_MESSAGE = "Internal Server Error";\r
73     protected static final String NOT_FOUND_MESSAGE = "Resource Not Found";\r
74     protected static final String INVALID_BODY_MESSAGE = "Invalid Body";\r
75     protected static final String INVALID_PAYLOAD_MESSAGE = "Not Acceptable Payload";\r
76     protected static final String HTTP_CONFLICT_MESSAGE = "Delete Conflict, Rule Violation";\r
77     protected static final String ERROR_MESSAGE_NO_POLICIES_FOUND = "No policies found";\r
78 \r
79     protected final Coder coder = new StandardCoder();\r
80 \r
81     protected <T> ResponseEntity<T> makeOkResponse(UUID requestId, T respEntity) {\r
82         HttpHeaders headers = new HttpHeaders();\r
83         addVersionControlHeaders(headers);\r
84         addLoggingHeaders(headers, requestId);\r
85         return ResponseEntity.ok().headers(headers).body(respEntity);\r
86     }\r
87 \r
88     protected <T> ResponseEntity<T> makeErrorResponse(UUID requestId, T respEntity, int status) {\r
89         HttpHeaders headers = new HttpHeaders();\r
90         addVersionControlHeaders(headers);\r
91         addLoggingHeaders(headers, requestId);\r
92         return ResponseEntity.status(status).headers(headers).body(respEntity);\r
93     }\r
94 \r
95     private void addVersionControlHeaders(HttpHeaders headers) {\r
96         headers.add("X-MinorVersion", "0");\r
97         headers.add("X-PatchVersion", "0");\r
98         headers.add("X-LatestVersion", "1.0.0");\r
99     }\r
100 \r
101     private void addLoggingHeaders(HttpHeaders headers, UUID requestId) {\r
102         if (requestId == null) {\r
103             // Generate a random uuid if client does not embed requestId in rest request\r
104             headers.add("X-ONAP-RequestID", UUID.randomUUID().toString());\r
105         } else {\r
106             headers.add("X-ONAP-RequestID", requestId.toString());\r
107         }\r
108     }\r
109 \r
110     /**\r
111      * Converts an object to a JSON string.\r
112      *\r
113      * @param object object to convert\r
114      * @return a JSON string representing the object\r
115      */\r
116     protected String toJson(Object object) {\r
117         if (object == null) {\r
118             return null;\r
119         }\r
120 \r
121         try {\r
122             return coder.encode(object);\r
123 \r
124         } catch (CoderException e) {\r
125             LOGGER.warn("cannot convert {} to JSON", object.getClass().getName(), e);\r
126             return null;\r
127         }\r
128     }\r
129 \r
130     @ExceptionHandler(value = {PolicyApiRuntimeException.class})\r
131     protected ResponseEntity<Object> handleException(PolicyApiRuntimeException ex) {\r
132         LOGGER.warn(ex.getMessage(), ex.getCause());\r
133         return makeErrorResponse(ex.getRequestId(), ex.getErrorResponse(),\r
134             ex.getErrorResponse().getResponseCode().getStatusCode());\r
135     }\r
136 }