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