Support for Test Topology Auto Design- Service Import
[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 @Tags({@Tag(name = "SDC Internal APIs")})
104 @Servers({@Server(url = "/sdc2/rest")})
105 @Controller
106 public class ServiceServlet extends AbstractValidationsServlet {
107
108     private final ElementBusinessLogic elementBusinessLogic;
109     private static final Logger log = Logger.getLogger(ServiceServlet.class);
110     private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceServlet.class.getName());
111
112     private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
113     private static final String MODIFIER_ID_IS = "modifier id is {}";
114
115     private final ServiceBusinessLogic serviceBusinessLogic;
116
117     @Inject
118     public ServiceServlet(UserBusinessLogic userBusinessLogic,
119         ComponentInstanceBusinessLogic componentInstanceBL,
120         ComponentsUtils componentsUtils, ServletUtils servletUtils,
121         ResourceImportManager resourceImportManager,
122         ServiceBusinessLogic serviceBusinessLogic,
123         ResourceBusinessLogic resourceBusinessLogic, ElementBusinessLogic elementBusinessLogic) {
124         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
125         this.serviceBusinessLogic = serviceBusinessLogic;
126         this.elementBusinessLogic = elementBusinessLogic;
127     }
128
129     @POST
130     @Path("/services")
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     @Consumes(MediaType.APPLICATION_JSON)
176     @Produces(MediaType.APPLICATION_JSON)
177     @Operation(description = "validate service name", method = "GET",
178             summary = "checks if the chosen service name is available ", responses = {
179             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
180             @ApiResponse(responseCode = "200", description = "Service found"),
181             @ApiResponse(responseCode = "403", description = "Restricted operation")})
182     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
183     public Response validateServiceName(@PathParam("serviceName") final String serviceName,
184             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
185         String url = request.getMethod() + " " + request.getRequestURI();
186         log.debug(START_HANDLE_REQUEST_OF, url);
187
188         // get modifier id
189         User modifier = new User();
190         modifier.setUserId(userId);
191         log.debug(MODIFIER_ID_IS, userId);
192         Response response = null;
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                 response = buildErrorResponse(actionResponse.right().value());
200                 return response;
201             }
202             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
203         } catch (Exception e) {
204             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
205             log.debug("validate service name failed with exception", e);
206             throw e;
207         }
208     }
209
210     @GET
211     @Path("/audit-records/{componentType}/{componentUniqueId}")
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     @Operation(description = "Delete Service", method = "DELETE", summary = "Return no content", responses = {
290             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
291             @ApiResponse(responseCode = "204", description = "Service deleted"),
292             @ApiResponse(responseCode = "403", description = "Restricted operation"),
293             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
294             @ApiResponse(responseCode = "404", description = "Service not found")})
295     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
296     public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) {
297         ServletContext context = request.getSession().getServletContext();
298         String url = request.getMethod() + " " + request.getRequestURI();
299         log.debug(START_HANDLE_REQUEST_OF, url);
300
301         // get modifier id
302         String userId = request.getHeader(Constants.USER_ID_HEADER);
303         User modifier = new User();
304         modifier.setUserId(userId);
305         log.debug(MODIFIER_ID_IS, userId);
306         Response response = null;
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                 response = buildErrorResponse(actionResponse);
315                 return response;
316             }
317             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
318             loggerSupportability.log(LoggerSupportabilityActions.DELETE_SERVICE,StatusCode.COMPLETE,"Ended deleting service {} by user {}",serviceIdLower, userId);
319             return response;
320
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     @DELETE
329     @Path("/services/{serviceName}/{version}")
330     @Operation(description = "Delete Service By Name And Version", method = "DELETE", summary = "Returns no content",
331             responses = {@ApiResponse(
332                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
333                     @ApiResponse(responseCode = "204", description = "Service deleted"),
334                     @ApiResponse(responseCode = "403", description = "Restricted operation"),
335                     @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
336                     @ApiResponse(responseCode = "404", description = "Service not found")})
337     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
338     public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,
339                                                   @PathParam("version") final String version,
340                                                   @Context final HttpServletRequest request) {
341         String url = request.getMethod() + " " + request.getRequestURI();
342         log.debug(START_HANDLE_REQUEST_OF, url);
343
344         // get modifier id
345         String userId = request.getHeader(Constants.USER_ID_HEADER);
346         User modifier = new User();
347         modifier.setUserId(userId);
348         log.debug(MODIFIER_ID_IS, userId);
349
350         Response response = null;
351
352         try {
353             ResponseFormat actionResponse = serviceBusinessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier);
354
355             if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
356                 log.debug("failed to delete service");
357                 response = buildErrorResponse(actionResponse);
358                 return response;
359             }
360             response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
361             return response;
362
363         } catch (Exception e) {
364             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
365             log.debug("delete service failed with exception", e);
366             throw e;
367         }
368     }
369
370     @PUT
371     @Path("/services/{serviceId}/metadata")
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         Response response = null;
393
394         try {
395             String serviceIdLower = serviceId.toLowerCase();
396
397             Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
398             if (convertResponse.isRight()) {
399                 log.debug("failed to parse service");
400                 response = buildErrorResponse(convertResponse.right().value());
401                 return response;
402             }
403             Service updatedService = convertResponse.left().value();
404             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier);
405
406             if (actionResponse.isRight()) {
407                 log.debug("failed to update service");
408                 response = buildErrorResponse(actionResponse.right().value());
409                 return response;
410             }
411
412             Service service = actionResponse.left().value();
413             Object result = RepresentationUtils.toRepresentation(service);
414             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
415
416         } catch (Exception e) {
417             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
418             log.debug("update service metadata failed with exception", e);
419             throw e;
420         }
421     }
422     /**
423      * updates group instance property values
424      * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated
425      * @param serviceId
426      * @param componentInstanceId
427      * @param groupInstanceId
428      * @param data
429      * @param request
430      * @param userId
431      * @return
432      */
433     @PUT
434     @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")
435     @Consumes(MediaType.APPLICATION_JSON)
436     @Produces(MediaType.APPLICATION_JSON)
437     @Operation(description = "Update Group Instance Property Values", method = "PUT",
438             summary = "Returns updated group instance", responses = {
439             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
440             @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"),
441             @ApiResponse(responseCode = "403", description = "Restricted operation"),
442             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
443     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
444     public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,
445             @PathParam("componentInstanceId") final String componentInstanceId,
446             @PathParam("groupInstanceId") final String groupInstanceId,
447             @Parameter(description = "Group instance object to be Updated", required = true) String data,
448             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws JsonProcessingException {
449
450         Response response = null;
451         String url = request.getMethod() + " " + request.getRequestURI();
452         log.debug(START_HANDLE_REQUEST_OF, url);
453
454         User modifier = new User();
455         modifier.setUserId(userId);
456         log.debug(MODIFIER_ID_IS,userId);
457
458         Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;
459         try {
460             List<GroupInstanceProperty> updatedProperties;
461             Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType();
462             ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);
463             if (newProperties == null) {
464                 actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
465             }
466             if(actionResponse == null){
467                 log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
468                 actionResponse = serviceBusinessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
469                 if(actionResponse.isRight()){
470                     actionResponse = Either.right(actionResponse.right().value());
471                 }
472             }
473             if(actionResponse.isLeft()){
474                 updatedProperties = actionResponse.left().value();
475                 ObjectMapper mapper = new ObjectMapper();
476                 String result = mapper.writeValueAsString(updatedProperties);
477                 response =  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
478             }
479             else{
480                 response = buildErrorResponse(actionResponse.right().value());
481             }
482         } catch (Exception e) {
483             log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
484             throw e;
485         }
486         return response;
487     }
488
489     @GET
490     @Path("/services/{serviceId}")
491     @Consumes(MediaType.APPLICATION_JSON)
492     @Produces(MediaType.APPLICATION_JSON)
493     @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId",
494             responses = {@ApiResponse(
495                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
496                     @ApiResponse(responseCode = "200", description = "Service found"),
497                     @ApiResponse(responseCode = "403", description = "Restricted operation"),
498                     @ApiResponse(responseCode = "404", description = "Service not found")})
499     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
500     public Response getServiceById(@PathParam("serviceId") final String serviceId,
501             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
502
503         String url = request.getMethod() + " " + request.getRequestURI();
504         log.debug(START_HANDLE_REQUEST_OF, url);
505
506         // get modifier id
507         User modifier = new User();
508         modifier.setUserId(userId);
509         log.debug(MODIFIER_ID_IS, userId);
510
511         Response response = null;
512         try {
513             String serviceIdLower = serviceId.toLowerCase();
514             log.debug("get service with id {}", serviceId);
515             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getService(serviceIdLower, modifier);
516
517             if (actionResponse.isRight()) {
518                 log.debug("failed to get service");
519                 response = buildErrorResponse(actionResponse.right().value());
520                 return response;
521             }
522
523             Service service = actionResponse.left().value();
524             Object result = RepresentationUtils.toRepresentation(service);
525
526             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
527
528         } catch (Exception e) {
529             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
530             log.debug("get service failed with exception", e);
531             throw e;
532         }
533     }
534
535     @GET
536     @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}")
537     @Consumes(MediaType.APPLICATION_JSON)
538     @Produces(MediaType.APPLICATION_JSON)
539     @Operation(description = "Retrieve Service", method = "GET",
540             summary = "Returns service according to name and version", responses = {
541             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
542             @ApiResponse(responseCode = "200", description = "Service found"),
543             @ApiResponse(responseCode = "403", description = "Restricted operation"),
544             @ApiResponse(responseCode = "404", description = "Service not found")})
545     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
546     public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,
547             @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
548             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
549
550         // get modifier id
551         User modifier = new User();
552         modifier.setUserId(userId);
553         log.debug(MODIFIER_ID_IS, userId);
554
555         Response response = null;
556         try {
557             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId);
558
559             if (actionResponse.isRight()) {
560                 response = buildErrorResponse(actionResponse.right().value());
561                 return response;
562             }
563
564             Service service = actionResponse.left().value();
565             Object result = RepresentationUtils.toRepresentation(service);
566
567             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
568
569         } catch (Exception e) {
570             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
571             log.debug("get service failed with exception", e);
572             throw e;
573         }
574     }
575
576     @POST
577     @Path("/services/{serviceId}/distribution/{env}/activate")
578     @Consumes(MediaType.APPLICATION_JSON)
579     @Produces(MediaType.APPLICATION_JSON)
580     @Operation(description = "Activate distribution", method = "POST", summary = "activate distribution",
581             responses = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "409",
582                     description = "Service cannot be distributed due to missing deployment artifacts"),
583                     @ApiResponse(responseCode = "404", description = "Requested service was not found"),
584                     @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
585     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
586     public Response activateDistribution(@PathParam("serviceId") final String serviceId,
587             @PathParam("env") final String env, @Context final HttpServletRequest request,
588             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
589
590         String url = request.getMethod() + " " + request.getRequestURI();
591         log.debug(START_HANDLE_REQUEST_OF, url);
592
593         User modifier = new User();
594         modifier.setUserId(userId);
595         log.debug(MODIFIER_ID_IS, userId);
596
597         Response response = null;
598         Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.activateDistribution(serviceId, env, modifier, request);
599
600         if (distResponse.isRight()) {
601             log.debug("failed to activate service distribution");
602             response = buildErrorResponse(distResponse.right().value());
603             return response;
604         }
605         Service service = distResponse.left().value();
606         Object result = null;
607         try {
608             result = RepresentationUtils.toRepresentation(service);
609         } catch (IOException e) {
610             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
611             log.debug("activate distribution failed with exception", e);
612             throw e;
613         }
614         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
615     }
616
617     @POST
618     @Path("/services/{serviceId}/distribution/{did}/markDeployed")
619     @Consumes(MediaType.APPLICATION_JSON)
620     @Produces(MediaType.APPLICATION_JSON)
621     @Operation(description = "Mark distribution as deployed", method = "POST",
622             summary = "relevant audit record will be created",
623             responses = {@ApiResponse(responseCode = "200", description = "Service was marked as deployed"),
624                     @ApiResponse(responseCode = "409", description = "Restricted operation"),
625                     @ApiResponse(responseCode = "403", description = "Service is not available"),
626                     @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
627                     @ApiResponse(responseCode = "404", description = "Requested service was not found"),
628                     @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
629     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
630     public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId,
631             @PathParam("did") final String did, @Context final HttpServletRequest request,
632             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
633
634         String url = request.getMethod() + " " + request.getRequestURI();
635         log.debug(START_HANDLE_REQUEST_OF, url);
636
637         User modifier = new User();
638         modifier.setUserId(userId);
639         log.debug(MODIFIER_ID_IS, userId);
640
641         Response response = null;
642         try {
643             Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.markDistributionAsDeployed(serviceId, did, modifier);
644
645             if (distResponse.isRight()) {
646                 log.debug("failed to mark distribution as deployed");
647                 response = buildErrorResponse(distResponse.right().value());
648                 return response;
649             }
650             Service service = distResponse.left().value();
651             Object result = RepresentationUtils.toRepresentation(service);
652             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
653         } catch (Exception e) {
654             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");
655             log.debug("mark distribution as deployed failed with exception", e);
656             throw e;
657         }
658     }
659
660     @POST
661     @Path("/services/{serviceId}/tempUrlToBeDeleted")
662     @Consumes(MediaType.APPLICATION_JSON)
663     @Produces(MediaType.APPLICATION_JSON)
664     @Operation(responses = {@ApiResponse(responseCode = "200", description = "OK"),
665             @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
666     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
667     public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
668
669         ServletContext context = request.getSession().getServletContext();
670         String url = request.getMethod() + " " + request.getRequestURI();
671         log.debug(START_HANDLE_REQUEST_OF, url);
672
673         User modifier = new User();
674         modifier.setUserId(userId);
675         log.debug(MODIFIER_ID_IS, userId);
676
677         Response response;
678         try {
679             Service service = (serviceBusinessLogic.getService(serviceId, modifier)).left().value();
680             Either<Service, ResponseFormat> res = serviceBusinessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
681
682             if (res.isRight()) {
683                 response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
684             }
685             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
686         } catch (Exception e) {
687             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");
688             log.debug("failed with exception", e);
689             throw e;
690         }
691     }
692
693
694     @GET
695     @Path("/services/{serviceId}/linksMap")
696     @Consumes(MediaType.APPLICATION_JSON)
697     @Produces(MediaType.APPLICATION_JSON)
698     @Operation(description = "Retrieve Service component relations map", method = "GET",
699             summary = "Returns service components relations", responses = {@ApiResponse(
700             content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))),
701             @ApiResponse(responseCode = "200", description = "Service found"),
702             @ApiResponse(responseCode = "403", description = "Restricted operation"),
703             @ApiResponse(responseCode = "404", description = "Service not found")})
704     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
705     public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId,
706                                                    @Context final HttpServletRequest request,
707                                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
708
709         String url = request.getMethod() + " " + request.getRequestURI();
710         log.debug(START_HANDLE_REQUEST_OF, url);
711
712         // get modifier id
713         User modifier = new User();
714         modifier.setUserId(userId);
715         log.debug(MODIFIER_ID_IS, userId);
716
717         Response response = null;
718         try {
719             String serviceIdLower = serviceId.toLowerCase();
720             log.debug("get service components relations with id {}", serviceId);
721             Either<ServiceRelations, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceComponentsRelations(serviceIdLower, modifier);
722
723             if (actionResponse.isRight()) {
724                 log.debug("failed to get service relations data");
725                 response = buildErrorResponse(actionResponse.right().value());
726                 return response;
727             }
728
729             ServiceRelations serviceRelations = actionResponse.left().value();
730             Object result = RepresentationUtils.toRepresentation(serviceRelations);
731
732             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
733
734         } catch (Exception e) {
735             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
736             log.debug("get service relations data failed with exception", e);
737             throw e;
738         }
739     }
740
741     @POST
742     @Path("/services/importService")
743     @Consumes(MediaType.APPLICATION_JSON)
744     @Produces(MediaType.APPLICATION_JSON)
745     @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
746     @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")})
747     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) {
748
749         userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
750         initSpringFromContext();
751
752         String url = request.getMethod() + " " + request.getRequestURI();
753         log.debug("Start handle request of {}" , url);
754
755         // get modifier id
756         User modifier = new User();
757         modifier.setUserId(userId);
758         log.debug("modifier id is {}", userId);
759
760         Response response;
761         try {
762
763             Wrapper<Response> responseWrapper = new Wrapper<>();
764             performUIImport(responseWrapper, data, request, userId, null);
765             return responseWrapper.getInnerElement();
766         } catch (IOException | ZipException e) {
767             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service");
768             log.debug("import service failed with exception", e);
769             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
770             return response;
771         }
772     }
773
774     private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId, String ServiceUniqueId)
775         throws FileNotFoundException, ZipException {
776
777         Wrapper<User> userWrapper = new Wrapper<>();
778         Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
779         Wrapper<String> yamlStringWrapper = new Wrapper<>();
780
781         ServiceAuthorityTypeEnum ServiceAuthorityEnum = ServiceAuthorityTypeEnum.USER_TYPE_UI;
782
783         commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, ServiceAuthorityEnum, userId, data);
784
785         specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, data, ServiceAuthorityEnum);
786
787         if (responseWrapper.isEmpty()) {
788             handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), ServiceAuthorityEnum, true, ServiceUniqueId);
789         }
790     }
791
792     /**import ReplaceService 
793      *
794      * @param userId
795      * @param requestId
796      * @param instanceIdHeader
797      * @param accept
798      * @param authorization
799      * @param request
800      * @param file
801      * @param contentDispositionHeader
802      * @param serviceInfoJsonString
803      * @param uuid
804      * @return
805      */
806     @POST
807     @Path("/services/serviceUUID/{uuid}/importReplaceService")
808     @Produces(MediaType.APPLICATION_JSON)
809     @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
810             @ApiResponse(responseCode = "201", description = "Service created"),
811             @ApiResponse(responseCode = "403", description = "Restricted operation"),
812             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
813             @ApiResponse(responseCode = "409", description = "Service already exist")})
814     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
815     public Response importReplaceService(
816             @Parameter(description = "The user id",
817                     required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
818             @Parameter(description = "X-ECOMP-RequestID header",
819                     required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
820             @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
821                     value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
822             @Parameter(description = "Determines the format of the body of the response",
823                     required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
824             @Parameter(description = "The username and password",
825                     required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
826             @Context final HttpServletRequest request,
827             @Parameter(description = "FileInputStream")
828             @FormDataParam("serviceZip") File file,
829             @Parameter(description = "ContentDisposition")
830             @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader,
831             @Parameter(description = "serviceMetadata")
832             @FormDataParam("serviceZipMetadata") String serviceInfoJsonString,
833             @Parameter(description = "The requested asset uuid",
834                     required = true) @PathParam("uuid") final String uuid) {
835
836         initSpringFromContext();
837
838         String requestURI = request.getRequestURI();
839         String url = request.getMethod() + " " + requestURI;
840         log.debug("importReplaceService,Start handle request of {}", url);
841
842         // get modifier id
843         User modifier = new User();
844         modifier.setUserId(userId);
845         log.debug("importReplaceService,modifier id is {}", userId);
846
847         log.debug("importReplaceService,get file:{},fileName:{}",file,file.getName());
848
849         Response response;
850         ResponseFormat responseFormat =null;
851         AuditingActionEnum auditingActionEnum = AuditingActionEnum.Import_Replace_Service;
852         String assetType = "services";
853
854         Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
855
856         if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
857             log.debug("getServiceAbstractStatus: Service Fetching Failed");
858             throw new ByResponseFormatComponentException(assetTypeData.right().value());
859         }
860
861         log.debug("getServiceAbstractStatus: Service Fetching Success");
862
863         Service oldService = (Service) assetTypeData.left().value().get(0);
864
865         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
866         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
867         DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
868         // Mandatory
869         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
870             log.debug("importReplaceService: Missing X-ECOMP-InstanceID header");
871             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
872             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
873                     resourceCommonInfo, requestId, null);
874             return buildErrorResponse(responseFormat);
875         }
876
877         try {
878             Wrapper<Response> responseWrapper = new Wrapper<>();
879             // file import
880             Wrapper<User> userWrapper = new Wrapper<>();
881             Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
882             Wrapper<String> yamlStringWrapper = new Wrapper<>();
883
884             ServiceUploadServlet.ServiceAuthorityTypeEnum serviceAuthorityEnum = ServiceUploadServlet.ServiceAuthorityTypeEnum.CSAR_TYPE_BE;
885
886             // PayLoad Validations
887             commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityEnum, userId, serviceInfoJsonString);
888
889             fillServicePayload(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, modifier, serviceInfoJsonString, serviceAuthorityEnum, file);
890
891             specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, serviceInfoJsonString, serviceAuthorityEnum);
892
893             log.debug("importReplaceService:get payload:{}", uploadServiceInfoWrapper.getInnerElement().getPayloadData());
894
895             ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition)oldService.getComponentMetadataDefinition().getMetadataDataDefinition();
896
897             uploadServiceInfoWrapper.getInnerElement().setServiceVendorModelNumber(serviceMetadataDataDefinition.getServiceVendorModelNumber());
898             uploadServiceInfoWrapper.getInnerElement().setDescription(oldService.getDescription());
899             uploadServiceInfoWrapper.getInnerElement().setCategories(oldService.getCategories());
900             uploadServiceInfoWrapper.getInnerElement().setIcon(oldService.getIcon());
901             uploadServiceInfoWrapper.getInnerElement().setProjectCode(oldService.getProjectCode());
902
903
904             if (responseWrapper.isEmpty()) {
905                 log.debug("importReplaceService:start handleImportService");
906                 handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null);
907             }
908
909             return responseWrapper.getInnerElement();
910         } catch (IOException | ZipException e) {
911             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service");
912             log.debug("import service failed with exception", e);
913             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
914             return response;
915         }
916     }
917 }