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.inject.Inject;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.ws.rs.Consumes;
37 import javax.ws.rs.DELETE;
38 import javax.ws.rs.GET;
39 import javax.ws.rs.HeaderParam;
40 import javax.ws.rs.POST;
41 import javax.ws.rs.PUT;
42 import javax.ws.rs.Path;
43 import javax.ws.rs.PathParam;
44 import javax.ws.rs.Produces;
45 import javax.ws.rs.core.Context;
46 import javax.ws.rs.core.MediaType;
47 import javax.ws.rs.core.Response;
48 import org.apache.commons.lang3.StringUtils;
49 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
50 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
51 import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic;
52 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
53 import org.openecomp.sdc.be.config.BeEcompErrorManager;
54 import org.openecomp.sdc.be.dao.api.ActionStatus;
55 import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType;
56 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
57 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
58 import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum;
59 import org.openecomp.sdc.be.impl.ComponentsUtils;
60 import org.openecomp.sdc.be.impl.ServletUtils;
61 import org.openecomp.sdc.be.model.PolicyDefinition;
62 import org.openecomp.sdc.be.model.PolicyTargetDTO;
63 import org.openecomp.sdc.be.model.Resource;
64 import org.openecomp.sdc.be.user.UserBusinessLogic;
65 import org.openecomp.sdc.common.api.Constants;
66 import org.openecomp.sdc.common.datastructure.Wrapper;
67 import org.openecomp.sdc.common.log.wrappers.Logger;
68 import org.openecomp.sdc.exception.ResponseFormat;
69 import org.springframework.stereotype.Controller;
72 * Provides REST API to create, retrieve, update, delete a policy
74 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
76 @Api(value = "Policy Servlet")
78 @Consumes(MediaType.APPLICATION_JSON)
79 @Produces(MediaType.APPLICATION_JSON)
80 public class PolicyServlet extends AbstractValidationsServlet {
82 private static final Logger log = Logger.getLogger(PolicyServlet.class);
83 private final PolicyBusinessLogic policyBusinessLogic;
86 public PolicyServlet(UserBusinessLogic userBusinessLogic,
87 ComponentInstanceBusinessLogic componentInstanceBL,
88 ComponentsUtils componentsUtils, ServletUtils servletUtils,
89 ResourceImportManager resourceImportManager,
90 PolicyBusinessLogic policyBusinessLogic) {
91 super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
92 this.policyBusinessLogic = policyBusinessLogic;
96 @Path("/{containerComponentType}/{componentId}/policies/{policyTypeName}")
97 @ApiOperation(value = "Create Policy", httpMethod = "POST", notes = "Returns created Policy", response = Response.class)
98 @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
99 @ApiResponse(code = 409, message = "Policy already exist"), @ApiResponse(code = 404, message = "Component not found")})
100 public Response createPolicy(@PathParam("componentId") final String containerComponentId,
101 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
102 @PathParam("policyTypeName") final String policyTypeName,
103 @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
104 @Context final HttpServletRequest request) {
107 Wrapper<Response> responseWrapper = new Wrapper<>();
109 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
110 if (responseWrapper.isEmpty()) {
111 responseWrapper.setInnerElement(policyBusinessLogic.createPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyTypeName, userId, true)
112 .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), l),
113 this::buildErrorResponse));
115 } catch (Exception e) {
116 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");
117 log.error("Failed to create policy. The exception {} occurred. ", e);
118 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
120 return responseWrapper.getInnerElement();
124 @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
125 @ApiOperation(value = "Update Policy metadata", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class)
126 @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
127 @ApiResponse(code = 404, message = "component / policy Not found")})
128 public Response updatePolicy(@PathParam("componentId") final String containerComponentId,
129 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
130 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
131 @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) {
134 Wrapper<Response> responseWrapper = new Wrapper<>();
136 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
137 Wrapper<PolicyDefinition> policyWrapper = new Wrapper<>();
138 if (responseWrapper.isEmpty()) {
139 convertJsonToObjectOfClass(policyData, policyWrapper, PolicyDefinition.class, responseWrapper);
140 if (policyWrapper.isEmpty()) {
141 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
144 if (!policyWrapper.isEmpty()) {
145 policyWrapper.getInnerElement().setUniqueId(policyId);
146 responseWrapper.setInnerElement(policyBusinessLogic.updatePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyWrapper.getInnerElement(), userId, true)
147 .either(this::buildOkResponse,
148 this::buildErrorResponse));
151 } catch (Exception e) {
152 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");
153 log.error("Failed to update policy. The exception {} occurred. ", e);
154 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
156 return responseWrapper.getInnerElement();
160 @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
161 @ApiOperation(value = "Get Policy", httpMethod = "GET", notes = "Returns Policy", response = Response.class)
162 @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy was found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
163 @ApiResponse(code = 404, message = "component / policy Not found")})
164 public Response getPolicy(@PathParam("componentId") final String containerComponentId,
165 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
166 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
167 @Context final HttpServletRequest request) {
170 Wrapper<Response> responseWrapper = new Wrapper<>();
172 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
173 if (responseWrapper.isEmpty()) {
174 responseWrapper.setInnerElement(policyBusinessLogic.getPolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId)
175 .either(this::buildOkResponse,
176 this::buildErrorResponse));
179 } catch (Exception e) {
180 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Policy");
181 log.error("Failed to retrieve policy. The exception {} occurred. ", e);
182 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
184 return responseWrapper.getInnerElement();
188 @Path("/{containerComponentType}/{componentId}/policies/{policyId}")
189 @ApiOperation(value = "Delete Policy", httpMethod = "DELETE", notes = "No body", response = Response.class)
190 @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
191 @ApiResponse(code = 404, message = "component / policy Not found")})
192 public Response deletePolicy(@PathParam("componentId") final String containerComponentId,
193 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
194 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
195 @Context final HttpServletRequest request) {
198 Wrapper<Response> responseWrapper = new Wrapper<>();
200 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
201 if (responseWrapper.isEmpty()) {
202 responseWrapper.setInnerElement(policyBusinessLogic.deletePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true)
203 .either(this::buildOkResponse,
204 this::buildErrorResponse));
207 } catch (Exception e) {
208 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Policy");
209 log.error("Failed to delete policy. The exception {} occurred. ", e);
210 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
212 return responseWrapper.getInnerElement();
216 @Path("/{containerComponentType}/{componentId}/policies/{policyId}/undeclare")
217 @ApiOperation(value = "undeclare Policy", httpMethod = "PUT", notes = "No body", response = Response.class)
218 @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was undeclared"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
219 @ApiResponse(code = 404, message = "component / policy Not found")})
220 public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId,
221 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
222 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
223 @Context final HttpServletRequest request) {
226 Wrapper<Response> responseWrapper = new Wrapper<>();
228 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
229 if (responseWrapper.isEmpty()) {
230 responseWrapper.setInnerElement(policyBusinessLogic.undeclarePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true)
231 .either(this::buildOkResponse,
232 this::buildErrorResponse));
235 } catch (Exception e) {
236 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Undeclare Policy");
237 log.error("Failed to undeclare policy. The exception {} occurred. ", e);
238 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
240 return responseWrapper.getInnerElement();
244 @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
245 @ApiOperation(value = "Get component policy properties", httpMethod = "GET", notes = "Returns component policy properties", response = PropertyDataDefinition.class, responseContainer="List")
246 @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"),
247 @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,
248 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
249 @ApiParam(value = "the id of the policy which its properties are to return") @PathParam("policyId") final String policyId,
250 @ApiParam(value = "the userid", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) String userId,
251 @Context final HttpServletRequest request) {
254 return convertToComponentType(containerComponentType)
256 .bind(cmptType -> policyBusinessLogic.getPolicyProperties(cmptType, containerComponentId, policyId, userId))
257 .either(this::buildOkResponse,
258 this::buildErrorResponse);
259 } catch (Exception e) {
260 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("get Policy properties");
261 log.debug("#getPolicyProperties - get Policy properties has failed.", e);
262 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
269 @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties")
270 @ApiOperation(value = "Update Policy properties", httpMethod = "PUT", notes = "Returns updated Policy", response = Response.class)
271 @ApiResponses(value = {@ApiResponse(code = 200, message = "Policy properties updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
272 @ApiResponse(code = 404, message = "component / policy Not found")})
273 public Response updatePolicyProperties(@PathParam("componentId") final String containerComponentId,
274 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
275 @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
276 @ApiParam(value = "PolicyDefinition", required = true) String policyData, @Context final HttpServletRequest request) {
278 Wrapper<Response> responseWrapper = new Wrapper<>();
280 Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper);
281 Wrapper<PropertyDataDefinition[]> propertiesWrapper = new Wrapper<>();
282 if (responseWrapper.isEmpty()) {
283 convertJsonToObjectOfClass(policyData, propertiesWrapper, PropertyDataDefinition[].class, responseWrapper);
284 if (propertiesWrapper.isEmpty()) {
285 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)));
288 if (!propertiesWrapper.isEmpty()) {
289 responseWrapper.setInnerElement(
290 policyBusinessLogic.updatePolicyProperties(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, propertiesWrapper.getInnerElement(), userId, true)
291 .either(this::buildOkResponse, this::buildErrorResponse));
293 } catch (Exception e) {
294 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Policy");
295 log.error("Failed to update policy. The exception {} occurred. ", e);
296 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
298 return responseWrapper.getInnerElement();
301 private Wrapper<ComponentTypeEnum> validateComponentTypeAndUserId(final String containerComponentType, String userId, Wrapper<Response> responseWrapper) {
302 Wrapper<ComponentTypeEnum> componentTypeWrapper = new Wrapper<>();
303 if (StringUtils.isEmpty(userId)) {
304 log.error("Missing userId HTTP header. ");
305 responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID)));
307 if (responseWrapper.isEmpty()) {
308 validateComponentType(responseWrapper, componentTypeWrapper, containerComponentType);
310 return componentTypeWrapper;
314 @Path("/{containerComponentType}/{componentId}/policies/{policyId}/targets")
315 @Consumes(MediaType.APPLICATION_JSON)
316 @Produces(MediaType.APPLICATION_JSON)
317 @ApiOperation(value = "update policy targets", httpMethod = "POST", notes = "Returns updated Policy", response = Response.class)
318 @ApiResponses(value = {@ApiResponse(code = 201, message = "Policy target updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content")})
319 public Response updatePolicyTargets(@PathParam("componentId") final String containerComponentId,
320 @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
321 @PathParam("policyId") final String policyId,
322 @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId,
323 @Context final HttpServletRequest request,
324 List<PolicyTargetDTO> requestJson) {
327 return updatePolicyTargetsFromDTO(requestJson)
329 .bind(policyTarget -> updatePolicyTargetsFromMap(policyTarget, containerComponentType, containerComponentId, policyId, userId))
330 .either(this::buildOkResponse, this::buildErrorResponse);
332 } catch (Exception e) {
333 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Policy");
334 log.debug("Policy target update has been failed with the exception{}. ", e);
335 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
340 @Path("/{componentType}/{componentId}/create/policies")
341 @ApiOperation(value = "Create policies on service", httpMethod = "POST", notes = "Return policies list", response = Resource.class)
342 @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
343 public Response declareProperties(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
344 @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns policies Object to be created", required = true) String componentInstPoliciesMapObj) {
346 return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj,
347 DeclarationTypeEnum.POLICY, request);
350 private Either<PolicyDefinition, ResponseFormat> updatePolicyTargetsFromMap(Map<PolicyTargetType, List<String>> policyTarget, String containerComponentType, String containerComponentId, String policyId, String userId) {
351 return convertToComponentType(containerComponentType)
353 .bind(cmptType -> policyBusinessLogic.updatePolicyTargets(cmptType, containerComponentId, policyId, policyTarget, userId));
356 private Either<Map<PolicyTargetType, List<String>>, ResponseFormat> updatePolicyTargetsFromDTO(List<PolicyTargetDTO> targetDTOList) {
357 Map<PolicyTargetType, List<String>> policyTarget = new HashMap<>();
358 for (PolicyTargetDTO currentTarget : targetDTOList) {
359 if(!addTargetsByType(policyTarget, currentTarget.getType(), currentTarget.getUniqueIds())){
360 return Either.right(componentsUtils.getResponseFormat(ActionStatus.POLICY_TARGET_TYPE_DOES_NOT_EXIST, currentTarget.getType()));
363 return Either.left(policyTarget);
367 public boolean addTargetsByType(Map<PolicyTargetType, List<String>> policyTarget, String type, List<String> uniqueIds) {
368 PolicyTargetType targetTypeEnum = PolicyTargetType.getByNameIgnoreCase(type);
369 if(targetTypeEnum != null){
370 policyTarget.put(targetTypeEnum, validateUniquenessOfIds(uniqueIds));
378 private List<String> validateUniquenessOfIds(List<String> uniqueIds) {
379 return uniqueIds.stream().distinct().collect(Collectors.toList());