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