Publish swagger files for SDC APIs
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ServiceServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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.fasterxml.jackson.core.JsonProcessingException;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.google.gson.reflect.TypeToken;
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 java.io.File;
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import java.lang.reflect.Type;
41 import java.util.ArrayList;
42 import java.util.List;
43 import java.util.Map;
44 import javax.inject.Inject;
45 import javax.servlet.ServletContext;
46 import javax.servlet.http.HttpServletRequest;
47 import javax.ws.rs.Consumes;
48 import javax.ws.rs.DELETE;
49 import javax.ws.rs.GET;
50 import javax.ws.rs.HeaderParam;
51 import javax.ws.rs.POST;
52 import javax.ws.rs.PUT;
53 import javax.ws.rs.Path;
54 import javax.ws.rs.PathParam;
55 import javax.ws.rs.Produces;
56 import javax.ws.rs.core.Context;
57 import javax.ws.rs.core.MediaType;
58 import javax.ws.rs.core.Response;
59 import org.apache.http.HttpStatus;
60 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
61 import org.glassfish.jersey.media.multipart.FormDataParam;
62 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
63 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
64 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
65 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
66 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
67 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
68 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
69 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
70 import org.openecomp.sdc.be.config.BeEcompErrorManager;
71 import org.openecomp.sdc.be.dao.api.ActionStatus;
72 import org.openecomp.sdc.be.datamodel.ServiceRelations;
73 import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
74 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
75 import org.openecomp.sdc.be.impl.ComponentsUtils;
76 import org.openecomp.sdc.be.impl.ServletUtils;
77 import org.openecomp.sdc.be.model.Component;
78 import org.openecomp.sdc.be.model.DistributionStatusEnum;
79 import org.openecomp.sdc.be.model.GroupInstanceProperty;
80 import org.openecomp.sdc.be.model.Resource;
81 import org.openecomp.sdc.be.model.Service;
82 import org.openecomp.sdc.be.model.UploadServiceInfo;
83 import org.openecomp.sdc.be.model.User;
84 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
85 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
86 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
87 import org.openecomp.sdc.be.servlets.ServiceUploadServlet.ServiceAuthorityTypeEnum;
88 import org.openecomp.sdc.be.user.UserBusinessLogic;
89 import org.openecomp.sdc.common.api.Constants;
90 import org.openecomp.sdc.common.datastructure.Wrapper;
91 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
92 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
93 import org.openecomp.sdc.common.log.enums.StatusCode;
94 import org.openecomp.sdc.common.log.wrappers.Logger;
95 import org.openecomp.sdc.common.zip.exception.ZipException;
96 import org.openecomp.sdc.exception.ResponseFormat;
97 import org.springframework.stereotype.Controller;
98
99 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
100 @Path("/v1/catalog")
101 @Servers({@Server(url = "/sdc2/rest")})
102 @Controller
103 public class ServiceServlet extends AbstractValidationsServlet {
104
105     private static final Logger log = Logger.getLogger(ServiceServlet.class);
106     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceServlet.class.getName());
107     private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
108     private static final String MODIFIER_ID_IS = "modifier id is {}";
109     private final ElementBusinessLogic elementBusinessLogic;
110     private final ServiceBusinessLogic serviceBusinessLogic;
111
112     @Inject
113     public ServiceServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
114                           ServletUtils servletUtils, ResourceImportManager resourceImportManager, ServiceBusinessLogic serviceBusinessLogic,
115                           ResourceBusinessLogic resourceBusinessLogic, ElementBusinessLogic elementBusinessLogic) {
116         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
117         this.serviceBusinessLogic = serviceBusinessLogic;
118         this.elementBusinessLogic = elementBusinessLogic;
119     }
120
121     @POST
122     @Path("/services")
123     @Tags({@Tag(name = "SDCE-2 APIs")})
124     @Consumes(MediaType.APPLICATION_JSON)
125     @Produces(MediaType.APPLICATION_JSON)
126     @Operation(description = "Create Service", method = "POST", summary = "Returns created service", responses = {
127         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
128         @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
129         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
130         @ApiResponse(responseCode = "409", description = "Service already exist")})
131     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
132     public Response createService(@Parameter(description = "Service object to be created", required = true) String data,
133                                   @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
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         loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, StatusCode.STARTED, "Starting to create a service by user {} ", userId);
140         validateNotEmptyBody(data);
141         Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
142         if (convertResponse.isRight()) {
143             throw new ByResponseFormatComponentException(convertResponse.right().value());
144         }
145         Service service = convertResponse.left().value();
146         Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);
147         if (actionResponse.isRight()) {
148             log.debug("Failed to create service");
149             throw new ByResponseFormatComponentException(actionResponse.right().value());
150         }
151         loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
152             "Service {} has been created by user {} ", service.getName(), userId);
153         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
154     }
155
156     public Either<Service, ResponseFormat> parseToService(String serviceJson, User user) {
157         return getComponentsUtils()
158             .convertJsonToObjectUsingObjectMapper(serviceJson, user, Service.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);
159     }
160
161     @GET
162     @Path("/services/validate-name/{serviceName}")
163     @Tags({@Tag(name = "SDCE-2 APIs")})
164     @Consumes(MediaType.APPLICATION_JSON)
165     @Produces(MediaType.APPLICATION_JSON)
166     @Operation(description = "validate service name", method = "GET", summary = "checks if the chosen service name is available ", responses = {
167         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
168         @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")})
169     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
170     public Response validateServiceName(@PathParam("serviceName") final String serviceName, @Context final HttpServletRequest request,
171                                         @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
172         String url = request.getMethod() + " " + request.getRequestURI();
173         log.debug(START_HANDLE_REQUEST_OF, url);
174         // get modifier id
175         User modifier = new User();
176         modifier.setUserId(userId);
177         log.debug(MODIFIER_ID_IS, userId);
178         try {
179             Either<Map<String, Boolean>, ResponseFormat> actionResponse = serviceBusinessLogic.validateServiceNameExists(serviceName, userId);
180             if (actionResponse.isRight()) {
181                 log.debug("failed to get validate service name");
182                 return buildErrorResponse(actionResponse.right().value());
183             }
184             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
185         } catch (Exception e) {
186             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
187             log.debug("validate service name failed with exception", e);
188             throw e;
189         }
190     }
191
192     @GET
193     @Path("/audit-records/{componentType}/{componentUniqueId}")
194     @Tags({@Tag(name = "SDCE-2 APIs")})
195     @Consumes(MediaType.APPLICATION_JSON)
196     @Produces(MediaType.APPLICATION_JSON)
197     @Operation(description = "get component audit records", method = "GET", summary = "get audit records for a service or a resource", responses = {
198         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
199         @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation")})
200     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
201     public Response getComponentAuditRecords(@PathParam("componentType") final String componentType,
202                                              @PathParam("componentUniqueId") final String componentUniqueId,
203                                              @Context final HttpServletRequest request,
204                                              @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
205         init();
206         ServletContext context = request.getSession().getServletContext();
207         String url = request.getMethod() + " " + request.getRequestURI();
208         log.debug(START_HANDLE_REQUEST_OF, url);
209         User modifier = new User();
210         modifier.setUserId(userId);
211         log.debug(MODIFIER_ID_IS, userId);
212         Wrapper<Response> responseWrapper = new Wrapper<>();
213         Wrapper<String> uuidWrapper = new Wrapper<>();
214         Wrapper<String> versionWrapper = new Wrapper<>();
215         Wrapper<User> userWrapper = new Wrapper<>();
216         try {
217             validateUserExist(responseWrapper, userWrapper, userId);
218             if (responseWrapper.isEmpty()) {
219                 fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), validateComponentType(componentType),
220                     componentUniqueId, context);
221             }
222             if (responseWrapper.isEmpty()) {
223                 Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = serviceBusinessLogic
224                     .getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId);
225                 if (eitherServiceAudit.isRight()) {
226                     Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value());
227                     responseWrapper.setInnerElement(errorResponse);
228                 } else {
229                     List<Map<String, Object>> auditRecords = eitherServiceAudit.left().value();
230                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords);
231                     responseWrapper.setInnerElement(okResponse);
232                 }
233             }
234         } catch (Exception e) {
235             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
236             log.debug("get Service Audit Records failed with exception", e);
237             throw e;
238         }
239         return responseWrapper.getInnerElement();
240     }
241
242     private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user,
243                                     final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) {
244         if (componentTypeEnum == ComponentTypeEnum.RESOURCE) {
245             Either<Resource, ResponseFormat> eitherResource = getResourceBL(context).getResource(componentUniqueId, user);
246             if (eitherResource.isLeft()) {
247                 uuidWrapper.setInnerElement(eitherResource.left().value().getUUID());
248                 versionWrapper.setInnerElement(eitherResource.left().value().getVersion());
249             } else {
250                 responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value()));
251             }
252         } else {
253             Either<Service, ResponseFormat> eitherService = getServiceBL(context).getService(componentUniqueId, user);
254             if (eitherService.isLeft()) {
255                 uuidWrapper.setInnerElement(eitherService.left().value().getUUID());
256                 versionWrapper.setInnerElement(eitherService.left().value().getVersion());
257             } else {
258                 responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value()));
259             }
260         }
261     }
262
263     @DELETE
264     @Path("/services/{serviceId}")
265     @Tags({@Tag(name = "SDCE-2 APIs")})
266     @Operation(description = "Delete Service", method = "DELETE", summary = "Return no content", responses = {
267         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
268         @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
269         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
270         @ApiResponse(responseCode = "404", description = "Service not found")})
271     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
272     public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) {
273         ServletContext context = request.getSession().getServletContext();
274         String url = request.getMethod() + " " + request.getRequestURI();
275         log.debug(START_HANDLE_REQUEST_OF, url);
276         // get modifier id
277         String userId = request.getHeader(Constants.USER_ID_HEADER);
278         User modifier = new User();
279         modifier.setUserId(userId);
280         log.debug(MODIFIER_ID_IS, userId);
281         try {
282             String serviceIdLower = serviceId.toLowerCase();
283             loggerSupportability
284                 .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.STARTED, "Starting to delete service {} by user {} ", serviceIdLower,
285                     userId);
286             ServiceBusinessLogic businessLogic = getServiceBL(context);
287             ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier);
288             if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
289                 log.debug("failed to delete service");
290                 return buildErrorResponse(actionResponse);
291             }
292             loggerSupportability
293                 .log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.COMPLETE, "Ended deleting service {} by user {}", serviceIdLower, userId);
294             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
295         } catch (Exception e) {
296             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
297             log.debug("delete service failed with exception", e);
298             throw e;
299         }
300     }
301
302     @DELETE
303     @Path("/services/{serviceName}/{version}")
304     @Tags({@Tag(name = "SDCE-2 APIs")})
305     @Operation(description = "Delete Service By Name And Version", method = "DELETE", summary = "Returns no content", responses = {
306         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
307         @ApiResponse(responseCode = "204", description = "Service deleted"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
308         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
309         @ApiResponse(responseCode = "404", description = "Service not found")})
310     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
311     public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName, @PathParam("version") final String version,
312                                                   @Context final HttpServletRequest request) {
313         User modifier = getUser(request);
314         try {
315             ResponseFormat actionResponse = serviceBusinessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier);
316             if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
317                 log.debug("failed to delete service");
318                 return buildErrorResponse(actionResponse);
319             }
320             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
321         } catch (Exception e) {
322             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
323             log.debug("delete service failed with exception", e);
324             throw e;
325         }
326     }
327
328     private User getUser(HttpServletRequest request) {
329         String url = request.getMethod() + " " + request.getRequestURI();
330         log.debug(START_HANDLE_REQUEST_OF, url);
331         // get modifier id
332         String userId = request.getHeader(Constants.USER_ID_HEADER);
333         User modifier = new User();
334         modifier.setUserId(userId);
335         log.debug(MODIFIER_ID_IS, userId);
336         return modifier;
337     }
338
339     @PUT
340     @Path("/services/{serviceId}/metadata")
341     @Tags({@Tag(name = "SDCE-2 APIs")})
342     @Consumes(MediaType.APPLICATION_JSON)
343     @Produces(MediaType.APPLICATION_JSON)
344     @Operation(description = "Update Service Metadata", method = "PUT", summary = "Returns updated service", responses = {
345         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
346         @ApiResponse(responseCode = "200", description = "Service Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
347         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
348     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
349     public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId,
350                                           @Parameter(description = "Service object to be Updated", required = true) String data,
351                                           @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
352         throws IOException {
353         String url = request.getMethod() + " " + request.getRequestURI();
354         log.debug(START_HANDLE_REQUEST_OF, url);
355         User modifier = new User();
356         modifier.setUserId(userId);
357         log.debug(MODIFIER_ID_IS, userId);
358         try {
359             String serviceIdLower = serviceId.toLowerCase();
360             Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
361             if (convertResponse.isRight()) {
362                 log.debug("failed to parse service");
363                 return buildErrorResponse(convertResponse.right().value());
364             }
365             Service updatedService = convertResponse.left().value();
366             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier);
367             if (actionResponse.isRight()) {
368                 log.debug("failed to update service");
369                 return buildErrorResponse(actionResponse.right().value());
370             }
371             Service service = actionResponse.left().value();
372             Object result = RepresentationUtils.toRepresentation(service);
373             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
374         } catch (Exception e) {
375             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
376             log.debug("update service metadata failed with exception", e);
377             throw e;
378         }
379     }
380
381     /**
382      * updates group instance property values Note, than in case of group instance updated successfully, related resourceInstance and containing
383      * component modification time will be updated
384      *
385      * @param serviceId
386      * @param componentInstanceId
387      * @param groupInstanceId
388      * @param data
389      * @param request
390      * @param userId
391      * @return
392      */
393     @PUT
394     @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")
395     @Tags({@Tag(name = "SDCE-2 APIs")})
396     @Consumes(MediaType.APPLICATION_JSON)
397     @Produces(MediaType.APPLICATION_JSON)
398     @Operation(description = "Update Group Instance Property Values", method = "PUT", summary = "Returns updated group instance", responses = {
399         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
400         @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"),
401         @ApiResponse(responseCode = "403", description = "Restricted operation"),
402         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
403     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
404     public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,
405                                                       @PathParam("componentInstanceId") final String componentInstanceId,
406                                                       @PathParam("groupInstanceId") final String groupInstanceId,
407                                                       @Parameter(description = "Group instance object to be Updated", required = true) String data,
408                                                       @Context final HttpServletRequest request,
409                                                       @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws JsonProcessingException {
410         String url = request.getMethod() + " " + request.getRequestURI();
411         log.debug(START_HANDLE_REQUEST_OF, url);
412         User modifier = new User();
413         modifier.setUserId(userId);
414         log.debug(MODIFIER_ID_IS, userId);
415         Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;
416         try {
417             List<GroupInstanceProperty> updatedProperties;
418             Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>() {
419             }.getType();
420             ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);
421             if (newProperties == null) {
422                 actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
423             }
424             if (actionResponse == null) {
425                 log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
426                 actionResponse = serviceBusinessLogic
427                     .updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
428                 if (actionResponse.isRight()) {
429                     actionResponse = Either.right(actionResponse.right().value());
430                 }
431             }
432             if (actionResponse.isLeft()) {
433                 updatedProperties = actionResponse.left().value();
434                 ObjectMapper mapper = new ObjectMapper();
435                 String result = mapper.writeValueAsString(updatedProperties);
436                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
437             } else {
438                 return buildErrorResponse(actionResponse.right().value());
439             }
440         } catch (Exception e) {
441             log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
442             throw e;
443         }
444     }
445
446     @GET
447     @Path("/services/{serviceId}")
448     @Tags({@Tag(name = "SDCE-2 APIs")})
449     @Consumes(MediaType.APPLICATION_JSON)
450     @Produces(MediaType.APPLICATION_JSON)
451     @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId", responses = {
452         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
453         @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
454         @ApiResponse(responseCode = "404", description = "Service not found")})
455     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
456     public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
457                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
458         String url = request.getMethod() + " " + request.getRequestURI();
459         log.debug(START_HANDLE_REQUEST_OF, url);
460         // get modifier id
461         User modifier = new User();
462         modifier.setUserId(userId);
463         log.debug(MODIFIER_ID_IS, userId);
464         try {
465             String serviceIdLower = serviceId.toLowerCase();
466             log.debug("get service with id {}", serviceId);
467             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getService(serviceIdLower, modifier);
468             if (actionResponse.isRight()) {
469                 log.debug("failed to get service");
470                 return buildErrorResponse(actionResponse.right().value());
471             }
472             Service service = actionResponse.left().value();
473             Object result = RepresentationUtils.toRepresentation(service);
474             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
475         } catch (Exception e) {
476             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
477             log.debug("get service failed with exception", e);
478             throw e;
479         }
480     }
481
482     @GET
483     @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}")
484     @Tags({@Tag(name = "SDCE-2 APIs")})
485     @Consumes(MediaType.APPLICATION_JSON)
486     @Produces(MediaType.APPLICATION_JSON)
487     @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to name and version", responses = {
488         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
489         @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
490         @ApiResponse(responseCode = "404", description = "Service not found")})
491     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
492     public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,
493                                                @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
494                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
495         // get modifier id
496         User modifier = new User();
497         modifier.setUserId(userId);
498         log.debug(MODIFIER_ID_IS, userId);
499         try {
500             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId);
501             if (actionResponse.isRight()) {
502                 return buildErrorResponse(actionResponse.right().value());
503             }
504             Service service = actionResponse.left().value();
505             Object result = RepresentationUtils.toRepresentation(service);
506             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
507         } catch (Exception e) {
508             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
509             log.debug("get service failed with exception", e);
510             throw e;
511         }
512     }
513
514     @POST
515     @Path("/services/{serviceId}/distribution/{env}/activate")
516     @Tags({@Tag(name = "SDCE-5 APIs")})
517     @Consumes(MediaType.APPLICATION_JSON)
518     @Produces(MediaType.APPLICATION_JSON)
519     @Operation(description = "Activate distribution", method = "POST", summary = "activate distribution", responses = {
520         @ApiResponse(responseCode = "200", description = "OK"),
521         @ApiResponse(responseCode = "409", description = "Service cannot be distributed due to missing deployment artifacts"),
522         @ApiResponse(responseCode = "404", description = "Requested service was not found"),
523         @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
524     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
525     public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env,
526                                          @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
527         throws IOException {
528         String url = request.getMethod() + " " + request.getRequestURI();
529         log.debug(START_HANDLE_REQUEST_OF, url);
530         User modifier = new User();
531         modifier.setUserId(userId);
532         log.debug(MODIFIER_ID_IS, userId);
533         Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.activateDistribution(serviceId, env, modifier, request);
534         if (distResponse.isRight()) {
535             log.debug("failed to activate service distribution");
536             return buildErrorResponse(distResponse.right().value());
537         }
538         Service service = distResponse.left().value();
539         Object result = null;
540         try {
541             result = RepresentationUtils.toRepresentation(service);
542         } catch (IOException e) {
543             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
544             log.debug("activate distribution failed with exception", e);
545             throw e;
546         }
547         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
548     }
549
550     @POST
551     @Path("/services/{serviceId}/distribution/{did}/markDeployed")
552     @Tags({@Tag(name = "SDCE-5 APIs")})
553     @Consumes(MediaType.APPLICATION_JSON)
554     @Produces(MediaType.APPLICATION_JSON)
555     @Operation(description = "Mark distribution as deployed", method = "POST", summary = "relevant audit record will be created", responses = {
556         @ApiResponse(responseCode = "200", description = "Service was marked as deployed"),
557         @ApiResponse(responseCode = "409", description = "Restricted operation"),
558         @ApiResponse(responseCode = "403", description = "Service is not available"),
559         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
560         @ApiResponse(responseCode = "404", description = "Requested service was not found"),
561         @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
562     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
563     public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did,
564                                                @Context final HttpServletRequest request,
565                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
566         String url = request.getMethod() + " " + request.getRequestURI();
567         log.debug(START_HANDLE_REQUEST_OF, url);
568         User modifier = new User();
569         modifier.setUserId(userId);
570         log.debug(MODIFIER_ID_IS, userId);
571         try {
572             Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.markDistributionAsDeployed(serviceId, did, modifier);
573             if (distResponse.isRight()) {
574                 log.debug("failed to mark distribution as deployed");
575                 return buildErrorResponse(distResponse.right().value());
576             }
577             Service service = distResponse.left().value();
578             Object result = RepresentationUtils.toRepresentation(service);
579             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
580         } catch (Exception e) {
581             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");
582             log.debug("mark distribution as deployed failed with exception", e);
583             throw e;
584         }
585     }
586
587     @POST
588     @Path("/services/{serviceId}/tempUrlToBeDeleted")
589     @Tags({@Tag(name = "SDCE-2 APIs")})
590     @Consumes(MediaType.APPLICATION_JSON)
591     @Produces(MediaType.APPLICATION_JSON)
592     @Operation(responses = {@ApiResponse(responseCode = "200", description = "OK"),
593         @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
594     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
595     public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
596                                        @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
597         ServletContext context = request.getSession().getServletContext();
598         String url = request.getMethod() + " " + request.getRequestURI();
599         log.debug(START_HANDLE_REQUEST_OF, url);
600         User modifier = new User();
601         modifier.setUserId(userId);
602         log.debug(MODIFIER_ID_IS, userId);
603         try {
604             Service service = (serviceBusinessLogic.getService(serviceId, modifier)).left().value();
605             Either<Service, ResponseFormat> res = serviceBusinessLogic
606                 .updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
607             if (res.isRight()) {
608                 buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
609             }
610             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
611         } catch (Exception e) {
612             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");
613             log.debug("failed with exception", e);
614             throw e;
615         }
616     }
617
618     @GET
619     @Path("/services/{serviceId}/linksMap")
620     @Tags({@Tag(name = "SDCE-2 APIs")})
621     @Consumes(MediaType.APPLICATION_JSON)
622     @Produces(MediaType.APPLICATION_JSON)
623     @Operation(description = "Retrieve Service component relations map", method = "GET", summary = "Returns service components relations", responses = {
624         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))),
625         @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
626         @ApiResponse(responseCode = "404", description = "Service not found")})
627     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
628     public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
629                                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
630         String url = request.getMethod() + " " + request.getRequestURI();
631         log.debug(START_HANDLE_REQUEST_OF, url);
632         // get modifier id
633         User modifier = new User();
634         modifier.setUserId(userId);
635         log.debug(MODIFIER_ID_IS, userId);
636         try {
637             String serviceIdLower = serviceId.toLowerCase();
638             log.debug("get service components relations with id {}", serviceId);
639             Either<ServiceRelations, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceComponentsRelations(serviceIdLower, modifier);
640             if (actionResponse.isRight()) {
641                 log.debug("failed to get service relations data");
642                 return buildErrorResponse(actionResponse.right().value());
643             }
644             ServiceRelations serviceRelations = actionResponse.left().value();
645             Object result = RepresentationUtils.toRepresentation(serviceRelations);
646             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
647         } catch (Exception e) {
648             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
649             log.debug("get service relations data failed with exception", e);
650             throw e;
651         }
652     }
653
654     @POST
655     @Path("/services/importService")
656     @Tags({@Tag(name = "SDCE-2 APIs")})
657     @Consumes(MediaType.APPLICATION_JSON)
658     @Produces(MediaType.APPLICATION_JSON)
659     @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
660         @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
661         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
662         @ApiResponse(responseCode = "409", description = "Service already exist")})
663     public Response importNsService(@Parameter(description = "Service object to be imported", required = true) String data,
664                                     @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
665         userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
666         initSpringFromContext();
667         String url = request.getMethod() + " " + request.getRequestURI();
668         log.debug("Start handle request of {}", url);
669         // get modifier id
670         User modifier = new User();
671         modifier.setUserId(userId);
672         log.debug("modifier id is {}", userId);
673         Response response;
674         try {
675             Wrapper<Response> responseWrapper = new Wrapper<>();
676             performUIImport(responseWrapper, data, request, userId, null);
677             return responseWrapper.getInnerElement();
678         } catch (IOException | ZipException e) {
679             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service");
680             log.debug("import service failed with exception", e);
681             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
682             return response;
683         }
684     }
685
686     private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId,
687                                  String ServiceUniqueId) throws FileNotFoundException, ZipException {
688         Wrapper<User> userWrapper = new Wrapper<>();
689         Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
690         Wrapper<String> yamlStringWrapper = new Wrapper<>();
691         ServiceAuthorityTypeEnum ServiceAuthorityEnum = ServiceAuthorityTypeEnum.USER_TYPE_UI;
692         commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, ServiceAuthorityEnum, userId, data);
693         specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request,
694             data, ServiceAuthorityEnum);
695         if (responseWrapper.isEmpty()) {
696             handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(),
697                 yamlStringWrapper.getInnerElement(), ServiceAuthorityEnum, true, ServiceUniqueId);
698         }
699     }
700
701     /**
702      * import ReplaceService
703      *
704      * @param userId
705      * @param requestId
706      * @param instanceIdHeader
707      * @param accept
708      * @param authorization
709      * @param request
710      * @param file
711      * @param contentDispositionHeader
712      * @param serviceInfoJsonString
713      * @param uuid
714      * @return
715      */
716     @POST
717     @Path("/services/serviceUUID/{uuid}/importReplaceService")
718     @Tags({@Tag(name = "SDCE-2 APIs")})
719     @Produces(MediaType.APPLICATION_JSON)
720     @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
721         @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
722         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
723         @ApiResponse(responseCode = "409", description = "Service already exist")})
724     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
725     public Response importReplaceService(
726         @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
727         @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
728         @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
729         @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
730         @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
731         @Context final HttpServletRequest request, @Parameter(description = "FileInputStream") @FormDataParam("serviceZip") File file,
732         @Parameter(description = "ContentDisposition") @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader,
733         @Parameter(description = "serviceMetadata") @FormDataParam("serviceZipMetadata") String serviceInfoJsonString,
734         @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) {
735         initSpringFromContext();
736         String requestURI = request.getRequestURI();
737         String url = request.getMethod() + " " + requestURI;
738         log.debug("importReplaceService,Start handle request of {}", url);
739         // get modifier id
740         User modifier = new User();
741         modifier.setUserId(userId);
742         log.debug("importReplaceService,modifier id is {}", userId);
743         log.debug("importReplaceService,get file:{},fileName:{}", file, file.getName());
744         Response response;
745         ResponseFormat responseFormat = null;
746         AuditingActionEnum auditingActionEnum = AuditingActionEnum.Import_Replace_Service;
747         String assetType = "services";
748         Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
749             .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
750         if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
751             log.debug("getServiceAbstractStatus: Service Fetching Failed");
752             throw new ByResponseFormatComponentException(assetTypeData.right().value());
753         }
754         log.debug("getServiceAbstractStatus: Service Fetching Success");
755         Service oldService = (Service) assetTypeData.left().value().get(0);
756         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
757         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
758         DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
759         // Mandatory
760         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
761             log.debug("importReplaceService: Missing X-ECOMP-InstanceID header");
762             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
763             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, null);
764             return buildErrorResponse(responseFormat);
765         }
766         try {
767             Wrapper<Response> responseWrapper = new Wrapper<>();
768             // file import
769             Wrapper<User> userWrapper = new Wrapper<>();
770             Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
771             Wrapper<String> yamlStringWrapper = new Wrapper<>();
772             ServiceUploadServlet.ServiceAuthorityTypeEnum serviceAuthorityEnum = ServiceUploadServlet.ServiceAuthorityTypeEnum.CSAR_TYPE_BE;
773             // PayLoad Validations
774             commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityEnum, userId,
775                 serviceInfoJsonString);
776             fillServicePayload(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, modifier, serviceInfoJsonString, serviceAuthorityEnum,
777                 file);
778             specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request,
779                 serviceInfoJsonString, serviceAuthorityEnum);
780             log.debug("importReplaceService:get payload:{}", uploadServiceInfoWrapper.getInnerElement().getPayloadData());
781             ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) oldService.getComponentMetadataDefinition()
782                 .getMetadataDataDefinition();
783             uploadServiceInfoWrapper.getInnerElement().setServiceVendorModelNumber(serviceMetadataDataDefinition.getServiceVendorModelNumber());
784             uploadServiceInfoWrapper.getInnerElement().setDescription(oldService.getDescription());
785             uploadServiceInfoWrapper.getInnerElement().setCategories(oldService.getCategories());
786             uploadServiceInfoWrapper.getInnerElement().setIcon(oldService.getIcon());
787             uploadServiceInfoWrapper.getInnerElement().setProjectCode(oldService.getProjectCode());
788             if (responseWrapper.isEmpty()) {
789                 log.debug("importReplaceService:start handleImportService");
790                 handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(),
791                     yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null);
792             }
793             return responseWrapper.getInnerElement();
794         } catch (IOException | ZipException e) {
795             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service");
796             log.debug("import service failed with exception", e);
797             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
798             return response;
799         }
800     }
801 }