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.apache.hc.core5.http.HttpStatus.SC_BAD_REQUEST;
23 import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR;
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import com.google.gson.reflect.TypeToken;
28 import com.jcabi.aspects.Loggable;
29 import fj.data.Either;
30 import io.swagger.v3.oas.annotations.Operation;
31 import io.swagger.v3.oas.annotations.Parameter;
32 import io.swagger.v3.oas.annotations.media.ArraySchema;
33 import io.swagger.v3.oas.annotations.media.Content;
34 import io.swagger.v3.oas.annotations.media.Schema;
35 import io.swagger.v3.oas.annotations.responses.ApiResponse;
36 import io.swagger.v3.oas.annotations.servers.Server;
37 import io.swagger.v3.oas.annotations.tags.Tag;
39 import java.io.FileNotFoundException;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.lang.reflect.Type;
43 import java.util.ArrayList;
44 import java.util.List;
47 import javax.inject.Inject;
48 import javax.servlet.ServletContext;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.validation.constraints.NotNull;
51 import javax.ws.rs.Consumes;
52 import javax.ws.rs.DELETE;
53 import javax.ws.rs.GET;
54 import javax.ws.rs.HeaderParam;
55 import javax.ws.rs.POST;
56 import javax.ws.rs.PUT;
57 import javax.ws.rs.Path;
58 import javax.ws.rs.PathParam;
59 import javax.ws.rs.Produces;
60 import javax.ws.rs.QueryParam;
61 import javax.ws.rs.core.Context;
62 import javax.ws.rs.core.MediaType;
63 import javax.ws.rs.core.Response;
64 import org.apache.commons.collections4.MapUtils;
65 import org.apache.http.HttpStatus;
66 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
67 import org.glassfish.jersey.media.multipart.FormDataParam;
68 import org.keycloak.representations.AccessToken;
69 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
70 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
71 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
72 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
73 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
74 import org.openecomp.sdc.be.components.impl.ServiceImportBusinessLogic;
75 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
76 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
77 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
78 import org.openecomp.sdc.be.config.BeEcompErrorManager;
79 import org.openecomp.sdc.be.dao.api.ActionStatus;
80 import org.openecomp.sdc.be.datamodel.ServiceRelations;
81 import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
82 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
83 import org.openecomp.sdc.be.impl.ComponentsUtils;
84 import org.openecomp.sdc.be.impl.ServletUtils;
85 import org.openecomp.sdc.be.model.Component;
86 import org.openecomp.sdc.be.model.DistributionStatusEnum;
87 import org.openecomp.sdc.be.model.GroupInstanceProperty;
88 import org.openecomp.sdc.be.model.Resource;
89 import org.openecomp.sdc.be.model.Service;
90 import org.openecomp.sdc.be.model.UploadServiceInfo;
91 import org.openecomp.sdc.be.model.User;
92 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
93 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
94 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
95 import org.openecomp.sdc.be.servlets.ServiceUploadServlet.ServiceAuthorityTypeEnum;
96 import org.openecomp.sdc.common.api.Constants;
97 import org.openecomp.sdc.common.datastructure.Wrapper;
98 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
99 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
100 import org.openecomp.sdc.common.log.enums.StatusCode;
101 import org.openecomp.sdc.common.log.wrappers.Logger;
102 import org.openecomp.sdc.common.util.Multitenancy;
103 import org.openecomp.sdc.common.zip.exception.ZipException;
104 import org.openecomp.sdc.exception.ResponseFormat;
105 import org.springframework.stereotype.Controller;
106 import org.yaml.snakeyaml.Yaml;
108 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
110 @Server(url = "/sdc2/rest")
112 public class ServiceServlet extends AbstractValidationsServlet {
114 private static final Logger log = Logger.getLogger(ServiceServlet.class);
115 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceServlet.class.getName());
116 private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
117 private static final String MODIFIER_ID_IS = "modifier id is {}";
118 private final ElementBusinessLogic elementBusinessLogic;
119 private final ServiceBusinessLogic serviceBusinessLogic;
122 public ServiceServlet(ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
123 ServletUtils servletUtils, ResourceImportManager resourceImportManager, ServiceBusinessLogic serviceBusinessLogic,
124 ResourceBusinessLogic resourceBusinessLogic, ElementBusinessLogic elementBusinessLogic) {
125 super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
126 this.serviceBusinessLogic = serviceBusinessLogic;
127 this.elementBusinessLogic = elementBusinessLogic;
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 User modifier = new User(userId);
368 log.debug(MODIFIER_ID_IS, userId);
373 @Path("/services/{serviceId}/metadata")
374 @Tag(name = "SDCE-2 APIs")
375 @Consumes(MediaType.APPLICATION_JSON)
376 @Produces(MediaType.APPLICATION_JSON)
377 @Operation(description = "Update Service Metadata", method = "PUT", summary = "Returns updated service", responses = {
378 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
379 @ApiResponse(responseCode = "200", description = "Service Updated"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
380 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
381 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
382 public Response updateServiceMetadata(@PathParam("serviceId") final String serviceId,
383 @Parameter(description = "Service object to be Updated", required = true) String data,
384 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
386 String url = request.getMethod() + " " + request.getRequestURI();
387 log.debug(START_HANDLE_REQUEST_OF, url);
388 User modifier = new User(userId);
389 log.debug(MODIFIER_ID_IS, userId);
391 String serviceIdLower = serviceId.toLowerCase();
392 Either<Service, ResponseFormat> convertResponse = parseToService(data, modifier);
393 if (convertResponse.isRight()) {
394 log.debug("failed to parse service");
395 return buildErrorResponse(convertResponse.right().value());
397 Service updatedService = convertResponse.left().value();
398 Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.updateServiceMetadata(serviceIdLower, updatedService, modifier);
399 if (actionResponse.isRight()) {
400 log.debug("failed to update service");
401 return buildErrorResponse(actionResponse.right().value());
403 Service service = actionResponse.left().value();
404 Object result = RepresentationUtils.toRepresentation(service);
405 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
406 } catch (Exception e) {
407 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
408 log.debug("update service metadata failed with exception", e);
414 * updates group instance property values Note, than in case of group instance updated successfully, related resourceInstance and containing
415 * component modification time will be updated
418 * @param componentInstanceId
419 * @param groupInstanceId
426 @Path("/{containerComponentType}/{serviceId}/resourceInstance/{componentInstanceId}/groupInstance/{groupInstanceId}")
427 @Tag(name = "SDCE-2 APIs")
428 @Consumes(MediaType.APPLICATION_JSON)
429 @Produces(MediaType.APPLICATION_JSON)
430 @Operation(description = "Update Group Instance Property Values", method = "PUT", summary = "Returns updated group instance", responses = {
431 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
432 @ApiResponse(responseCode = "200", description = "Group Instance Property Values Updated"),
433 @ApiResponse(responseCode = "403", description = "Restricted operation"),
434 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
435 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
436 public Response updateGroupInstancePropertyValues(@PathParam("serviceId") final String serviceId,
437 @PathParam("componentInstanceId") final String componentInstanceId,
438 @PathParam("groupInstanceId") final String groupInstanceId,
439 @Parameter(description = "Group instance object to be Updated", required = true) String data,
440 @Context final HttpServletRequest request,
441 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws JsonProcessingException {
442 String url = request.getMethod() + " " + request.getRequestURI();
443 log.debug(START_HANDLE_REQUEST_OF, url);
444 User modifier = new User(userId);
445 log.debug(MODIFIER_ID_IS, userId);
446 Either<List<GroupInstanceProperty>, ResponseFormat> actionResponse = null;
448 List<GroupInstanceProperty> updatedProperties;
449 Type listType = new TypeToken<ArrayList<GroupInstanceProperty>>() {
451 ArrayList<GroupInstanceProperty> newProperties = gson.fromJson(data, listType);
452 if (newProperties == null) {
453 actionResponse = Either.right(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
455 if (actionResponse == null) {
456 log.debug("Start handle update group instance property values request. Received group instance is {}", groupInstanceId);
457 actionResponse = serviceBusinessLogic
458 .updateGroupInstancePropertyValues(modifier, serviceId, componentInstanceId, groupInstanceId, newProperties);
459 if (actionResponse.isRight()) {
460 actionResponse = Either.right(actionResponse.right().value());
463 if (actionResponse.isLeft()) {
464 updatedProperties = actionResponse.left().value();
465 ObjectMapper mapper = new ObjectMapper();
466 String result = mapper.writeValueAsString(updatedProperties);
467 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
469 return buildErrorResponse(actionResponse.right().value());
471 } catch (Exception e) {
472 log.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), "Exception occured during update Group Instance property values.", e);
478 @Path("/services/{serviceId}")
479 @Tag(name = "SDCE-2 APIs")
480 @Consumes(MediaType.APPLICATION_JSON)
481 @Produces(MediaType.APPLICATION_JSON)
482 @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to serviceId", responses = {
483 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
484 @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
485 @ApiResponse(responseCode = "404", description = "Service not found")})
486 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
487 public Response getServiceById(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
488 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
489 String url = request.getMethod() + " " + request.getRequestURI();
490 log.debug(START_HANDLE_REQUEST_OF, url);
492 User modifier = new User(userId);
493 log.debug(MODIFIER_ID_IS, userId);
495 String serviceIdLower = serviceId.toLowerCase();
496 log.debug("get service with id {}", serviceId);
497 Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getService(serviceIdLower, modifier);
498 if (actionResponse.isRight()) {
499 log.debug("failed to get service");
500 return buildErrorResponse(actionResponse.right().value());
502 Service service = actionResponse.left().value();
503 Object result = RepresentationUtils.toRepresentation(service);
504 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
505 } catch (Exception e) {
506 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
507 log.debug("get service failed with exception", e);
513 @Path("/services/serviceName/{serviceName}/serviceVersion/{serviceVersion}")
514 @Tag(name = "SDCE-2 APIs")
515 @Consumes(MediaType.APPLICATION_JSON)
516 @Produces(MediaType.APPLICATION_JSON)
517 @Operation(description = "Retrieve Service", method = "GET", summary = "Returns service according to name and version", responses = {
518 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
519 @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
520 @ApiResponse(responseCode = "404", description = "Service not found")})
521 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
522 public Response getServiceByNameAndVersion(@PathParam("serviceName") final String serviceName,
523 @PathParam("serviceVersion") final String serviceVersion, @Context final HttpServletRequest request,
524 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
526 log.debug(MODIFIER_ID_IS, userId);
528 Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceByNameAndVersion(serviceName, serviceVersion, userId);
529 if (actionResponse.isRight()) {
530 return buildErrorResponse(actionResponse.right().value());
532 Service service = actionResponse.left().value();
533 Object result = RepresentationUtils.toRepresentation(service);
534 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
535 } catch (Exception e) {
536 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service by name and version");
537 log.debug("get service failed with exception", e);
543 @Path("/services/{serviceId}/distribution/{env}/activate")
544 @Tag(name = "SDCE-5 APIs")
545 @Consumes(MediaType.APPLICATION_JSON)
546 @Produces(MediaType.APPLICATION_JSON)
547 @Operation(description = "Activate distribution", method = "POST", summary = "activate distribution", responses = {
548 @ApiResponse(responseCode = "200", description = "OK"),
549 @ApiResponse(responseCode = "409", description = "Service cannot be distributed due to missing deployment artifacts"),
550 @ApiResponse(responseCode = "404", description = "Requested service was not found"),
551 @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
552 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
553 public Response activateDistribution(@PathParam("serviceId") final String serviceId, @PathParam("env") final String env,
554 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId)
556 String url = request.getMethod() + " " + request.getRequestURI();
557 log.debug(START_HANDLE_REQUEST_OF, url);
558 User modifier = new User(userId);
559 log.debug(MODIFIER_ID_IS, userId);
560 Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.activateDistribution(serviceId, env, modifier, request);
561 if (distResponse.isRight()) {
562 log.debug("failed to activate service distribution");
563 return buildErrorResponse(distResponse.right().value());
565 Service service = distResponse.left().value();
566 Object result = null;
568 result = RepresentationUtils.toRepresentation(service);
569 } catch (IOException e) {
570 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Activate Distribution");
571 log.debug("activate distribution failed with exception", e);
574 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
578 @Path("/services/{serviceId}/distribution/{did}/markDeployed")
579 @Tag(name = "SDCE-5 APIs")
580 @Consumes(MediaType.APPLICATION_JSON)
581 @Produces(MediaType.APPLICATION_JSON)
582 @Operation(description = "Mark distribution as deployed", method = "POST", summary = "relevant audit record will be created", responses = {
583 @ApiResponse(responseCode = "200", description = "Service was marked as deployed"),
584 @ApiResponse(responseCode = "409", description = "Restricted operation"),
585 @ApiResponse(responseCode = "403", description = "Service is not available"),
586 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
587 @ApiResponse(responseCode = "404", description = "Requested service was not found"),
588 @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
589 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
590 public Response markDistributionAsDeployed(@PathParam("serviceId") final String serviceId, @PathParam("did") final String did,
591 @Context final HttpServletRequest request,
592 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
593 String url = request.getMethod() + " " + request.getRequestURI();
594 log.debug(START_HANDLE_REQUEST_OF, url);
595 User modifier = new User(userId);
596 log.debug(MODIFIER_ID_IS, userId);
598 Either<Service, ResponseFormat> distResponse = serviceBusinessLogic.markDistributionAsDeployed(serviceId, did, modifier);
599 if (distResponse.isRight()) {
600 log.debug("failed to mark distribution as deployed");
601 return buildErrorResponse(distResponse.right().value());
603 Service service = distResponse.left().value();
604 Object result = RepresentationUtils.toRepresentation(service);
605 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
606 } catch (Exception e) {
607 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Mark Distribution As Deployed");
608 log.debug("mark distribution as deployed failed with exception", e);
614 @Path("/services/{serviceId}/tempUrlToBeDeleted")
615 @Tag(name = "SDCE-2 APIs")
616 @Consumes(MediaType.APPLICATION_JSON)
617 @Produces(MediaType.APPLICATION_JSON)
618 @Operation(responses = {@ApiResponse(responseCode = "200", description = "OK"),
619 @ApiResponse(responseCode = "500", description = "Internal Server Error. Please try again later.")})
620 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
621 public Response tempUrlToBeDeleted(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
622 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
623 String url = request.getMethod() + " " + request.getRequestURI();
624 log.debug(START_HANDLE_REQUEST_OF, url);
625 User modifier = new User(userId);
626 log.debug(MODIFIER_ID_IS, userId);
628 Service service = (serviceBusinessLogic.getService(serviceId, modifier)).left().value();
629 Either<Service, ResponseFormat> res = serviceBusinessLogic
630 .updateDistributionStatusForActivation(service, modifier, DistributionStatusEnum.DISTRIBUTED);
632 buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
634 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), null);
635 } catch (Exception e) {
636 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("tempUrlToBeDeleted");
637 log.debug("failed with exception", e);
643 @Path("/services/{serviceId}/linksMap")
644 @Tag(name = "SDCE-2 APIs")
645 @Consumes(MediaType.APPLICATION_JSON)
646 @Produces(MediaType.APPLICATION_JSON)
647 @Operation(description = "Retrieve Service component relations map", method = "GET", summary = "Returns service components relations", responses = {
648 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ServiceRelations.class)))),
649 @ApiResponse(responseCode = "200", description = "Service found"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
650 @ApiResponse(responseCode = "404", description = "Service not found")})
651 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
652 public Response getServiceComponentRelationMap(@PathParam("serviceId") final String serviceId, @Context final HttpServletRequest request,
653 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
654 String url = request.getMethod() + " " + request.getRequestURI();
655 log.debug(START_HANDLE_REQUEST_OF, url);
657 User modifier = new User(userId);
658 log.debug(MODIFIER_ID_IS, userId);
660 String serviceIdLower = serviceId.toLowerCase();
661 log.debug("get service components relations with id {}", serviceId);
662 Either<ServiceRelations, ResponseFormat> actionResponse = serviceBusinessLogic.getServiceComponentsRelations(serviceIdLower, modifier);
663 if (actionResponse.isRight()) {
664 log.debug("failed to get service relations data");
665 return buildErrorResponse(actionResponse.right().value());
667 ServiceRelations serviceRelations = actionResponse.left().value();
668 Object result = RepresentationUtils.toRepresentation(serviceRelations);
669 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result);
670 } catch (Exception e) {
671 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Service");
672 log.debug("get service relations data failed with exception", e);
678 @Path("/services/importService")
679 @Tag(name = "SDCE-2 APIs")
680 @Consumes(MediaType.APPLICATION_JSON)
681 @Produces(MediaType.APPLICATION_JSON)
682 @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
683 @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
684 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
685 @ApiResponse(responseCode = "409", description = "Service already exist")})
686 public Response importNsService(@Parameter(description = "Service object to be imported", required = true) String data,
687 @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
688 userId = (userId != null) ? userId : request.getHeader(Constants.USER_ID_HEADER);
689 initSpringFromContext();
690 String url = request.getMethod() + " " + request.getRequestURI();
691 log.debug(START_HANDLE_REQUEST_OF, url);
692 log.debug(MODIFIER_ID_IS, userId);
694 final Wrapper<Response> responseWrapper = performUIImport(data, request, userId);
695 return responseWrapper.getInnerElement();
696 } catch (IOException | ZipException e) {
697 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service");
698 log.debug("import service failed with exception", e);
699 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
703 private Wrapper<Response> performUIImport(String data, final HttpServletRequest request,
704 String userId) throws FileNotFoundException, ZipException {
705 Wrapper<Response> responseWrapper = new Wrapper<>();
706 Wrapper<User> userWrapper = new Wrapper<>();
707 Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
708 Wrapper<String> yamlStringWrapper = new Wrapper<>();
709 ServiceAuthorityTypeEnum serviceAuthorityTypeEnum = ServiceAuthorityTypeEnum.USER_TYPE_UI;
710 commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityTypeEnum, userId, data);
711 specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, request,
712 data, serviceAuthorityTypeEnum);
713 if (responseWrapper.isEmpty()) {
714 handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement());
716 return responseWrapper;
720 * import ReplaceService
724 * @param instanceIdHeader
726 * @param authorization
729 * @param contentDispositionHeader
730 * @param serviceInfoJsonString
735 @Path("/services/serviceUUID/{uuid}/importReplaceService")
736 @Tag(name = "SDCE-2 APIs")
737 @Produces(MediaType.APPLICATION_JSON)
738 @Operation(description = "Import Service", method = "POST", summary = "Returns imported service", responses = {
739 @ApiResponse(responseCode = "201", description = "Service created"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
740 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
741 @ApiResponse(responseCode = "409", description = "Service already exist")})
742 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
743 public Response importReplaceService(
744 @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
745 @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
746 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
747 @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
748 @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
749 @Context final HttpServletRequest request, @Parameter(description = "FileInputStream") @FormDataParam("serviceZip") File file,
750 @Parameter(description = "ContentDisposition") @FormDataParam("serviceZip") FormDataContentDisposition contentDispositionHeader,
751 @Parameter(description = "serviceMetadata") @FormDataParam("serviceZipMetadata") String serviceInfoJsonString,
752 @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) {
753 initSpringFromContext();
754 String requestURI = request.getRequestURI();
755 String url = request.getMethod() + " " + requestURI;
756 log.debug("importReplaceService,Start handle request of {}", url);
758 User modifier = new User(userId);
759 log.debug("importReplaceService,modifier id is {}", userId);
760 log.debug("importReplaceService,get file:{},fileName:{}", file, file.getName());
761 ResponseFormat responseFormat = null;
762 AuditingActionEnum auditingActionEnum = AuditingActionEnum.Import_Replace_Service;
763 String assetType = "services";
764 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
765 .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
766 if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
767 log.debug("getServiceAbstractStatus: Service Fetching Failed");
768 throw new ByResponseFormatComponentException(assetTypeData.right().value());
770 log.debug("getServiceAbstractStatus: Service Fetching Success");
771 Service oldService = (Service) assetTypeData.left().value().get(0);
772 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
773 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
774 DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
776 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
777 log.debug("importReplaceService: Missing X-ECOMP-InstanceID header");
778 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
779 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, null);
780 return buildErrorResponse(responseFormat);
783 Wrapper<Response> responseWrapper = new Wrapper<>();
785 Wrapper<User> userWrapper = new Wrapper<>();
786 Wrapper<UploadServiceInfo> uploadServiceInfoWrapper = new Wrapper<>();
787 Wrapper<String> yamlStringWrapper = new Wrapper<>();
788 ServiceUploadServlet.ServiceAuthorityTypeEnum serviceAuthorityEnum = ServiceUploadServlet.ServiceAuthorityTypeEnum.CSAR_TYPE_BE;
789 // PayLoad Validations
790 commonServiceGeneralValidations(responseWrapper, userWrapper, uploadServiceInfoWrapper, serviceAuthorityEnum, userId,
791 serviceInfoJsonString);
792 fillServicePayload(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, modifier, serviceInfoJsonString, serviceAuthorityEnum,
794 specificServiceAuthorityValidations(responseWrapper, uploadServiceInfoWrapper, yamlStringWrapper, request,
795 serviceInfoJsonString, serviceAuthorityEnum);
796 log.debug("importReplaceService:get payload:{}", uploadServiceInfoWrapper.getInnerElement().getPayloadData());
797 ServiceMetadataDataDefinition serviceMetadataDataDefinition = (ServiceMetadataDataDefinition) oldService.getComponentMetadataDefinition()
798 .getMetadataDataDefinition();
799 uploadServiceInfoWrapper.getInnerElement().setServiceVendorModelNumber(serviceMetadataDataDefinition.getServiceVendorModelNumber());
800 uploadServiceInfoWrapper.getInnerElement().setDescription(oldService.getDescription());
801 uploadServiceInfoWrapper.getInnerElement().setCategories(oldService.getCategories());
802 uploadServiceInfoWrapper.getInnerElement().setIcon(oldService.getIcon());
803 uploadServiceInfoWrapper.getInnerElement().setProjectCode(oldService.getProjectCode());
804 if (responseWrapper.isEmpty()) {
805 log.debug("importReplaceService:start handleImportService");
806 handleImportService(responseWrapper, userWrapper.getInnerElement(), uploadServiceInfoWrapper.getInnerElement());
808 return responseWrapper.getInnerElement();
809 } catch (final ZipException e) {
810 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Import Service");
811 log.debug("import service failed with exception", e);
812 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
818 @Path("/services/{serviceId}/toscaTemplate")
819 @Tag(name = "SDCE-2 APIs")
820 @Consumes(MediaType.APPLICATION_JSON)
821 @Produces(MediaType.APPLICATION_JSON)
822 @Operation(description = "Update service by tosca template import", method = "PUT", summary = "Returns updated service",
824 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class)))),
825 @ApiResponse(responseCode = "200", description = "Service Updated"),
826 @ApiResponse(responseCode = "403", description = "Restricted operation"),
827 @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")})
828 @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
829 public Response importToscaTemplate(@PathParam("serviceId") final String serviceId,
830 @Parameter(description = "Service object to be Updated", required = true) final String data,
831 @Context final HttpServletRequest request,
832 @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) throws IOException {
833 initSpringFromContext();
834 final String url = request.getMethod() + " " + request.getRequestURI();
835 log.debug(START_HANDLE_REQUEST_OF, url);
836 final User modifier = new User(userId);
837 log.debug(MODIFIER_ID_IS, userId);
839 final ServiceImportBusinessLogic serviceImportBusinessLogic = serviceImportManager.getServiceImportBusinessLogic();
840 final Service updatedService = serviceImportBusinessLogic.updateServiceFromToscaTemplate(serviceId, modifier, data);
841 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), RepresentationUtils.toRepresentation(updatedService));
842 } catch (Exception e) {
843 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Service Metadata");
844 log.debug("update service metadata failed with exception", e);
849 public enum Action {DELETE, MARK_AS_DELETE}