1645e76af64f4473293025edd93a8d7be20b5423
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / PolicyServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20 package org.openecomp.sdc.be.servlets;
21
22 import com.jcabi.aspects.Loggable;
23 import fj.data.Either;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.media.ArraySchema;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.servers.Server;
31 import io.swagger.v3.oas.annotations.tags.Tag;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.stream.Collectors;
36 import javax.inject.Inject;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.ws.rs.Consumes;
39 import javax.ws.rs.DELETE;
40 import javax.ws.rs.GET;
41 import javax.ws.rs.HeaderParam;
42 import javax.ws.rs.POST;
43 import javax.ws.rs.PUT;
44 import javax.ws.rs.Path;
45 import javax.ws.rs.PathParam;
46 import javax.ws.rs.Produces;
47 import javax.ws.rs.core.Context;
48 import javax.ws.rs.core.MediaType;
49 import javax.ws.rs.core.Response;
50 import org.apache.commons.lang3.StringUtils;
51 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
52 import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
53 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
54 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
55 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
56 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
57 import org.openecomp.sdc.be.config.BeEcompErrorManager;
58 import org.openecomp.sdc.be.dao.api.ActionStatus;
59 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
60 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
61 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
62 import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;
63 import org.openecomp.sdc.be.impl.ComponentsUtils;
64 import org.openecomp.sdc.be.impl.ServletUtils;
65 import org.openecomp.sdc.be.model.PolicyDefinition;
66 import org.openecomp.sdc.be.model.PolicyTargetDTO;
67 import org.openecomp.sdc.be.model.Resource;
68 import org.openecomp.sdc.common.api.Constants;
69 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
70 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
71 import org.openecomp.sdc.common.log.enums.StatusCode;
72 import org.openecomp.sdc.common.log.wrappers.Logger;
73 import org.openecomp.sdc.exception.ResponseFormat;
74 import org.springframework.stereotype.Controller;
75
76 /**
77  * Provides REST API to create, retrieve, update, delete a policy
78  */
79 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
80 @Path("/v1/catalog")
81 @Tag(name = "SDCE-2 APIs")
82 @Server(url = "/sdc2/rest")
83 @Controller
84 @Consumes(MediaType.APPLICATION_JSON)
85 @Produces(MediaType.APPLICATION_JSON)
86 public class PolicyServlet extends AbstractValidationsServlet {
87
88     private static final Logger log = Logger.getLogger(PolicyServlet.class);
89     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceServlet.class.getName());
90     private final PolicyBusinessLogic policyBusinessLogic;
91
92     @Inject
93     public PolicyServlet(ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
94                          ServletUtils servletUtils, ResourceImportManager resourceImportManager, PolicyBusinessLogic policyBusinessLogic) {
95         super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
96         this.policyBusinessLogic = policyBusinessLogic;
97         this.servletUtils = servletUtils;
98         this.resourceImportManager = resourceImportManager;
99         this.componentsUtils = componentsUtils;
100     }
101
102     @POST
103     @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}")
104     @Operation(description = "Create Policy", method = "POST", summary = "Returns created Policy", responses = {
105         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
106         @ApiResponse(responseCode = "201", description = "Policy created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
107         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
108         @ApiResponse(responseCode = "409", description = "Policy already exist"),
109         @ApiResponse(responseCode = "404", description = "Component not found")})
110     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
111     public Response createPolicy(@PathParam("componentId") final String containerComponentId,
112                                  @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
113                                      ComponentTypeEnum.RESOURCE_PARAM_NAME,
114                                      ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
115                                  @PathParam("policyTypeName") final String policyTypeName,
116                                  @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
117                                  @Context final HttpServletRequest request) {
118         init();
119         loggerSupportability
120             .log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.STARTED, "Starting to create Policy by user {} containerComponentId={}",
121                 userId, containerComponentId);
122         ComponentTypeEnum componentType = validateComponentTypeAndUserId(containerComponentType, userId);
123         PolicyDefinition policy = policyBusinessLogic.createPolicy(componentType, containerComponentId, policyTypeName, userId, true);
124         loggerSupportability
125             .log(LoggerSupportabilityActions.CREATE_POLICIES, StatusCode.COMPLETE, "Ended create Policy by user {} containerComponentId={}", userId,
126                 containerComponentId);
127         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), policy);
128     }
129
130     @PUT
131     @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
132     @Operation(description = "Update Policy metadata", method = "PUT", summary = "Returns updated Policy", responses = {
133         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
134         @ApiResponse(responseCode = "200", description = "Policy updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
135         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
136         @ApiResponse(responseCode = "404", description = "component / policy Not found")})
137     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
138     public Response updatePolicy(@PathParam("componentId") final String containerComponentId,
139                                  @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
140                                      ComponentTypeEnum.RESOURCE_PARAM_NAME,
141                                      ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
142                                  @PathParam("policyId") final String policyId,
143                                  @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
144                                  @Parameter(description = "PolicyDefinition", required = true) String policyData,
145                                  @Context final HttpServletRequest request) {
146         init();
147         loggerSupportability
148             .log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED, "Starting to update Policy by user {} containerComponentId={}",
149                 userId, containerComponentId);
150         PolicyDefinition policyDefinition = convertJsonToObjectOfClass(policyData, PolicyDefinition.class);
151         policyDefinition.setUniqueId(policyId);
152         policyDefinition = policyBusinessLogic
153             .updatePolicy(validateComponentTypeAndUserId(containerComponentType, userId), containerComponentId, policyDefinition, userId, true);
154         loggerSupportability
155             .log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE, "Ended update Policy by user {} containerComponentId={}",
156                 userId, containerComponentId);
157         return buildOkResponse(policyDefinition);
158     }
159
160     @GET
161     @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
162     @Operation(description = "Get Policy", method = "GET", summary = "Returns Policy", responses = {
163         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
164         @ApiResponse(responseCode = "200", description = "Policy was found"),
165         @ApiResponse(responseCode = "403", description = "Restricted operation"),
166         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
167         @ApiResponse(responseCode = "404", description = "component / policy Not found")})
168     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
169     public Response getPolicy(@PathParam("componentId") final String containerComponentId,
170                               @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
171                                   ComponentTypeEnum.RESOURCE_PARAM_NAME,
172                                   ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
173                               @PathParam("policyId") final String policyId,
174                               @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
175                               @Context final HttpServletRequest request) {
176         init();
177         PolicyDefinition policy = policyBusinessLogic
178             .getPolicy(validateComponentTypeAndUserId(containerComponentType, userId), containerComponentId, policyId, userId);
179         return buildOkResponse(policy);
180     }
181
182     @DELETE
183     @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
184     @Operation(description = "Delete Policy", method = "DELETE", summary = "No body", responses = {
185         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
186         @ApiResponse(responseCode = "204", description = "Policy was deleted"),
187         @ApiResponse(responseCode = "403", description = "Restricted operation"),
188         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
189         @ApiResponse(responseCode = "404", description = "component / policy Not found")})
190     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
191     public Response deletePolicy(@PathParam("componentId") final String containerComponentId,
192                                  @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
193                                      ComponentTypeEnum.RESOURCE_PARAM_NAME,
194                                      ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
195                                  @PathParam("policyId") final String policyId,
196                                  @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
197                                  @Context final HttpServletRequest request) {
198         init();
199         ComponentTypeEnum componentTypeEnum = validateComponentTypeAndUserId(containerComponentType, userId);
200         PolicyDefinition policyDefinition = policyBusinessLogic.deletePolicy(componentTypeEnum, containerComponentId, policyId, userId, true);
201         return buildOkResponse(policyDefinition);
202     }
203
204     @PUT
205     @Path("/{containerComponentType}/{componentId}/policies/{policyId}/undeclare")
206     @Operation(description = "undeclare Policy", method = "PUT", summary = "No body", responses = {
207         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
208         @ApiResponse(responseCode = "204", description = "Policy was undeclared"),
209         @ApiResponse(responseCode = "403", description = "Restricted operation"),
210         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
211         @ApiResponse(responseCode = "404", description = "component / policy Not found")})
212     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
213     public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId,
214                                     @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
215                                         ComponentTypeEnum.RESOURCE_PARAM_NAME,
216                                         ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
217                                     @PathParam("policyId") final String policyId,
218                                     @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
219                                     @Context final HttpServletRequest request) {
220         init();
221         Response response = null;
222         try {
223             ComponentTypeEnum componentTypeEnum = validateComponentTypeAndUserId(containerComponentType, userId);
224             Either<PolicyDefinition, ResponseFormat> undeclarePolicy = policyBusinessLogic
225                 .undeclarePolicy(componentTypeEnum, containerComponentId, policyId, userId, true);
226             if (undeclarePolicy.isLeft()) {
227                 response = buildOkResponse(undeclarePolicy.left().value());
228             } else {
229                 response = buildErrorResponse(undeclarePolicy.right().value());
230             }
231         } catch (Exception e) {
232             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Undeclare Policy");
233             log.error("Failed to undeclare policy. The exception {} occurred. ", e);
234         }
235         return response;
236     }
237
238     @GET
239     @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
240     @Operation(description = "Get component policy properties", method = "GET", summary = "Returns component policy properties", responses = {
241         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PropertyDataDefinition.class)))),
242         @ApiResponse(responseCode = "200", description = "Properties found"),
243         @ApiResponse(responseCode = "400", description = "invalid content - Error: containerComponentType is invalid"),
244         @ApiResponse(responseCode = "403", description = "Restricted operation"),
245         @ApiResponse(responseCode = "404", description = "Componentorpolicy  not found"),
246         @ApiResponse(responseCode = "500", description = "The GET request failed due to internal SDC problem.")})
247     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
248     public Response getPolicyProperties(
249         @Parameter(description = "the id of the component which is the container of the policy") @PathParam("componentId") final String containerComponentId,
250         @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
251             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
252         @Parameter(description = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId,
253         @Parameter(description = "the userid", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
254         @Context final HttpServletRequest request) {
255         init();
256         List<PropertyDataDefinition> propertyDataDefinitionList = policyBusinessLogic
257             .getPolicyProperties(convertToComponentType(containerComponentType), containerComponentId, policyId, userId);
258         return buildOkResponse(propertyDataDefinitionList);
259     }
260
261     @PUT
262     @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
263     @Operation(description = "Update Policy properties", method = "PUT", summary = "Returns updated Policy", responses = {
264         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
265         @ApiResponse(responseCode = "200", description = "Policy properties updated"),
266         @ApiResponse(responseCode = "403", description = "Restricted operation"),
267         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
268         @ApiResponse(responseCode = "404", description = "component / policy Not found")})
269     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
270     public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId,
271                                            @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
272                                                ComponentTypeEnum.RESOURCE_PARAM_NAME,
273                                                ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
274                                            @PathParam("policyId") final String policyId,
275                                            @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
276                                            @Parameter(description = "PolicyDefinition", required = true) String policyData,
277                                            @Context final HttpServletRequest request) {
278         init();
279         loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED,
280             "Starting to update Policy Properties by user {} containerComponentId={}", userId, containerComponentId);
281         ComponentTypeEnum componentTypeEnum = validateComponentTypeAndUserId(containerComponentType, userId);
282         PropertyDataDefinition[] propertyDataDefinitions = convertJsonToObjectOfClass(policyData, PropertyDataDefinition[].class);
283         List<PropertyDataDefinition> propertyDataDefinitionList = policyBusinessLogic
284             .updatePolicyProperties(componentTypeEnum, containerComponentId, policyId, propertyDataDefinitions, userId, true);
285         loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICIES_PROPERTIES, StatusCode.STARTED,
286             "Starting to update Policy Properties by user {} containerComponentId={}", userId, containerComponentId);
287         return buildOkResponse(propertyDataDefinitionList);
288     }
289
290     private ComponentTypeEnum validateComponentTypeAndUserId(final String containerComponentType, String userId) {
291         if (StringUtils.isEmpty(userId)) {
292             log.error("Missing userId HTTP header. ");
293             throw new ByActionStatusComponentException(ActionStatus.MISSING_USER_ID);
294         }
295         return validateComponentType(containerComponentType);
296     }
297
298     @POST
299     @Path("/{containerComponentType}/{componentId}/policies/{policyId}/targets")
300     @Consumes(MediaType.APPLICATION_JSON)
301     @Produces(MediaType.APPLICATION_JSON)
302     @Operation(description = "update policy targets", method = "POST", summary = "Returns updated Policy", responses = {
303         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
304         @ApiResponse(responseCode = "201", description = "Policy target updated"),
305         @ApiResponse(responseCode = "403", description = "Restricted operation"),
306         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
307     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
308     public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId,
309                                         @Parameter(description = "valid values: resources / services", schema = @Schema(allowableValues = {
310                                             ComponentTypeEnum.RESOURCE_PARAM_NAME,
311                                             ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType,
312                                         @PathParam("policyId") final String policyId,
313                                         @HeaderParam(value = Constants.USER_ID_HEADER) @Parameter(description = "USER_ID of modifier user", required = true) String userId,
314                                         @Context final HttpServletRequest request, List<PolicyTargetDTO> requestJson) {
315         Map<PolicyTargetType, List<String>> policyTargetTypeListMap = updatePolicyTargetsFromDTO(requestJson);
316         PolicyDefinition policyDefinition = updatePolicyTargetsFromMap(policyTargetTypeListMap, containerComponentType, containerComponentId,
317             policyId, userId);
318         return buildOkResponse(policyDefinition);
319     }
320
321     @POST
322     @Path("/{componentType}/{componentId}/create/policies")
323     @Operation(description = "Create policies on service", method = "POST", summary = "Return policies list", responses = {
324         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
325         @ApiResponse(responseCode = "200", description = "Component found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
326         @ApiResponse(responseCode = "404", description = "Component not found")})
327     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
328     public Response declareProperties(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId,
329                                       @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
330                                       @Parameter(description = "ComponentIns policies Object to be created", required = true) String componentInstPoliciesMapObj) {
331         return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj, DeclarationTypeEnum.POLICY, request);
332     }
333
334     private PolicyDefinition updatePolicyTargetsFromMap(Map<PolicyTargetType, List<String>> policyTarget, String containerComponentType,
335                                                         String containerComponentId, String policyId, String userId) {
336         ComponentTypeEnum componentTypeEnum = convertToComponentType(containerComponentType);
337         return policyBusinessLogic.updatePolicyTargets(componentTypeEnum, containerComponentId, policyId, policyTarget, userId);
338     }
339
340     private Map<PolicyTargetType, List<String>> updatePolicyTargetsFromDTO(List<PolicyTargetDTO> targetDTOList) {
341         loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.STARTED, "Starting to update Policy target");
342         Map<PolicyTargetType, List<String>> policyTarget = new HashMap<>();
343         for (PolicyTargetDTO currentTarget : targetDTOList) {
344             if (!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())) {
345                 throw new ByActionStatusComponentException(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST, currentTarget.getType());
346             }
347         }
348         loggerSupportability.log(LoggerSupportabilityActions.UPDATE_POLICY_TARGET, StatusCode.COMPLETE, "Ended update Policy target");
349         return policyTarget;
350     }
351
352     public boolean addTargetsByType(Map<PolicyTargetType, List<String>> policyTarget, String type, List<String> uniqueIds) {
353         PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type);
354         if (targetTypeEnum != null) {
355             policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds));
356             return true;
357         } else {
358             return false;
359         }
360     }
361
362     private List<String> validateUniquenessOfIds(List<String> uniqueIds) {
363         return uniqueIds.stream().distinct().collect(Collectors.toList());
364     }
365 }