2 * Copyright (C) 2020 CMCC, Inc. and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.openecomp.sdc.be.externalapi.servlet;
18 import com.jcabi.aspects.Loggable;
19 import fj.data.Either;
20 import io.swagger.v3.oas.annotations.Operation;
21 import io.swagger.v3.oas.annotations.Parameter;
22 import io.swagger.v3.oas.annotations.media.ArraySchema;
23 import io.swagger.v3.oas.annotations.media.Content;
24 import io.swagger.v3.oas.annotations.media.Schema;
25 import io.swagger.v3.oas.annotations.responses.ApiResponse;
26 import io.swagger.v3.oas.annotations.servers.Server;
27 import io.swagger.v3.oas.annotations.tags.Tag;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.List;
31 import javax.inject.Inject;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.HeaderParam;
35 import javax.ws.rs.POST;
36 import javax.ws.rs.Path;
37 import javax.ws.rs.PathParam;
38 import javax.ws.rs.Produces;
39 import javax.ws.rs.core.Context;
40 import javax.ws.rs.core.MediaType;
41 import javax.ws.rs.core.Response;
43 import org.apache.commons.collections.CollectionUtils;
44 import org.openecomp.sdc.be.components.impl.AbstractTemplateBusinessLogic;
45 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
46 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
47 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
48 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
49 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
50 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
51 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
52 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
53 import org.openecomp.sdc.be.config.BeEcompErrorManager;
54 import org.openecomp.sdc.be.dao.api.ActionStatus;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
56 import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractTemplateInfo;
57 import org.openecomp.sdc.be.externalapi.servlet.representation.CopyServiceInfo;
58 import org.openecomp.sdc.be.impl.ComponentsUtils;
59 import org.openecomp.sdc.be.impl.ServletUtils;
60 import org.openecomp.sdc.be.model.Component;
61 import org.openecomp.sdc.be.model.Service;
62 import org.openecomp.sdc.be.model.User;
63 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
64 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
65 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
66 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
67 import org.openecomp.sdc.be.servlets.RepresentationUtils;
68 import org.openecomp.sdc.common.api.Constants;
69 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
70 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
71 import org.openecomp.sdc.common.log.enums.StatusCode;
72 import org.openecomp.sdc.common.log.wrappers.Logger;
73 import org.openecomp.sdc.exception.ResponseFormat;
74 import org.springframework.stereotype.Controller;
77 * This servlet provides external interfaces related to abstract templates.
81 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
83 @Tag(name = "SDCE-7 APIs")
86 public class AbstractTemplateServlet extends AbstractValidationsServlet {
88 private static final Logger log = Logger.getLogger(AbstractTemplateServlet.class);
89 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(AbstractTemplateServlet.class.getName());
90 private final ElementBusinessLogic elementBusinessLogic;
91 private final AbstractTemplateBusinessLogic abstractTemplateBusinessLogic;
92 private final ServiceBusinessLogic serviceBusinessLogic;
93 private final ResourceBusinessLogic resourceBusinessLogic;
95 private HttpServletRequest request;
98 public AbstractTemplateServlet(ComponentInstanceBusinessLogic componentInstanceBL,
99 ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
100 ElementBusinessLogic elementBusinessLogic, AbstractTemplateBusinessLogic abstractTemplateBusinessLogic,
101 ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
102 super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
103 this.elementBusinessLogic = elementBusinessLogic;
104 this.abstractTemplateBusinessLogic = abstractTemplateBusinessLogic;
105 this.serviceBusinessLogic = serviceBusinessLogic;
106 this.resourceBusinessLogic = resourceBusinessLogic;
111 * @param instanceIdHeader
113 * @param authorization
118 @Path("/abstract/service/serviceUUID/{uuid}/status")
119 @Produces(MediaType.APPLICATION_JSON)
120 @Operation(description = "Fetch abstract status of service", method = "GET", summary = "Return whether the service is a virtual service", responses = {
121 @ApiResponse(responseCode = "200", description = "The check result of whether the service is an abstract service is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
122 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
123 @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
124 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
125 @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
126 @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
127 @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
128 @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
129 public Response getServiceAbstractStatus(
130 @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
131 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
132 @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
133 @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
134 @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) throws IOException {
135 ResponseFormat responseFormat = null;
136 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TEMPLATE_ABSTRACT_STATUS;
137 String requestURI = request.getRequestURI();
138 String url = request.getMethod() + " " + requestURI;
139 log.debug("getServiceAbstractStatus: Start handle request of {}", url);
140 String assetType = "services";
141 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
142 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
143 DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
145 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
146 log.debug("getServiceAbstractStatus: Missing X-ECOMP-InstanceID header");
147 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
148 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
149 return buildErrorResponse(responseFormat);
152 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
153 .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
154 if (assetTypeData.isRight()) {
155 log.debug("getServiceAbstractStatus: Service Fetching Failed");
156 responseFormat = assetTypeData.right().value();
157 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
158 return buildErrorResponse(responseFormat);
160 resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
161 log.debug("getServiceAbstractStatus: Service Fetching Success");
162 Either<AbstractTemplateInfo, ResponseFormat> resMetadata = abstractTemplateBusinessLogic
163 .getServiceAbstractStatus(assetTypeData.left().value());
164 if (resMetadata.isRight()) {
165 log.debug("getServiceAbstractStatus: Service abstract status get Failed");
166 responseFormat = resMetadata.right().value();
167 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
168 return buildErrorResponse(responseFormat);
170 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
171 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
172 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
173 return buildOkResponse(responseFormat, result);
174 } catch (Exception e) {
175 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch abstract status of service");
176 log.debug("getServiceAbstractStatus: Fetch abstract status of service with exception", e);
183 * @param instanceIdHeader
185 * @param authorization
190 @Path("/abstract/service/serviceUUID/{uuid}/copy")
191 @Produces(MediaType.APPLICATION_JSON)
192 @Operation(description = "Copy a new service based on the existing service", method = "POST", summary = "Return whether the copy service is successful", responses = {
193 @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
194 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
195 @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
196 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
197 @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
198 @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
199 @ApiResponse(responseCode = "500", description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
200 @ApiResponse(responseCode = "409", description = "Service already exist")})
201 @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE)
202 public Response copyExistService(
203 @Parameter(description = "The user id", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
204 @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
205 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
206 @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
207 @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
208 @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid,
209 @Parameter(hidden = true) String data) throws IOException {
210 String url = request.getMethod() + " " + request.getRequestURI();
211 log.debug("copyExistService: Start handle request of {}", url);
212 User modifier = new User();
213 modifier.setUserId(userId);
214 log.debug("modifier id is {}", userId);
215 loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, StatusCode.STARTED, "Starting to create a service by user {} ", userId);
216 validateNotEmptyBody(data);
217 Either<CopyServiceInfo, ResponseFormat> convertResponse = parseToCopyServiceInfo(data, modifier);
218 if (convertResponse.isRight()) {
219 throw new ByResponseFormatComponentException(convertResponse.right().value());
221 String assetType = "services";
222 CopyServiceInfo copyServiceInfo = convertResponse.left().value();
223 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
224 .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
225 if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
226 log.debug("getServiceAbstractStatus: Service Fetching Failed");
227 throw new ByResponseFormatComponentException(assetTypeData.right().value());
229 log.debug("getServiceAbstractStatus: Service Fetching Success");
230 Service service = (Service) assetTypeData.left().value().get(0);
231 List<String> tags = service.getTags();
232 if (CollectionUtils.isNotEmpty(tags)) {
234 for (int i = tags.size() - 1; i >= 0; i--) {
235 String tag = tags.get(i);
236 if (service.getName().equals(tag)) {
241 tags = new ArrayList<>();
243 service.setName(copyServiceInfo.getNewServiceName());
244 tags.add(copyServiceInfo.getNewServiceName());
245 Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);
246 if (actionResponse.isRight()) {
247 log.debug("Failed to create service");
248 throw new ByResponseFormatComponentException(actionResponse.right().value());
250 loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE,
251 "Service {} has been copyied by user {} ", service.getName(), userId);
252 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
255 public Either<CopyServiceInfo, ResponseFormat> parseToCopyServiceInfo(String serviceJson, User user) {
256 return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, CopyServiceInfo.class, AuditingActionEnum.CREATE_RESOURCE,
257 ComponentTypeEnum.SERVICE);