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