Remove dead code
[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         try {
193             Either<Map<String, Boolean>, ResponseFormat> actionResponse =
194                     serviceBusinessLogic.validateServiceNameExists(serviceName, userId);
195
196             if (actionResponse.isRight()) {
197                 log.debug("failed to get validate service name");
198                 return buildErrorResponse(actionResponse.right().value());
199             }
200             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
201         } catch (Exception e) {
202             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
203             log.debug("validate service name failed with exception", e);
204             throw e;
205         }
206     }
207
208     @GET
209     @Path("/audit-records/{componentType}/{componentUniqueId}")
210     @Consumes(MediaType.APPLICATION_JSON)
211     @Produces(MediaType.APPLICATION_JSON)
212     @Operation(description = "get component audit records", method = "GET",
213             summary = "get audit records for a service or a resource", responses = {
214             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
215             @ApiResponse(responseCode = "200", description = "Service found"),
216             @ApiResponse(responseCode = "403", description = "Restricted operation")})
217     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
218     public Response getComponentAuditRecords(@PathParam("componentType") final String componentType,
219             @PathParam("componentUniqueId") final String componentUniqueId, @Context final HttpServletRequest request,
220             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
221         init();
222         ServletContext context = request.getSession().getServletContext();
223         String url = request.getMethod() + " " + request.getRequestURI();
224         log.debug(START_HANDLE_REQUEST_OF, url);
225
226         User modifier = new User();
227         modifier.setUserId(userId);
228         log.debug(MODIFIER_ID_IS, userId);
229         Wrapper<Response> responseWrapper = new Wrapper<>();
230         Wrapper<String> uuidWrapper = new Wrapper<>();
231         Wrapper<String> versionWrapper = new Wrapper<>();
232         Wrapper<User> userWrapper = new Wrapper<>();
233         try {
234             validateUserExist(responseWrapper, userWrapper, userId);
235
236             if (responseWrapper.isEmpty()) {
237                 fillUUIDAndVersion(responseWrapper, uuidWrapper, versionWrapper, userWrapper.getInnerElement(), validateComponentType(componentType), componentUniqueId, context);
238             }
239
240             if (responseWrapper.isEmpty()) {
241                 Either<List<Map<String, Object>>, ResponseFormat> eitherServiceAudit = serviceBusinessLogic.getComponentAuditRecords(versionWrapper.getInnerElement(), uuidWrapper.getInnerElement(), userId);
242
243                 if (eitherServiceAudit.isRight()) {
244                     Response errorResponse = buildErrorResponse(eitherServiceAudit.right().value());
245                     responseWrapper.setInnerElement(errorResponse);
246                 } else {
247                     List<Map<String, Object>> auditRecords = eitherServiceAudit.left().value();
248                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), auditRecords);
249                     responseWrapper.setInnerElement(okResponse);
250
251                 }
252             }
253
254         } catch (Exception e) {
255             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Validate Service Name");
256             log.debug("get Service Audit Records failed with exception", e);
257             throw e;
258         }
259         return responseWrapper.getInnerElement();
260     }
261
262     private void fillUUIDAndVersion(Wrapper<Response> responseWrapper, Wrapper<String> uuidWrapper, Wrapper<String> versionWrapper, User user, final ComponentTypeEnum componentTypeEnum, final String componentUniqueId, ServletContext context) {
263
264         if (componentTypeEnum == ComponentTypeEnum.RESOURCE) {
265             Either<Resource, ResponseFormat> eitherResource = getResourceBL(context).getResource(componentUniqueId, user);
266             if (eitherResource.isLeft()) {
267                 uuidWrapper.setInnerElement(eitherResource.left().value().getUUID());
268                 versionWrapper.setInnerElement(eitherResource.left().value().getVersion());
269             } else {
270                 responseWrapper.setInnerElement(buildErrorResponse(eitherResource.right().value()));
271             }
272
273         } else {
274             Either<Service, ResponseFormat> eitherService = getServiceBL(context).getService(componentUniqueId, user);
275             if (eitherService.isLeft()) {
276                 uuidWrapper.setInnerElement(eitherService.left().value().getUUID());
277                 versionWrapper.setInnerElement(eitherService.left().value().getVersion());
278             } else {
279                 responseWrapper.setInnerElement(buildErrorResponse(eitherService.right().value()));
280
281             }
282         }
283     }
284
285     @DELETE
286     @Path("/services/{serviceId}")
287     @Operation(description = "Delete Service", method = "DELETE", summary = "Return no content", responses = {
288             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
289             @ApiResponse(responseCode = "204", description = "Service deleted"),
290             @ApiResponse(responseCode = "403", description = "Restricted operation"),
291             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
292             @ApiResponse(responseCode = "404", description = "Service not found")})
293     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
294     public Response deleteService(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request) {
295         ServletContext context = request.getSession().getServletContext();
296         String url = request.getMethod() + " " + request.getRequestURI();
297         log.debug(START_HANDLE_REQUEST_OF, url);
298
299         // get modifier id
300         String userId = request.getHeader(Constants.USER_ID_HEADER);
301         User modifier = new User();
302         modifier.setUserId(userId);
303         log.debug(MODIFIER_ID_IS, userId);
304         try {
305             String serviceIdLower = serviceId.toLowerCase();
306             loggerSupportability.log(LoggerSupportabilityActions.DELETE_SERVICE, StatusCode.STARTED,"Starting to delete service {} by user {} ",serviceIdLower, userId);
307             ServiceBusinessLogic businessLogic = getServiceBL(context);
308             ResponseFormat actionResponse = businessLogic.deleteService(serviceIdLower, modifier);
309             if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
310                 log.debug("failed to delete service");
311                 return buildErrorResponse(actionResponse);
312             }
313             loggerSupportability.log(LoggerSupportabilityActions.DELETE_SERVICE,StatusCode.COMPLETE,"Ended deleting service {} by user {}",serviceIdLower, userId);
314             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
315
316         } catch (Exception e) {
317             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
318             log.debug("delete service failed with exception", e);
319             throw e;
320         }
321     }
322
323     @DELETE
324     @Path("/services/{serviceName}/{version}")
325     @Operation(description = "Delete Service By Name And Version", method = "DELETE", summary = "Returns no content",
326             responses = {@ApiResponse(
327                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))),
328                     @ApiResponse(responseCode = "204", description = "Service deleted"),
329                     @ApiResponse(responseCode = "403", description = "Restricted operation"),
330                     @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
331                     @ApiResponse(responseCode = "404", description = "Service not found")})
332     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
333     public Response deleteServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,
334                                                   @PathParam("version") final String version,
335                                                   @Context final HttpServletRequest request) {
336         User modifier = getUser(request);
337
338         try {
339             ResponseFormat actionResponse = serviceBusinessLogic.deleteServiceByNameAndVersion(serviceName, version, modifier);
340
341             if (actionResponse.getStatus() != HttpStatus.SC_NO_CONTENT) {
342                 log.debug("failed to delete service");
343                 return buildErrorResponse(actionResponse);
344             }
345             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
346         } catch (Exception e) {
347             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Service");
348             log.debug("delete service failed with exception", e);
349             throw e;
350         }
351     }
352
353     private User getUser(HttpServletRequest request) {
354         String url = request.getMethod() + " " + request.getRequestURI();
355         log.debug(START_HANDLE_REQUEST_OF, url);
356
357         // get modifier id
358         String userId = request.getHeader(Constants.USER_ID_HEADER);
359         User modifier = new User();
360         modifier.setUserId(userId);
361         log.debug(MODIFIER_ID_IS, userId);
362         return modifier;
363     }
364
365     @PUT
366     @Path("/services/{serviceId}/metadata")
367     @Consumes(MediaType.APPLICATION_JSON)
368     @Produces(MediaType.APPLICATION_JSON)
369     @Operation(description = "Update Service Metadata", method = "PUT", summary = "Returns updated service",
370             responses = {@ApiResponse(
371                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
372                     @ApiResponse(responseCode = "200", description = "Service Updated"),
373                     @ApiResponse(responseCode = "403", description = "Restricted operation"),
374                     @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
375     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
376     public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId,
377             @Parameter(description = "Service object to be Updated", required = true) String data,
378             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
379
380         String url = request.getMethod() + " " + request.getRequestURI();
381         log.debug(START_HANDLE_REQUEST_OF, url);
382
383         User modifier = new User();
384         modifier.setUserId(userId);
385         log.debug(MODIFIER_ID_IS, userId);
386
387         try {
388             String serviceIdLower = serviceId.toLowerCase();
389
390             Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
391             if (convertResponse.isRight()) {
392                 log.debug("failed to parse service");
393                 return buildErrorResponse(convertResponse.right().value());
394             }
395             Service updatedService = convertResponse.left().value();
396             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier);
397
398             if (actionResponse.isRight()) {
399                 log.debug("failed to update service");
400                 return buildErrorResponse(actionResponse.right().value());
401             }
402
403             Service service = actionResponse.left().value();
404             Object result = RepresentationUtils.toRepresentation(service);
405             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
406
407         } catch (Exception e) {
408             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
409             log.debug("update service metadata failed with exception", e);
410             throw e;
411         }
412     }
413     /**
414      * updates group instance property values
415      * Note, than in case of group instance updated successfully, related resourceInstance and containing component modification time will be updated
416      * @param serviceId
417      * @param componentInstanceId
418      * @param groupInstanceId
419      * @param data
420      * @param request
421      * @param userId
422      * @return
423      */
424     @PUT
425     @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")
426     @Consumes(MediaType.APPLICATION_JSON)
427     @Produces(MediaType.APPLICATION_JSON)
428     @Operation(description = "Update Group Instance Property Values", method = "PUT",
429             summary = "Returns updated group instance", responses = {
430             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
431             @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"),
432             @ApiResponse(responseCode = "403", description = "Restricted operation"),
433             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
434     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
435     public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,
436             @PathParam("componentInstanceId") final String componentInstanceId,
437             @PathParam("groupInstanceId") final String groupInstanceId,
438             @Parameter(description = "Group instance object to be Updated", required = true) String data,
439             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws JsonProcessingException {
440
441         String url = request.getMethod() + " " + request.getRequestURI();
442         log.debug(START_HANDLE_REQUEST_OF, url);
443
444         User modifier = new User();
445         modifier.setUserId(userId);
446         log.debug(MODIFIER_ID_IS,userId);
447
448         Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;
449         try {
450             List<GroupInstanceProperty> updatedProperties;
451             Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>(){}.getType();
452             ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);
453             if (newProperties == null) {
454                 actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
455             }
456             if(actionResponse == null){
457                 log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
458                 actionResponse = serviceBusinessLogic.updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
459                 if(actionResponse.isRight()){
460                     actionResponse = Either.right(actionResponse.right().value());
461                 }
462             }
463             if(actionResponse.isLeft()){
464                 updatedProperties = actionResponse.left().value();
465                 ObjectMapper mapper = new ObjectMapper();
466                 String result = mapper.writeValueAsString(updatedProperties);
467                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
468             }
469             else{
470                 return buildErrorResponse(actionResponse.right().value());
471             }
472         } catch (Exception e) {
473             log.error("Exception occured during update Group Instance property values: {}", e.getMessage(), e);
474             throw e;
475         }
476     }
477
478     @GET
479     @Path("/services/{serviceId}")
480     @Consumes(MediaType.APPLICATION_JSON)
481     @Produces(MediaType.APPLICATION_JSON)
482     @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId",
483             responses = {@ApiResponse(
484                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
485                     @ApiResponse(responseCode = "200", description = "Service found"),
486                     @ApiResponse(responseCode = "403", description = "Restricted operation"),
487                     @ApiResponse(responseCode = "404", description = "Service not found")})
488     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
489     public Response getServiceById(@PathParam("serviceId") final String serviceId,
490             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
491
492         String url = request.getMethod() + " " + request.getRequestURI();
493         log.debug(START_HANDLE_REQUEST_OF, url);
494
495         // get modifier id
496         User modifier = new User();
497         modifier.setUserId(userId);
498         log.debug(MODIFIER_ID_IS, userId);
499
500         try {
501             String serviceIdLower = serviceId.toLowerCase();
502             log.debug("get service with id {}", serviceId);
503             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getService(serviceIdLower, modifier);
504
505             if (actionResponse.isRight()) {
506                 log.debug("failed to get service");
507                 return buildErrorResponse(actionResponse.right().value());
508             }
509
510             Service service = actionResponse.left().value();
511             Object result = RepresentationUtils.toRepresentation(service);
512
513             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
514
515         } catch (Exception e) {
516             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
517             log.debug("get service failed with exception", e);
518             throw e;
519         }
520     }
521
522     @GET
523     @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}")
524     @Consumes(MediaType.APPLICATION_JSON)
525     @Produces(MediaType.APPLICATION_JSON)
526     @Operation(description = "Retrieve Service", method = "GET",
527             summary = "Returns service according to name and version", responses = {
528             @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
529             @ApiResponse(responseCode = "200", description = "Service found"),
530             @ApiResponse(responseCode = "403", description = "Restricted operation"),
531             @ApiResponse(responseCode = "404", description = "Service not found")})
532     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
533     public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,
534             @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
535             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
536
537         // get modifier id
538         User modifier = new User();
539         modifier.setUserId(userId);
540         log.debug(MODIFIER_ID_IS, userId);
541
542         try {
543             Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId);
544
545             if (actionResponse.isRight()) {
546                 return buildErrorResponse(actionResponse.right().value());
547             }
548
549             Service service = actionResponse.left().value();
550             Object result = RepresentationUtils.toRepresentation(service);
551
552             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
553
554         } catch (Exception e) {
555             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
556             log.debug("get service failed with exception", e);
557             throw e;
558         }
559     }
560
561     @POST
562     @Path("/services/{serviceId}/distribution/{env}/activate")
563     @Consumes(MediaType.APPLICATION_JSON)
564     @Produces(MediaType.APPLICATION_JSON)
565     @Operation(description = "Activate distribution", method = "POST", summary = "activate distribution",
566             responses = {@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "409",
567                     description = "Service cannot be distributed due to missing deployment artifacts"),
568                     @ApiResponse(responseCode = "404", description = "Requested service was not found"),
569                     @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
570     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
571     public Response activateDistribution(@PathParam("serviceId") final String serviceId,
572             @PathParam("env") final String env, @Context final HttpServletRequest request,
573             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
574
575         String url = request.getMethod() + " " + request.getRequestURI();
576         log.debug(START_HANDLE_REQUEST_OF, url);
577
578         User modifier = new User();
579         modifier.setUserId(userId);
580         log.debug(MODIFIER_ID_IS, userId);
581
582         Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.activateDistribution(serviceId, env, modifier, request);
583
584         if (distResponse.isRight()) {
585             log.debug("failed to activate service distribution");
586             return buildErrorResponse(distResponse.right().value());
587         }
588         Service service = distResponse.left().value();
589         Object result = null;
590         try {
591             result = RepresentationUtils.toRepresentation(service);
592         } catch (IOException e) {
593             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
594             log.debug("activate distribution failed with exception", e);
595             throw e;
596         }
597         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
598     }
599
600     @POST
601     @Path("/services/{serviceId}/distribution/{did}/markDeployed")
602     @Consumes(MediaType.APPLICATION_JSON)
603     @Produces(MediaType.APPLICATION_JSON)
604     @Operation(description = "Mark distribution as deployed", method = "POST",
605             summary = "relevant audit record will be created",
606             responses = {@ApiResponse(responseCode = "200", description = "Service was marked as deployed"),
607                     @ApiResponse(responseCode = "409", description = "Restricted operation"),
608                     @ApiResponse(responseCode = "403", description = "Service is not available"),
609                     @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
610                     @ApiResponse(responseCode = "404", description = "Requested service was not found"),
611                     @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
612     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
613     public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId,
614             @PathParam("did") final String did, @Context final HttpServletRequest request,
615             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
616
617         String url = request.getMethod() + " " + request.getRequestURI();
618         log.debug(START_HANDLE_REQUEST_OF, url);
619
620         User modifier = new User();
621         modifier.setUserId(userId);
622         log.debug(MODIFIER_ID_IS, userId);
623
624         try {
625             Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.markDistributionAsDeployed(serviceId, did, modifier);
626
627             if (distResponse.isRight()) {
628                 log.debug("failed to mark distribution as deployed");
629                 return buildErrorResponse(distResponse.right().value());
630             }
631             Service service = distResponse.left().value();
632             Object result = RepresentationUtils.toRepresentation(service);
633             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
634         } catch (Exception e) {
635             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");
636             log.debug("mark distribution as deployed failed with exception", e);
637             throw e;
638         }
639     }
640
641     @POST
642     @Path("/services/{serviceId}/tempUrlToBeDeleted")
643     @Consumes(MediaType.APPLICATION_JSON)
644     @Produces(MediaType.APPLICATION_JSON)
645     @Operation(responses = {@ApiResponse(responseCode = "200", description = "OK"),
646             @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
647     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
648     public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
649
650         ServletContext context = request.getSession().getServletContext();
651         String url = request.getMethod() + " " + request.getRequestURI();
652         log.debug(START_HANDLE_REQUEST_OF, url);
653
654         User modifier = new User();
655         modifier.setUserId(userId);
656         log.debug(MODIFIER_ID_IS, userId);
657
658         try {
659             Service service = (serviceBusinessLogic.getService(serviceId, modifier)).left().value();
660             Either<Service, ResponseFormat> res = serviceBusinessLogic.updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
661
662             if (res.isRight()) {
663                 buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
664             }
665             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
666         } catch (Exception e) {
667             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");
668             log.debug("failed with exception", e);
669             throw e;
670         }
671     }
672
673
674     @GET
675     @Path("/services/{serviceId}/linksMap")
676     @Consumes(MediaType.APPLICATION_JSON)
677     @Produces(MediaType.APPLICATION_JSON)
678     @Operation(description = "Retrieve Service component relations map", method = "GET",
679             summary = "Returns service components relations", responses = {@ApiResponse(
680             content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))),
681             @ApiResponse(responseCode = "200", description = "Service found"),
682             @ApiResponse(responseCode = "403", description = "Restricted operation"),
683             @ApiResponse(responseCode = "404", description = "Service not found")})
684     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
685     public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId,
686                                                    @Context final HttpServletRequest request,
687                                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
688
689         String url = request.getMethod() + " " + request.getRequestURI();
690         log.debug(START_HANDLE_REQUEST_OF, url);
691
692         // get modifier id
693         User modifier = new User();
694         modifier.setUserId(userId);
695         log.debug(MODIFIER_ID_IS, userId);
696
697         try {
698             String serviceIdLower = serviceId.toLowerCase();
699             log.debug("get service components relations with id {}", serviceId);
700             Either<ServiceRelations, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceComponentsRelations(serviceIdLower, modifier);
701
702             if (actionResponse.isRight()) {
703                 log.debug("failed to get service relations data");
704                 return buildErrorResponse(actionResponse.right().value());
705             }
706
707             ServiceRelations serviceRelations = actionResponse.left().value();
708             Object result = RepresentationUtils.toRepresentation(serviceRelations);
709
710             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
711
712         } catch (Exception e) {
713             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
714             log.debug("get service relations data failed with exception", e);
715             throw e;
716         }
717     }
718
719     @POST
720     @Path("/services/importService")
721     @Consumes(MediaType.APPLICATION_JSON)
722     @Produces(MediaType.APPLICATION_JSON)
723     @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
724     @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")})
725     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) {
726
727         userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
728         initSpringFromContext();
729
730         String url = request.getMethod() + " " + request.getRequestURI();
731         log.debug("Start handle request of {}" , url);
732
733         // get modifier id
734         User modifier = new User();
735         modifier.setUserId(userId);
736         log.debug("modifier id is {}", userId);
737
738         Response response;
739         try {
740
741             Wrapper<Response> responseWrapper = new Wrapper<>();
742             performUIImport(responseWrapper, data, request, userId, null);
743             return responseWrapper.getInnerElement();
744         } catch (IOException | ZipException e) {
745             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service");
746             log.debug("import service failed with exception", e);
747             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
748             return response;
749         }
750     }
751
752     private void performUIImport(Wrapper<Response> responseWrapper, String data, final HttpServletRequest request, String userId, String ServiceUniqueId)
753         throws FileNotFoundException, ZipException {
754
755         Wrapper<User> userWrapper = new Wrapper<>();
756         Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
757         Wrapper<String> yamlStringWrapper = new Wrapper<>();
758
759         ServiceAuthorityTypeEnum ServiceAuthorityEnum = ServiceAuthorityTypeEnum.USER_TYPE_UI;
760
761         commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, ServiceAuthorityEnum, userId, data);
762
763         specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, data, ServiceAuthorityEnum);
764
765         if (responseWrapper.isEmpty()) {
766             handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), ServiceAuthorityEnum, true, ServiceUniqueId);
767         }
768     }
769
770     /**import ReplaceService 
771      *
772      * @param userId
773      * @param requestId
774      * @param instanceIdHeader
775      * @param accept
776      * @param authorization
777      * @param request
778      * @param file
779      * @param contentDispositionHeader
780      * @param serviceInfoJsonString
781      * @param uuid
782      * @return
783      */
784     @POST
785     @Path("/services/serviceUUID/{uuid}/importReplaceService")
786     @Produces(MediaType.APPLICATION_JSON)
787     @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
788             @ApiResponse(responseCode = "201", description = "Service created"),
789             @ApiResponse(responseCode = "403", description = "Restricted operation"),
790             @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
791             @ApiResponse(responseCode = "409", description = "Service already exist")})
792     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
793     public Response importReplaceService(
794             @Parameter(description = "The user id",
795                     required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
796             @Parameter(description = "X-ECOMP-RequestID header",
797                     required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
798             @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
799                     value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
800             @Parameter(description = "Determines the format of the body of the response",
801                     required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
802             @Parameter(description = "The username and password",
803                     required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
804             @Context final HttpServletRequest request,
805             @Parameter(description = "FileInputStream")
806             @FormDataParam("serviceZip") File file,
807             @Parameter(description = "ContentDisposition")
808             @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader,
809             @Parameter(description = "serviceMetadata")
810             @FormDataParam("serviceZipMetadata") String serviceInfoJsonString,
811             @Parameter(description = "The requested asset uuid",
812                     required = true) @PathParam("uuid") final String uuid) {
813
814         initSpringFromContext();
815
816         String requestURI = request.getRequestURI();
817         String url = request.getMethod() + " " + requestURI;
818         log.debug("importReplaceService,Start handle request of {}", url);
819
820         // get modifier id
821         User modifier = new User();
822         modifier.setUserId(userId);
823         log.debug("importReplaceService,modifier id is {}", userId);
824
825         log.debug("importReplaceService,get file:{},fileName:{}",file,file.getName());
826
827         Response response;
828         ResponseFormat responseFormat =null;
829         AuditingActionEnum auditingActionEnum = AuditingActionEnum.Import_Replace_Service;
830         String assetType = "services";
831
832         Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
833
834         if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
835             log.debug("getServiceAbstractStatus: Service Fetching Failed");
836             throw new ByResponseFormatComponentException(assetTypeData.right().value());
837         }
838
839         log.debug("getServiceAbstractStatus: Service Fetching Success");
840
841         Service oldService = (Service) assetTypeData.left().value().get(0);
842
843         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
844         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
845         DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
846         // Mandatory
847         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
848             log.debug("importReplaceService: Missing X-ECOMP-InstanceID header");
849             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
850             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
851                     resourceCommonInfo, requestId, null);
852             return buildErrorResponse(responseFormat);
853         }
854
855         try {
856             Wrapper<Response> responseWrapper = new Wrapper<>();
857             // file import
858             Wrapper<User> userWrapper = new Wrapper<>();
859             Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
860             Wrapper<String> yamlStringWrapper = new Wrapper<>();
861
862             ServiceUploadServlet.ServiceAuthorityTypeEnum serviceAuthorityEnum = ServiceUploadServlet.ServiceAuthorityTypeEnum.CSAR_TYPE_BE;
863
864             // PayLoad Validations
865             commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityEnum, userId, serviceInfoJsonString);
866
867             fillServicePayload(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, modifier, serviceInfoJsonString, serviceAuthorityEnum, file);
868
869             specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, userWrapper.getInnerElement(), request, serviceInfoJsonString, serviceAuthorityEnum);
870
871             log.debug("importReplaceService:get payload:{}", uploadServiceInfoWrapper.getInnerElement().getPayloadData());
872
873             ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition)oldService.getComponentMetadataDefinition().getMetadataDataDefinition();
874
875             uploadServiceInfoWrapper.getInnerElement().setServiceVendorModelNumber(serviceMetadataDataDefinition.getServiceVendorModelNumber());
876             uploadServiceInfoWrapper.getInnerElement().setDescription(oldService.getDescription());
877             uploadServiceInfoWrapper.getInnerElement().setCategories(oldService.getCategories());
878             uploadServiceInfoWrapper.getInnerElement().setIcon(oldService.getIcon());
879             uploadServiceInfoWrapper.getInnerElement().setProjectCode(oldService.getProjectCode());
880
881
882             if (responseWrapper.isEmpty()) {
883                 log.debug("importReplaceService:start handleImportService");
884                 handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement(), yamlStringWrapper.getInnerElement(), serviceAuthorityEnum, true, null);
885             }
886
887             return responseWrapper.getInnerElement();
888         } catch (IOException | ZipException e) {
889             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service");
890             log.debug("import service failed with exception", e);
891             response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
892             return response;
893         }
894     }
895 }