253acd5395458babf84e46f244ca3a7bae14442e
[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.v3.oas.annotations.Operation;
28 import io.swagger.v3.oas.annotations.Parameter;
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.servers.Server;
34 import io.swagger.v3.oas.annotations.servers.Servers;
35 import io.swagger.v3.oas.annotations.tags.Tag;
36 import io.swagger.v3.oas.annotations.tags.Tags;
37 import org.apache.commons.collections.MapUtils;
38 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
39 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
40 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
41 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
42 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager;
44 import org.openecomp.sdc.be.dao.api.ActionStatus;
45 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
46 import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum;
47 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
48 import org.openecomp.sdc.be.impl.ComponentsUtils;
49 import org.openecomp.sdc.be.impl.ServletUtils;
50 import org.openecomp.sdc.be.model.Service;
51 import org.openecomp.sdc.be.model.User;
52 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
53 import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
54 import org.openecomp.sdc.be.ui.model.UiServiceDataTransfer;
55 import org.openecomp.sdc.be.user.UserBusinessLogic;
56 import org.openecomp.sdc.common.api.Constants;
57 import org.openecomp.sdc.common.log.wrappers.Logger;
58 import org.openecomp.sdc.exception.ResponseFormat;
59 import org.springframework.stereotype.Controller;
60
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.io.IOException;
76 import java.util.Collections;
77 import java.util.Set;
78
79 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
80 @Path("/v1/catalog/services/{serviceId}/paths")
81 @Consumes(MediaType.APPLICATION_JSON)
82 @Produces(MediaType.APPLICATION_JSON)
83 @Tags({@Tag(name = "SDC Internal APIs")})
84 @Servers({@Server(url = "/sdc2/rest")})
85 @Controller
86 public class ServiceForwardingPathServlet extends AbstractValidationsServlet {
87
88     private static final Logger log = Logger.getLogger(ServiceForwardingPathServlet.class);
89     private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
90     private static final String MODIFIER_ID_IS = "modifier id is {}";
91     private final ServiceBusinessLogic serviceBusinessLogic;
92
93     @Inject
94     public ServiceForwardingPathServlet(UserBusinessLogic userBusinessLogic,
95         ComponentInstanceBusinessLogic componentInstanceBL,
96         ComponentsUtils componentsUtils, ServletUtils servletUtils,
97         ResourceImportManager resourceImportManager,
98         ServiceBusinessLogic serviceBusinessLogic) {
99         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
100         this.serviceBusinessLogic = serviceBusinessLogic;
101     }
102
103     @POST
104     @Consumes(MediaType.APPLICATION_JSON)
105     @Produces(MediaType.APPLICATION_JSON)
106     @Path("/")
107     @Operation(description = "Create Forwarding Path", method = "POST", summary = "Create Forwarding Path",
108             responses = {@ApiResponse(
109                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
110                     @ApiResponse(responseCode = "201", description = "Create Forwarding Path"),
111                     @ApiResponse(responseCode = "403", description = "Restricted operation"),
112                     @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
113                     @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
114     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
115     public Response createForwardingPath(
116             @Parameter(description = "Forwarding Path to create", required = true) String data,
117             @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
118             @Context final HttpServletRequest request,
119             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
120         return createOrUpdate(data, serviceId, request, userId, false);
121     }
122
123
124
125     @PUT
126     @Consumes(MediaType.APPLICATION_JSON)
127     @Produces(MediaType.APPLICATION_JSON)
128     @Path("/")
129     @Operation(description = "Update Forwarding Path", method = "PUT", summary = "Update Forwarding Path", responses = {
130             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
131             @ApiResponse(responseCode = "201", description = "Update Forwarding Path"),
132             @ApiResponse(responseCode = "403", description = "Restricted operation"),
133             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
134             @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
135     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
136     public Response updateForwardingPath(
137             @Parameter(description = "Update Path to create", required = true) String data,
138             @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
139             @Context final HttpServletRequest request,
140             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
141         return createOrUpdate(data, serviceId, request, userId, true);
142     }
143
144     private Response createOrUpdate( String data, String serviceId, HttpServletRequest request, String userId, boolean isUpdate) throws IOException {
145         String url = request.getMethod() + " " + request.getRequestURI();
146         log.debug(START_HANDLE_REQUEST_OF, url);
147
148         User modifier = new User();
149         modifier.setUserId(userId);
150         log.debug(MODIFIER_ID_IS, userId);
151
152         Response response;
153
154         try {
155             String serviceIdLower = serviceId.toLowerCase();
156
157             Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
158             if (convertResponse.isRight()) {
159                 log.debug("failed to parse service");
160                 response = buildErrorResponse(convertResponse.right().value());
161                 return response;
162             }
163             Service updatedService = convertResponse.left().value();
164             Service actionResponse ;
165             if (isUpdate) {
166                 actionResponse = serviceBusinessLogic.updateForwardingPath(serviceIdLower, updatedService, modifier, true);
167             } else {
168                 actionResponse = serviceBusinessLogic.createForwardingPath(serviceIdLower, updatedService, modifier, true);
169             }
170
171             Service service = actionResponse;
172             Object result = RepresentationUtils.toRepresentation(service);
173             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
174
175         } catch (IOException e) {
176             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Forward Path Creation or update");
177             log.debug("create or update forwarding path with an error", e);
178             throw e;
179         }
180     }
181
182     @GET
183     @Consumes(MediaType.APPLICATION_JSON)
184     @Produces(MediaType.APPLICATION_JSON)
185     @Path("/{forwardingPathId}")
186     @Operation(description = "Get Forwarding Path", method = "GET", summary = "GET Forwarding Path", responses = {
187             @ApiResponse(content = @Content(
188                     array = @ArraySchema(schema = @Schema(implementation = ForwardingPathDataDefinition.class)))),
189             @ApiResponse(responseCode = "201", description = "Get Forwarding Path"),
190             @ApiResponse(responseCode = "403", description = "Restricted operation"),
191             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
192             @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
193     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
194     public Response getForwardingPath(
195             @Parameter(description = "Forwarding Path to create", required = true) String datax,
196             @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
197             @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
198             @Context final HttpServletRequest request,
199             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
200         String url = request.getMethod() + " " + request.getRequestURI();
201         log.debug(START_HANDLE_REQUEST_OF, url);
202
203         User modifier = new User();
204         modifier.setUserId(userId);
205         log.debug(MODIFIER_ID_IS, userId);
206
207
208         try {
209             Either<UiComponentDataTransfer, ResponseFormat> serviceResponse = serviceBusinessLogic.getComponentDataFilteredByParams(serviceId, modifier, Collections.singletonList(ComponentFieldsEnum.FORWARDING_PATHS.getValue()));
210             if (serviceResponse.isRight()) {
211                 return buildErrorResponse(serviceResponse.right().value());
212             }
213
214             UiServiceDataTransfer uiServiceDataTransfer = (UiServiceDataTransfer) serviceResponse.left().value();
215
216             ForwardingPathDataDefinition forwardingPathDataDefinition = new ForwardingPathDataDefinition();
217             if (!MapUtils.isEmpty(uiServiceDataTransfer.getForwardingPaths())) {
218                 forwardingPathDataDefinition = uiServiceDataTransfer.getForwardingPaths().get(forwardingPathId);
219             }
220             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(forwardingPathDataDefinition));
221
222
223         } catch (Exception e) {
224             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
225             log.debug("update service metadata failed with exception", e);
226             throw e;
227         }
228     }
229
230     @DELETE
231     @Consumes(MediaType.APPLICATION_JSON)
232     @Produces(MediaType.APPLICATION_JSON)
233     @Path("/{forwardingPathId}")
234     @Operation(description = "Delete Forwarding Path", method = "DELETE", summary = "Delete Forwarding Path",
235             responses = {@ApiResponse(
236                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
237                     @ApiResponse(responseCode = "201", description = "Delete Forwarding Path"),
238                     @ApiResponse(responseCode = "403", description = "Restricted operation"),
239                     @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
240                     @ApiResponse(responseCode = "409", description = "Forwarding Path already exist")})
241     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
242     public Response deleteForwardingPath(
243             @Parameter(description = "Forwarding Path Id") @PathParam("forwardingPathId") String forwardingPathId,
244             @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId,
245             @Context final HttpServletRequest request,
246             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
247         String url = request.getMethod() + " " + request.getRequestURI();
248         log.debug(START_HANDLE_REQUEST_OF, url);
249
250         User modifier = new User();
251         modifier.setUserId(userId);
252         log.debug(MODIFIER_ID_IS, userId);
253
254         Response response;
255
256         try {
257             String serviceIdLower = serviceId.toLowerCase();
258
259             Set<String> deletedPaths = serviceBusinessLogic.deleteForwardingPaths(serviceIdLower, Sets.newHashSet(forwardingPathId), modifier, true);
260             Object result = RepresentationUtils.toRepresentation(deletedPaths);
261             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
262
263         } catch (IOException e) {
264             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete forward paths");
265             log.debug("Delete service paths with an error", e);
266             throw e;
267         }
268     }
269
270
271     private Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
272         return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);//TODO: change sSERVICE constant
273     }
274 }