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