2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.servlets;
23 import com.jcabi.aspects.Loggable;
24 import fj.data.Either;
25 import io.swagger.annotations.Api;
26 import io.swagger.annotations.ApiOperation;
27 import io.swagger.annotations.ApiParam;
28 import io.swagger.annotations.ApiResponse;
29 import io.swagger.annotations.ApiResponses;
30 import java.util.HashMap;
31 import java.util.List;
33 import java.util.stream.Collectors;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.ws.rs.Consumes;
36 import javax.ws.rs.DELETE;
37 import javax.ws.rs.GET;
38 import javax.ws.rs.HeaderParam;
39 import javax.ws.rs.POST;
40 import javax.ws.rs.PUT;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.PathParam;
43 import javax.ws.rs.Produces;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.MediaType;
46 import javax.ws.rs.core.Response;
47 import org.apache.commons.lang3.StringUtils;
48 import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
49 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
50 import org.openecomp.sdc.be.config.BeEcompErrorManager;
51 import org.openecomp.sdc.be.dao.api.ActionStatus;
52 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
53 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
54 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
55 import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;
56 import org.openecomp.sdc.be.impl.ComponentsUtils;
57 import org.openecomp.sdc.be.impl.ServletUtils;
58 import org.openecomp.sdc.be.model.PolicyDefinition;
59 import org.openecomp.sdc.be.model.PolicyTargetDTO;
60 import org.openecomp.sdc.be.model.Resource;
61 import org.openecomp.sdc.common.api.Constants;
62 import org.openecomp.sdc.common.datastructure.Wrapper;
63 import org.openecomp.sdc.common.log.wrappers.Logger;
64 import org.openecomp.sdc.exception.ResponseFormat;
65 import org.springframework.stereotype.Controller;
68 * Provides REST API to create, retrieve, update, delete a policy
70 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
72 @Api(value = "Policy Servlet")
74 @Consumes(MediaType.APPLICATION_JSON)
75 @Produces(MediaType.APPLICATION_JSON)
76 public class PolicyServlet extends AbstractValidationsServlet {
78 private static final Logger log = Logger.getLogger(PolicyServlet.class);
79 private final PolicyBusinessLogic policyBusinessLogic;
81 public PolicyServlet(PolicyBusinessLogic policyBusinessLogic, ServletUtils servletUtils, ResourceImportManager resourceImportManager, ComponentsUtils componentsUtils) {
82 this.policyBusinessLogic = policyBusinessLogic;
83 this.servletUtils = servletUtils;
84 this.resourceImportManager = resourceImportManager;
85 this.componentsUtils = componentsUtils;
89 @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}")
90 @ApiOperation(value = "Create Policy", httpMethod = "POST", notes = "Returns created Policy", response = Response.class)
91 @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
92 @ApiResponse(code = 409, message = "Policy already exist"), @ApiResponse(code = 404, message = "Component not found")})
93 public Response createPolicy(@PathParam("componentId") final String containerComponentId,
94 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
95 @PathParam("policyTypeName") final String policyTypeName,
96 @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
97 @Context final HttpServletRequest request) {
100 Wrapper<Response> responseWrapper = new Wrapper<>();
102 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
103 if (responseWrapper.isEmpty()) {
104 responseWrapper.setInnerElement(policyBusinessLogic.createPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyTypeName, userId, true)
105 .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), l),
106 this::buildErrorResponse));
108 } catch (Exception e) {
109 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");
110 log.error("Failed to create policy. The exception {} occurred. ", e);
111 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
113 return responseWrapper.getInnerElement();
117 @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
118 @ApiOperation(value = "Update Policy metadata", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class)
119 @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
120 @ApiResponse(code = 404, message = "component / policy Not found")})
121 public Response updatePolicy(@PathParam("componentId") final String containerComponentId,
122 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
123 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
124 @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) {
127 Wrapper<Response> responseWrapper = new Wrapper<>();
129 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
130 Wrapper<PolicyDefinition> policyWrapper = new Wrapper<>();
131 if (responseWrapper.isEmpty()) {
132 convertJsonToObjectOfClass(policyData, policyWrapper, PolicyDefinition.class, responseWrapper);
133 if (policyWrapper.isEmpty()) {
134 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
137 if (!policyWrapper.isEmpty()) {
138 policyWrapper.getInnerElement().setUniqueId(policyId);
139 responseWrapper.setInnerElement(policyBusinessLogic.updatePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyWrapper.getInnerElement(), userId, true)
140 .either(this::buildOkResponse,
141 this::buildErrorResponse));
144 } catch (Exception e) {
145 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");
146 log.error("Failed to update policy. The exception {} occurred. ", e);
147 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
149 return responseWrapper.getInnerElement();
153 @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
154 @ApiOperation(value = "Get Policy", httpMethod = "GET", notes = "Returns Policy", response = Response.class)
155 @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy was found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
156 @ApiResponse(code = 404, message = "component / policy Not found")})
157 public Response getPolicy(@PathParam("componentId") final String containerComponentId,
158 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
159 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
160 @Context final HttpServletRequest request) {
163 Wrapper<Response> responseWrapper = new Wrapper<>();
165 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
166 if (responseWrapper.isEmpty()) {
167 responseWrapper.setInnerElement(policyBusinessLogic.getPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId)
168 .either(this::buildOkResponse,
169 this::buildErrorResponse));
172 } catch (Exception e) {
173 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Policy");
174 log.error("Failed to retrieve policy. The exception {} occurred. ", e);
175 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
177 return responseWrapper.getInnerElement();
181 @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
182 @ApiOperation(value = "Delete Policy", httpMethod = "DELETE", notes = "No body", response = Response.class)
183 @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
184 @ApiResponse(code = 404, message = "component / policy Not found")})
185 public Response deletePolicy(@PathParam("componentId") final String containerComponentId,
186 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
187 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
188 @Context final HttpServletRequest request) {
191 Wrapper<Response> responseWrapper = new Wrapper<>();
193 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
194 if (responseWrapper.isEmpty()) {
195 responseWrapper.setInnerElement(policyBusinessLogic.deletePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true)
196 .either(this::buildOkResponse,
197 this::buildErrorResponse));
200 } catch (Exception e) {
201 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Policy");
202 log.error("Failed to delete policy. The exception {} occurred. ", e);
203 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
205 return responseWrapper.getInnerElement();
209 @Path("/{containerComponentType}/{componentId}/policies/{policyId}/undeclare")
210 @ApiOperation(value = "undeclare Policy", httpMethod = "PUT", notes = "No body", response = Response.class)
211 @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was undeclared"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
212 @ApiResponse(code = 404, message = "component / policy Not found")})
213 public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId,
214 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
215 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
216 @Context final HttpServletRequest request) {
219 Wrapper<Response> responseWrapper = new Wrapper<>();
221 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
222 if (responseWrapper.isEmpty()) {
223 responseWrapper.setInnerElement(policyBusinessLogic.undeclarePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true)
224 .either(this::buildOkResponse,
225 this::buildErrorResponse));
228 } catch (Exception e) {
229 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Undeclare Policy");
230 log.error("Failed to undeclare policy. The exception {} occurred. ", e);
231 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
233 return responseWrapper.getInnerElement();
237 @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
238 @ApiOperation(value = "Get component policy properties", httpMethod = "GET", notes = "Returns component policy properties", response = PropertyDataDefinition.class, responseContainer="List")
239 @ApiResponses(value = {@ApiResponse(code = 200, message = "Properties found"),@ApiResponse(code = 400, message = "invalid content - Error: containerComponentType is invalid"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Componentorpolicy not found"),
240 @ApiResponse(code = 500, message = "The GET request failed due to internal SDC problem.") })public Response getPolicyProperties(@ApiParam(value = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId,
241 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
242 @ApiParam(value = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId,
243 @ApiParam(value = "the userid", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
244 @Context final HttpServletRequest request) {
247 return convertToComponentType(containerComponentType)
249 .bind(cmptType -> policyBusinessLogic.getPolicyProperties(cmptType, containerComponentId, policyId, userId))
250 .either(this::buildOkResponse,
251 this::buildErrorResponse);
252 } catch (Exception e) {
253 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("get Policy properties");
254 log.debug("#getPolicyProperties - get Policy properties has failed.", e);
255 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
262 @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
263 @ApiOperation(value = "Update Policy properties", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class)
264 @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy properties updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
265 @ApiResponse(code = 404, message = "component / policy Not found")})
266 public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId,
267 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
268 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
269 @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) {
271 Wrapper<Response> responseWrapper = new Wrapper<>();
273 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
274 Wrapper<PropertyDataDefinition[]> propertiesWrapper = new Wrapper<>();
275 if (responseWrapper.isEmpty()) {
276 convertJsonToObjectOfClass(policyData, propertiesWrapper, PropertyDataDefinition[].class, responseWrapper);
277 if (propertiesWrapper.isEmpty()) {
278 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
281 if (!propertiesWrapper.isEmpty()) {
282 responseWrapper.setInnerElement(
283 policyBusinessLogic.updatePolicyProperties(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, propertiesWrapper.getInnerElement(), userId, true)
284 .either(this::buildOkResponse, this::buildErrorResponse));
286 } catch (Exception e) {
287 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");
288 log.error("Failed to update policy. The exception {} occurred. ", e);
289 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
291 return responseWrapper.getInnerElement();
294 private Wrapper<ComponentTypeEnum> validateComponentTypeAndUserId(final String containerComponentType, String userId, Wrapper<Response> responseWrapper) {
295 Wrapper<ComponentTypeEnum> componentTypeWrapper = new Wrapper<>();
296 if (StringUtils.isEmpty(userId)) {
297 log.error("Missing userId HTTP header. ");
298 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID)));
300 if (responseWrapper.isEmpty()) {
301 validateComponentType(responseWrapper, componentTypeWrapper, containerComponentType);
303 return componentTypeWrapper;
307 @Path("/{containerComponentType}/{componentId}/policies/{policyId}/targets")
308 @Consumes(MediaType.APPLICATION_JSON)
309 @Produces(MediaType.APPLICATION_JSON)
310 @ApiOperation(value = "update policy targets", httpMethod = "POST", notes = "Returns updated Policy", response = Response.class)
311 @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy target updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content")})
312 public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId,
313 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
314 @PathParam("policyId") final String policyId,
315 @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
316 @Context final HttpServletRequest request,
317 List<PolicyTargetDTO> requestJson) {
320 return updatePolicyTargetsFromDTO(requestJson)
322 .bind(policyTarget -> updatePolicyTargetsFromMap(policyTarget, containerComponentType, containerComponentId, policyId, userId))
323 .either(this::buildOkResponse, this::buildErrorResponse);
325 } catch (Exception e) {
326 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");
327 log.debug("Policy target update has been failed with the exception{}. ", e);
328 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
333 @Path("/{componentType}/{componentId}/create/policies")
334 @ApiOperation(value = "Create policies on service", httpMethod = "POST", notes = "Return policies list", response = Resource.class)
335 @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
336 public Response declareProperties(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
337 @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns policies Object to be created", required = true) String componentInstPoliciesMapObj) {
339 return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj,
340 DeclarationTypeEnum.POLICY, request);
343 private Either<PolicyDefinition, ResponseFormat> updatePolicyTargetsFromMap(Map<PolicyTargetType, List<String>> policyTarget, String containerComponentType, String containerComponentId, String policyId, String userId) {
344 return convertToComponentType(containerComponentType)
346 .bind(cmptType -> policyBusinessLogic.updatePolicyTargets(cmptType, containerComponentId, policyId, policyTarget, userId));
349 private Either<Map<PolicyTargetType, List<String>>, ResponseFormat> updatePolicyTargetsFromDTO(List<PolicyTargetDTO> targetDTOList) {
350 Map<PolicyTargetType, List<String>> policyTarget = new HashMap<>();
351 for (PolicyTargetDTO currentTarget : targetDTOList) {
352 if(!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())){
353 return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST, currentTarget.getType()));
356 return Either.left(policyTarget);
360 public boolean addTargetsByType(Map<PolicyTargetType, List<String>> policyTarget, String type, List<String> uniqueIds) {
361 PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type);
362 if(targetTypeEnum != null){
363 policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds));
371 private List<String> validateUniquenessOfIds(List<String> uniqueIds) {
372 return uniqueIds.stream().distinct().collect(Collectors.toList());