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