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