re base code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ResourceInterfaceOperationServlet.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.be.servlets;
18
19 import com.google.common.collect.Sets;
20 import com.jcabi.aspects.Loggable;
21 import fj.data.Either;
22 import io.swagger.annotations.*;
23 import org.apache.commons.collections.CollectionUtils;
24 import org.apache.commons.collections.MapUtils;
25 import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
26 import org.openecomp.sdc.be.config.BeEcompErrorManager;
27 import org.openecomp.sdc.be.dao.api.ActionStatus;
28 import org.openecomp.sdc.be.datamodel.utils.InterfaceUIDataConverter;
29 import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationDataDefinition;
30 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
31 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
32 import org.openecomp.sdc.be.model.InterfaceDefinition;
33 import org.openecomp.sdc.be.model.Operation;
34 import org.openecomp.sdc.be.model.Resource;
35 import org.openecomp.sdc.be.model.User;
36 import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils;
37 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
38 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
39 import org.openecomp.sdc.be.ui.model.UiResourceDataTransfer;
40 import org.openecomp.sdc.common.api.Constants;
41 import org.openecomp.sdc.exception.ResponseFormat;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import javax.inject.Singleton;
46 import javax.servlet.ServletContext;
47 import javax.servlet.http.HttpServletRequest;
48 import javax.ws.rs.*;
49 import javax.ws.rs.core.Context;
50 import javax.ws.rs.core.MediaType;
51 import javax.ws.rs.core.Response;
52 import java.util.*;
53
54 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
55 @Path("/v1/catalog/resources/{resourceId}/interfaceOperations")
56 @Consumes(MediaType.APPLICATION_JSON)
57 @Produces(MediaType.APPLICATION_JSON)
58 @Api(value = "Interface Operation", description = "Interface Operation Servlet")
59 @Singleton
60 public class ResourceInterfaceOperationServlet extends AbstractValidationsServlet {
61
62   private static final Logger log = LoggerFactory.getLogger(ResourceInterfaceOperationServlet.class);
63
64   @POST
65   @Consumes(MediaType.APPLICATION_JSON)
66   @Produces(MediaType.APPLICATION_JSON)
67   @Path("/")
68   @ApiOperation(value = "Create Interface Operation", httpMethod = "POST", notes = "Create Interface Operation", response = InterfaceOperationDataDefinition.class)
69   @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Interface Operation"),
70       @ApiResponse(code = 403, message = "Restricted operation"),
71       @ApiResponse(code = 400, message = "Invalid content / Missing content"),
72       @ApiResponse(code = 409, message = "Interface Operation already exist")})
73   public Response createInterfaceOperation(
74       @ApiParam(value = "Interface Operation to create", required = true) String data,
75       @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
76       @Context final HttpServletRequest request,
77       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
78     return createOrUpdate(data, resourceId, request, userId, false);
79   }
80
81
82   @PUT
83   @Consumes(MediaType.APPLICATION_JSON)
84   @Produces(MediaType.APPLICATION_JSON)
85   @Path("/")
86   @ApiOperation(value = "Update Interface Operation", httpMethod = "PUT", notes = "Update Interface Operation", response = InterfaceOperationDataDefinition.class)
87   @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Interface Operation"),
88       @ApiResponse(code = 403, message = "Restricted operation"),
89       @ApiResponse(code = 400, message = "Invalid content / Missing content")})
90   public Response updateInterfaceOperation(
91       @ApiParam(value = "Interface Operation to update", required = true) String data,
92       @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
93       @Context final HttpServletRequest request,
94       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
95     return createOrUpdate(data, resourceId, request, userId, true);
96   }
97
98
99   @DELETE
100   @Consumes(MediaType.APPLICATION_JSON)
101   @Produces(MediaType.APPLICATION_JSON)
102   @Path("/{interfaceOperationId}")
103   @ApiOperation(value = "Delete Interface Operation", httpMethod = "DELETE", notes = "Delete Interface Operation", response = InterfaceOperationDataDefinition.class)
104   @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Interface Operation"),
105       @ApiResponse(code = 403, message = "Restricted operation"),
106       @ApiResponse(code = 400, message = "Invalid content / Missing content")})
107   public Response deleteInterfaceOperation(
108       @ApiParam(value = "Interface Operation Id") @PathParam("interfaceOperationId") String interfaceOperationId,
109       @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
110       @Context final HttpServletRequest request,
111       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
112     return delete(interfaceOperationId, resourceId, request, userId);
113   }
114
115   @GET
116   @Consumes(MediaType.APPLICATION_JSON)
117   @Produces(MediaType.APPLICATION_JSON)
118   @Path("/{interfaceOperationId}")
119   @ApiOperation(value = "Get Interface Operation", httpMethod = "GET", notes = "GET Interface Operation", response = InterfaceOperationDataDefinition.class)
120   @ApiResponses(value = {@ApiResponse(code = 201, message = "Get Interface Operation"),
121       @ApiResponse(code = 403, message = "Restricted operation"),
122       @ApiResponse(code = 400, message = "Invalid content / Missing content")})
123   public Response getInterfaceOperation(
124       @ApiParam(value = "Interface Operation Id") @PathParam("interfaceOperationId") String interfaceOperationId,
125       @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId,
126       @Context final HttpServletRequest request,
127       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
128
129     return get(interfaceOperationId, resourceId, request, userId);
130   }
131
132   private Response get (String interfaceOperationId, String resourceId, HttpServletRequest request, String userId){
133     ServletContext context = request.getSession().getServletContext();
134     String url = request.getMethod() + " " + request.getRequestURI();
135
136     User modifier = new User();
137     modifier.setUserId(userId);
138     log.debug("Start get request of {} with modifier id {}", url, userId);
139
140     try {
141       InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context);
142       Either<UiComponentDataTransfer, ResponseFormat> resourceResponse = businessLogic.getComponentDataFilteredByParams(resourceId, modifier, Collections
143           .singletonList(ComponentFieldsEnum.INTERFACES.getValue()));
144       if (resourceResponse.isRight()) {
145         return buildErrorResponse(resourceResponse.right().value());
146       }
147
148       UiResourceDataTransfer uiResourceDataTransfer = (UiResourceDataTransfer) resourceResponse.left().value();
149       InterfaceOperationDataDefinition interfaceOperationDataDefinition = getInterfaceOperationForResponse(interfaceOperationId, uiResourceDataTransfer.getInterfaces());
150
151       return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition));
152
153     } catch (Exception e) {
154       BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Resource interface operations");
155       log.debug("get resource interface operations failed with exception", e);
156       return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
157     }
158   }
159
160   private Response delete (String interfaceOperationId, String resourceId, HttpServletRequest
161       request, String userId){
162
163     ServletContext context = request.getSession().getServletContext();
164     String url = request.getMethod() + " " + request.getRequestURI();
165
166     User modifier = new User();
167     modifier.setUserId(userId);
168     log.debug("Start delete request of {} with modifier id {}", url, userId);
169
170     Response response;
171
172     try {
173       String resourceIdLower = resourceId.toLowerCase();
174       InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context);
175
176       Either<Resource, ResponseFormat> actionResponse = businessLogic.deleteInterfaceOperation(resourceIdLower, Sets.newHashSet(interfaceOperationId), modifier, true);
177
178       if (actionResponse.isRight()) {
179         log.debug("failed to delete interface operation");
180         response = buildErrorResponse(actionResponse.right().value());
181         return response;
182       }
183
184       Resource resource = actionResponse.left().value();
185       InterfaceOperationDataDefinition interfaceOperationDataDefinition = getInterfaceOperationForResponse(interfaceOperationId, resource.getInterfaces());
186       Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition);
187       return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
188
189     } catch (Exception e) {
190       BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Interface Operation");
191       log.debug("Delete interface operation with an error", e);
192       response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
193       return response;
194
195     }
196   }
197
198   private Response createOrUpdate (String data, String resourceId, HttpServletRequest request, String userId, boolean isUpdate) {
199     ServletContext context = request.getSession().getServletContext();
200     String url = request.getMethod() + " " + request.getRequestURI();
201
202     User modifier = new User();
203     modifier.setUserId(userId);
204     log.debug("Start create or update request of {} with modifier id {}", url, userId);
205
206     Response response;
207     try {
208       String resourceIdLower = resourceId.toLowerCase();
209       InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context);
210
211       Either<Resource, ResponseFormat> resourceEither = businessLogic.getResourceDetails(resourceId);
212       Resource origResource = resourceEither.left().value();
213
214       Either<Resource, ResponseFormat> convertResponse = parseToResource(data, origResource, isUpdate, modifier);
215       if (convertResponse.isRight()) {
216         log.debug("failed to parse resource");
217         response = buildErrorResponse(convertResponse.right().value());
218         return response;
219       }
220
221       Resource updatedResource = convertResponse.left().value();
222       Either<Resource, ResponseFormat> actionResponse ;
223       if (isUpdate) {
224         actionResponse = businessLogic.updateInterfaceOperation(resourceIdLower, updatedResource, modifier, true);
225       } else {
226         actionResponse = businessLogic.createInterfaceOperation(resourceIdLower, updatedResource, modifier, true);
227       }
228
229       if (actionResponse.isRight()) {
230         log.debug("failed to update or create interface operation");
231         response = buildErrorResponse(actionResponse.right().value());
232         return response;
233       }
234
235       Resource resource = actionResponse.left().value();
236       List<Operation> operationData = InterfaceUtils.getOperationsFromInterface(updatedResource.getInterfaces());
237       InterfaceOperationDataDefinition interfaceOperationDataDefinition = getInterfaceOperationForResponse(operationData.get(0).getUniqueId(), resource.getInterfaces());
238
239       Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition);
240       return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
241
242     } catch (Exception e) {
243       BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Interface Operation Creation or update");
244       log.debug("create or update interface Operation with an error", e);
245       response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
246       return response;
247
248     }
249   }
250
251   private Either<Resource, ResponseFormat> parseToResource(String resourceJson, Resource origResource, boolean isUpdate, User user) {
252
253     Resource resource = convertToResourceObject(resourceJson, user).left().value();
254
255     Either<UiResourceDataTransfer, ResponseFormat> uiResourceEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, UiResourceDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE);
256     Optional<InterfaceOperationDataDefinition> opDef = uiResourceEither.left().value().getInterfaceOperations().values().stream().findFirst();
257     InterfaceOperationDataDefinition interfaceOperationDataDefinition;
258     if(opDef.isPresent()) {
259       interfaceOperationDataDefinition = opDef.get();
260
261       if(!isUpdate)
262         interfaceOperationDataDefinition.setUniqueId(UUID.randomUUID().toString());
263
264       Map<String, Operation> interfaceOperations = new HashMap<>();
265       interfaceOperations.put(interfaceOperationDataDefinition.getUniqueId(), InterfaceUIDataConverter.convertInterfaceDataToOperationData(interfaceOperationDataDefinition));
266       InterfaceDefinition interfaceDefinition = new InterfaceDefinition();
267       interfaceDefinition.setUniqueId(UUID.randomUUID().toString());
268       interfaceDefinition.setToscaResourceName(InterfaceUtils.createInterfaceToscaResourceName(origResource.getName()));
269       interfaceDefinition.setOperationsMap(interfaceOperations);
270
271       Map<String, InterfaceDefinition> interfaceMap = new HashMap<>();
272       interfaceMap.put(interfaceDefinition.getUniqueId(), interfaceDefinition);
273
274       resource.setInterfaces(interfaceMap);
275     }
276
277     return Either.left(resource);
278   }
279
280   private Either<Resource, ResponseFormat> convertToResourceObject(String resourceJson, User user) {
281     return getComponentsUtils().convertJsonToObjectUsingObjectMapper(resourceJson, user, Resource.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.RESOURCE);
282   }
283
284   private InterfaceOperationDataDefinition getInterfaceOperationForResponse(String interfaceOperationId, Map<String, InterfaceDefinition> interfaces){
285     InterfaceOperationDataDefinition interfaceOperationDataDefinition = new InterfaceOperationDataDefinition();
286     if(!MapUtils.isEmpty(interfaces)){
287       List<Operation> operationData = InterfaceUtils.getOperationsFromInterface(interfaces);
288       if(CollectionUtils.isNotEmpty(operationData)){
289         Optional<Operation> matchedOp = operationData.stream().filter(a -> a.getUniqueId().equals(interfaceOperationId)).findAny();
290         if(matchedOp.isPresent()) {
291           interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(matchedOp.get());
292         }
293       }
294     }
295     return interfaceOperationDataDefinition;
296   }
297
298 }
299