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