Interface operation support for service - BE
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / InterfaceOperationServlet.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.jcabi.aspects.Loggable;
20 import fj.data.Either;
21 import io.swagger.annotations.Api;
22 import io.swagger.annotations.ApiOperation;
23 import io.swagger.annotations.ApiParam;
24 import io.swagger.annotations.ApiResponse;
25 import io.swagger.annotations.ApiResponses;
26 import java.util.Optional;
27 import java.util.UUID;
28 import javax.inject.Singleton;
29 import javax.servlet.ServletContext;
30 import javax.servlet.http.HttpServletRequest;
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.DELETE;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.HeaderParam;
35 import javax.ws.rs.POST;
36 import javax.ws.rs.PUT;
37 import javax.ws.rs.Path;
38 import javax.ws.rs.PathParam;
39 import javax.ws.rs.Produces;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.MediaType;
42 import javax.ws.rs.core.Response;
43 import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.datamodel.utils.InterfaceUIDataConverter;
47 import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationDataDefinition;
48 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
49 import org.openecomp.sdc.be.model.Operation;
50 import org.openecomp.sdc.be.model.User;
51 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
52 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
53 import org.openecomp.sdc.common.api.Constants;
54 import org.openecomp.sdc.exception.ResponseFormat;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
59 @Path("/v1/catalog/{componentType}/{componentId}/interfaceOperations")
60 @Consumes(MediaType.APPLICATION_JSON)
61 @Produces(MediaType.APPLICATION_JSON)
62 @Api(value = "Interface Operation", description = "Interface Operation Servlet")
63 @Singleton
64 public class InterfaceOperationServlet extends AbstractValidationsServlet {
65
66   private static final Logger log = LoggerFactory.getLogger(InterfaceOperationServlet.class);
67
68   @POST
69   @Consumes(MediaType.APPLICATION_JSON)
70   @Produces(MediaType.APPLICATION_JSON)
71   @Path("/")
72   @ApiOperation(value = "Create Interface Operation", httpMethod = "POST", notes = "Create Interface Operation", response = InterfaceOperationDataDefinition.class)
73   @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Interface Operation"),
74       @ApiResponse(code = 403, message = "Restricted operation"),
75       @ApiResponse(code = 400, message = "Invalid content / Missing content"),
76       @ApiResponse(code = 409, message = "Interface Operation already exist")})
77   public Response createInterfaceOperation(
78       @ApiParam(value = "Interface Operation to create", required = true) String data,
79       @ApiParam(value = "Component type") @PathParam("componentType") String componentType,
80       @ApiParam(value = "Component Id") @PathParam("componentId") String componentId,
81       @Context final HttpServletRequest request,
82       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
83     return createOrUpdate(data, componentType ,componentId, request, userId, false);
84   }
85
86   @PUT
87   @Consumes(MediaType.APPLICATION_JSON)
88   @Produces(MediaType.APPLICATION_JSON)
89   @Path("/")
90   @ApiOperation(value = "Update Interface Operation", httpMethod = "PUT", notes = "Update Interface Operation", response = InterfaceOperationDataDefinition.class)
91   @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Interface Operation"),
92       @ApiResponse(code = 403, message = "Restricted operation"),
93       @ApiResponse(code = 400, message = "Invalid content / Missing content")})
94   public Response updateInterfaceOperation(
95       @ApiParam(value = "Interface Operation to update", required = true) String data,
96       @ApiParam(value = "Component type") @PathParam("componentType") String componentType,
97       @ApiParam(value = "Component Id") @PathParam("componentId") String componentId,
98       @Context final HttpServletRequest request,
99       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
100     return createOrUpdate(data, componentType,componentId, request, userId, true);
101   }
102
103   @DELETE
104   @Consumes(MediaType.APPLICATION_JSON)
105   @Produces(MediaType.APPLICATION_JSON)
106   @Path("/{interfaceOperationId}")
107   @ApiOperation(value = "Delete Interface Operation", httpMethod = "DELETE", notes = "Delete Interface Operation", response = InterfaceOperationDataDefinition.class)
108   @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Interface Operation"),
109       @ApiResponse(code = 403, message = "Restricted operation"),
110       @ApiResponse(code = 400, message = "Invalid content / Missing content")})
111   public Response deleteInterfaceOperation(
112       @ApiParam(value = "Interface Operation Id") @PathParam("interfaceOperationId") String interfaceOperationId,
113       @ApiParam(value = "Component Id") @PathParam("componentId") String componentId,
114       @Context final HttpServletRequest request,
115       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
116     return delete(interfaceOperationId, componentId, request, userId);
117   }
118
119   @GET
120   @Consumes(MediaType.APPLICATION_JSON)
121   @Produces(MediaType.APPLICATION_JSON)
122   @Path("/{interfaceOperationId}")
123   @ApiOperation(value = "Get Interface Operation", httpMethod = "GET", notes = "GET Interface Operation", response = InterfaceOperationDataDefinition.class)
124   @ApiResponses(value = {@ApiResponse(code = 201, message = "Get Interface Operation"),
125       @ApiResponse(code = 403, message = "Restricted operation"),
126       @ApiResponse(code = 400, message = "Invalid content / Missing content")})
127   public Response getInterfaceOperation(
128       @ApiParam(value = "Interface Operation Id") @PathParam("interfaceOperationId") String interfaceOperationId,
129       @ApiParam(value = "Component Id") @PathParam("componentId") String componentId,
130       @Context final HttpServletRequest request,
131       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
132
133     return get(interfaceOperationId, componentId, request, userId);
134   }
135
136   private Response get (String interfaceOperationId,  String componentId, HttpServletRequest request, String userId){
137     ServletContext context = request.getSession().getServletContext();
138     String url = request.getMethod() + " " + request.getRequestURI();
139
140     User modifier = new User();
141     modifier.setUserId(userId);
142     log.debug("Start get request of {} with modifier id {}", url, userId);
143
144     try {
145       String componentIdLower = componentId.toLowerCase();
146       InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context);
147
148       Either<Operation, ResponseFormat> actionResponse = businessLogic.getInterfaceOperation(componentIdLower, interfaceOperationId, modifier, true);
149       if (actionResponse.isRight()) {
150         log.error("failed to get interface operation");
151         return buildErrorResponse(actionResponse.right().value());
152       }
153
154       InterfaceOperationDataDefinition interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(actionResponse.left().value());
155       Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition);
156       return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
157     }
158     catch (Exception e) {
159       BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component interface operations");
160       log.error("get component interface operations failed with exception", e);
161       return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
162     }
163   }
164
165   private Response delete (String interfaceOperationId, String componentId, HttpServletRequest
166       request, String userId){
167
168     ServletContext context = request.getSession().getServletContext();
169     String url = request.getMethod() + " " + request.getRequestURI();
170
171     User modifier = new User();
172     modifier.setUserId(userId);
173     log.debug("Start delete request of {} with modifier id {}", url, userId);
174
175     try {
176       String componentIdLower = componentId.toLowerCase();
177       InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context);
178
179       Either<Operation, ResponseFormat> actionResponse = businessLogic.deleteInterfaceOperation(componentIdLower, interfaceOperationId, modifier, true);
180       if (actionResponse.isRight()) {
181         log.error("failed to delete interface operation");
182         return buildErrorResponse(actionResponse.right().value());
183       }
184
185       InterfaceOperationDataDefinition interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(actionResponse.left().value());
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.error("Delete interface operation with an error", e);
192       return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
193     }
194   }
195
196   private Response createOrUpdate (String data, String componentType, String componentId, HttpServletRequest request, String userId, boolean isUpdate) {
197     ServletContext context = request.getSession().getServletContext();
198     String url = request.getMethod() + " " + request.getRequestURI();
199
200     User modifier = new User();
201     modifier.setUserId(userId);
202     log.debug("Start create or update request of {} with modifier id {}", url, userId);
203
204     try {
205       String componentIdLower = componentId.toLowerCase();
206       InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context);
207
208       Operation operation = getMappedOperationData(data, isUpdate, modifier, ComponentTypeEnum.findByParamName(componentType));
209       Either<Operation, ResponseFormat> actionResponse ;
210       if (isUpdate) {
211         actionResponse = businessLogic.updateInterfaceOperation(componentIdLower, operation, modifier, true);
212       } else {
213         actionResponse = businessLogic.createInterfaceOperation(componentIdLower, operation, modifier, true);
214       }
215
216       if (actionResponse.isRight()) {
217         log.error("failed to update or create interface operation");
218         return buildErrorResponse(actionResponse.right().value());
219       }
220
221       InterfaceOperationDataDefinition interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(actionResponse.left().value());
222       Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition);
223       return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
224     }
225     catch (Exception e) {
226       BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Interface Operation Creation or update");
227       log.error("create or update interface Operation with an error", e);
228       return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
229     }
230   }
231
232   private Operation getMappedOperationData(String inputJson, boolean isUpdate, User user, ComponentTypeEnum componentTypeEnum){
233     Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum);
234     Optional<InterfaceOperationDataDefinition> opDef = uiComponentEither.left().value().getInterfaceOperations().values().stream().findFirst();
235     InterfaceOperationDataDefinition interfaceOperationDataDefinition = new InterfaceOperationDataDefinition();
236     if(opDef.isPresent()) {
237       interfaceOperationDataDefinition = opDef.get();
238       if(!isUpdate)
239         interfaceOperationDataDefinition.setUniqueId(UUID.randomUUID().toString());
240     }
241     return InterfaceUIDataConverter.convertInterfaceDataToOperationData(interfaceOperationDataDefinition);
242   }
243
244 }
245