Added oparent to sdc main
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ServiceForwardingPathServlet.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
21 package org.openecomp.sdc.be.servlets;
22
23
24 import com.google.common.collect.Sets;
25 import com.jcabi.aspects.Loggable;
26 import fj.data.Either;
27 import io.swagger.annotations.*;
28 import org.apache.commons.collections.MapUtils;
29 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
30 import org.openecomp.sdc.be.config.BeEcompErrorManager;
31 import org.openecomp.sdc.be.dao.api.ActionStatus;
32 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
33 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
34 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
35 import org.openecomp.sdc.be.model.Service;
36 import org.openecomp.sdc.be.model.User;
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.UiServiceDataTransfer;
40 import org.openecomp.sdc.common.api.Constants;
41 import org.openecomp.sdc.common.log.wrappers.Logger;
42 import org.openecomp.sdc.exception.ResponseFormat;
43
44 import javax.inject.Singleton;
45 import javax.servlet.ServletContext;
46 import javax.servlet.http.HttpServletRequest;
47 import javax.ws.rs.*;
48 import javax.ws.rs.core.Context;
49 import javax.ws.rs.core.MediaType;
50 import javax.ws.rs.core.Response;
51 import java.util.Collections;
52 import java.util.Set;
53
54 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
55 @Path("/v1/catalog/services/{serviceId}/paths")
56 @Consumes(MediaType.APPLICATION_JSON)
57 @Produces(MediaType.APPLICATION_JSON)
58 @Api(value = "Service Forwarding Path", description = "Service Forwarding Path Servlet")
59 @Singleton
60 public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
61
62     private static final Logger log = Logger.getLogger(ServiceForwardingPathServlet.class);
63
64     @POST
65     @Consumes(MediaType.APPLICATION_JSON)
66     @Produces(MediaType.APPLICATION_JSON)
67     @Path("/")
68     @ApiOperation(value = "Create Forwarding Path", httpMethod = "POST", notes = "Create Forwarding Path", response = Service.class)
69     @ApiResponses(value =
70             {@ApiResponse(code = 201, message = "Create Forwarding Path"),
71                     @ApiResponse(code = 403, message = "Restricted operation"),
72                     @ApiResponse(code = 400, message = "Invalid content / Missing content"),
73                     @ApiResponse(code = 409, message = "Forwarding Path already exist")})
74     public Response createForwardingPath(
75             @ApiParam(value = "Forwarding Path to create", required = true) String data,
76             @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
77             @Context final HttpServletRequest request,
78             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
79         return createOrUpdate(data, serviceId, request, userId, false);
80     }
81
82
83
84     @PUT
85     @Consumes(MediaType.APPLICATION_JSON)
86     @Produces(MediaType.APPLICATION_JSON)
87     @Path("/")
88     @ApiOperation(value = "Update Forwarding Path", httpMethod = "PUT", notes = "Update Forwarding Path", response = Service.class)
89     @ApiResponses(value =
90             {@ApiResponse(code = 201, message = "Update Forwarding Path"),
91                     @ApiResponse(code = 403, message = "Restricted operation"),
92                     @ApiResponse(code = 400, message = "Invalid content / Missing content"),
93                     @ApiResponse(code = 409, message = "Forwarding Path already exist")})
94     public Response updateForwardingPath(
95             @ApiParam(value = "Update Path to create", required = true) String data,
96             @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
97             @Context final HttpServletRequest request,
98             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
99         return createOrUpdate(data, serviceId, request, userId, true);
100     }
101
102     private Response createOrUpdate( String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) {
103         ServletContext context = request.getSession().getServletContext();
104         String url = request.getMethod() + " " + request.getRequestURI();
105         log.debug("Start handle request of {}", url);
106
107         User modifier = new User();
108         modifier.setUserId(userId);
109         log.debug("modifier id is {}", userId);
110
111         Response response;
112
113         try {
114             String serviceIdLower = serviceId.toLowerCase();
115             ServiceBusinessLogic businessLogic = getServiceBL(context);
116
117             Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
118             if (convertResponse.isRight()) {
119                 log.debug("failed to parse service");
120                 response = buildErrorResponse(convertResponse.right().value());
121                 return response;
122             }
123             Service updatedService = convertResponse.left().value();
124             Either<Service, ResponseFormat> actionResponse ;
125             if (isUpdate) {
126                 actionResponse = businessLogic.updateForwardingPath(serviceIdLower, updatedService, modifier, true);
127             } else {
128                 actionResponse = businessLogic.createForwardingPath(serviceIdLower, updatedService, modifier, true);
129             }
130
131             if (actionResponse.isRight()) {
132                 log.debug("failed to update or create paths");
133                 response = buildErrorResponse(actionResponse.right().value());
134                 return response;
135             }
136
137             Service service = actionResponse.left().value();
138             Object result = RepresentationUtils.toRepresentation(service);
139             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
140
141         } catch (Exception e) {
142             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Forward Path Creation or update");
143             log.debug("create or update forwarding path with an error", e);
144             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
145             return response;
146
147         }
148     }
149
150     @GET
151     @Consumes(MediaType.APPLICATION_JSON)
152     @Produces(MediaType.APPLICATION_JSON)
153     @Path("/{forwardingPathId}")
154     @ApiOperation(value = "Get Forwarding Path", httpMethod = "GET", notes = "GET Forwarding Path", response = ForwardingPathDataDefinition.class)
155     @ApiResponses(value =
156             {@ApiResponse(code = 201, message = "Get Forwarding Path"),
157                     @ApiResponse(code = 403, message = "Restricted operation"),
158                     @ApiResponse(code = 400, message = "Invalid content / Missing content"),
159                     @ApiResponse(code = 409, message = "Forwarding Path already exist")})
160     public Response getForwardingPath(
161             @ApiParam(value = "Forwarding Path to create", required = true) String datax,
162             @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
163             @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
164             @Context final HttpServletRequest request,
165             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
166         ServletContext context = request.getSession().getServletContext();
167         String url = request.getMethod() + " " + request.getRequestURI();
168         log.debug("Start handle request of {}", url);
169
170         User modifier = new User();
171         modifier.setUserId(userId);
172         log.debug("modifier id is {}", userId);
173
174
175         try {
176             ServiceBusinessLogic businessLogic = getServiceBL(context);
177             Either<UiComponentDataTransfer, ResponseFormat> serviceResponse = businessLogic.getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue()));
178             if (serviceResponse.isRight()) {
179                 return buildErrorResponse(serviceResponse.right().value());
180             }
181
182             UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) serviceResponse.left().value();
183
184             ForwardingPathDataDefinition forwardingPathDataDefinition = new ForwardingPathDataDefinition();
185             if (!MapUtils.isEmpty(uiServiceDataTransfer.getForwardingPaths())) {
186                 forwardingPathDataDefinition = uiServiceDataTransfer.getForwardingPaths().get(forwardingPathId);
187             }
188             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(forwardingPathDataDefinition));
189
190
191         } catch (Exception e) {
192             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
193             log.debug("update service metadata failed with exception", e);
194             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
195         }
196     }
197
198     @DELETE
199     @Consumes(MediaType.APPLICATION_JSON)
200     @Produces(MediaType.APPLICATION_JSON)
201     @Path("/{forwardingPathId}")
202     @ApiOperation(value = "Delete Forwarding Path", httpMethod = "DELETE", notes = "Delete Forwarding Path", response = Service.class)
203     @ApiResponses(value =
204             {@ApiResponse(code = 201, message = "Delete Forwarding Path"),
205                     @ApiResponse(code = 403, message = "Restricted operation"),
206                     @ApiResponse(code = 400, message = "Invalid content / Missing content"),
207                     @ApiResponse(code = 409, message = "Forwarding Path already exist")})
208     public Response deleteForwardingPath(
209             @ApiParam(value = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
210             @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId,
211             @Context final HttpServletRequest request,
212             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
213         ServletContext context = request.getSession().getServletContext();
214         String url = request.getMethod() + " " + request.getRequestURI();
215         log.debug("Start handle request of {}", url);
216
217         User modifier = new User();
218         modifier.setUserId(userId);
219         log.debug("modifier id is {}", userId);
220
221         Response response;
222
223         try {
224             String serviceIdLower = serviceId.toLowerCase();
225             ServiceBusinessLogic businessLogic = getServiceBL(context);
226
227             Either<Set<String>, ResponseFormat> actionResponse = businessLogic.deleteForwardingPaths(serviceIdLower, Sets.newHashSet(forwardingPathId), modifier, true);
228
229             if (actionResponse.isRight()) {
230                 log.debug("failed to delete paths");
231                 response = buildErrorResponse(actionResponse.right().value());
232                 return response;
233             }
234
235             Set<String> deletedPaths = actionResponse.left().value();
236             Object result = RepresentationUtils.toRepresentation(deletedPaths);
237             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
238
239         } catch (Exception e) {
240             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete forward paths");
241             log.debug("Delete service paths with an error", e);
242             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
243             return response;
244
245         }
246     }
247
248
249     private Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
250         return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant
251     }
252 }