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.
17 package org.openecomp.sdc.be.externalapi.servlet;
19 import com.jcabi.aspects.Loggable;
20 import fj.data.Either;
21 import io.swagger.v3.oas.annotations.Operation;
22 import io.swagger.v3.oas.annotations.Parameter;
23 import io.swagger.v3.oas.annotations.media.ArraySchema;
24 import io.swagger.v3.oas.annotations.media.Content;
25 import io.swagger.v3.oas.annotations.media.Schema;
26 import io.swagger.v3.oas.annotations.responses.ApiResponse;
27 import io.swagger.v3.oas.annotations.servers.Server;
28 import io.swagger.v3.oas.annotations.tags.Tag;
30 import java.io.IOException;
31 import java.util.List;
32 import javax.inject.Inject;
33 import javax.servlet.http.HttpServletRequest;
35 import javax.ws.rs.core.Context;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
40 import org.openecomp.sdc.be.components.impl.*;
41 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
42 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
43 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
47 import org.openecomp.sdc.be.externalapi.servlet.representation.AbstractTemplateInfo;
48 import org.openecomp.sdc.be.externalapi.servlet.representation.CopyServiceInfo;
49 import org.openecomp.sdc.be.impl.ComponentsUtils;
50 import org.openecomp.sdc.be.impl.ServletUtils;
51 import org.openecomp.sdc.be.model.*;
52 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
53 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
54 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
55 import org.openecomp.sdc.be.servlets.*;
56 import org.openecomp.sdc.be.user.UserBusinessLogic;
57 import org.openecomp.sdc.common.api.Constants;
58 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
59 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
60 import org.openecomp.sdc.common.log.enums.StatusCode;
61 import org.openecomp.sdc.common.log.wrappers.Logger;
62 import org.openecomp.sdc.exception.ResponseFormat;
63 import org.springframework.stereotype.Controller;
66 * This servlet provides external interfaces related to abstract templates.
71 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
73 @Tag(name = "SDCE-7 APIs")
77 public class AbstractTemplateServlet extends AbstractValidationsServlet {
80 private HttpServletRequest request;
82 private final ElementBusinessLogic elementBusinessLogic;
83 private final AbstractTemplateBusinessLogic abstractTemplateBusinessLogic;
85 private final ServiceBusinessLogic serviceBusinessLogic;
86 private final ResourceBusinessLogic resourceBusinessLogic;
88 private static final Logger log = Logger.getLogger(AbstractTemplateServlet.class);
89 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(AbstractTemplateServlet.class.getName());
92 public AbstractTemplateServlet(UserBusinessLogic userBusinessLogic,
93 ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
94 ServletUtils servletUtils, ResourceImportManager resourceImportManager,
95 ElementBusinessLogic elementBusinessLogic,
96 AbstractTemplateBusinessLogic abstractTemplateBusinessLogic, ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
97 super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
98 this.elementBusinessLogic = elementBusinessLogic;
99 this.abstractTemplateBusinessLogic = abstractTemplateBusinessLogic;
100 this.serviceBusinessLogic = serviceBusinessLogic;
101 this.resourceBusinessLogic = resourceBusinessLogic;
106 * @param instanceIdHeader
108 * @param authorization
113 @Path("/abstract/service/serviceUUID/{uuid}/status")
114 @Produces(MediaType.APPLICATION_JSON)
115 @Operation(description = "Fetch abstract status of service", method = "GET",
116 summary = "Return whether the service is a virtual service", responses = {@ApiResponse(responseCode = "200",
117 description = "The check result of whether the service is an abstract service is returned",
118 content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
119 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
120 @ApiResponse(responseCode = "401",
121 description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
122 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
123 @ApiResponse(responseCode = "404",
124 description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
125 @ApiResponse(responseCode = "405",
126 description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
127 @ApiResponse(responseCode = "500",
128 description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
129 @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
130 public Response getServiceAbstractStatus(
131 @Parameter(description = "X-ECOMP-RequestID header",
132 required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
133 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
134 value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
135 @Parameter(description = "Determines the format of the body of the response",
136 required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
137 @Parameter(description = "The username and password",
138 required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
139 @Parameter(description = "The requested asset uuid",
140 required = true) @PathParam("uuid") final String uuid) throws IOException {
142 ResponseFormat responseFormat = null;
143 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TEMPLATE_ABSTRACT_STATUS;
144 String requestURI = request.getRequestURI();
145 String url = request.getMethod() + " " + requestURI;
146 log.debug("getServiceAbstractStatus: Start handle request of {}", url);
148 String assetType = "services";
149 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
150 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
151 DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
153 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
154 log.debug("getServiceAbstractStatus: Missing X-ECOMP-InstanceID header");
155 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
156 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
157 resourceCommonInfo, requestId, uuid);
158 return buildErrorResponse(responseFormat);
163 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
165 if (assetTypeData.isRight()) {
166 log.debug("getServiceAbstractStatus: Service Fetching Failed");
167 responseFormat = assetTypeData.right().value();
168 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
169 resourceCommonInfo, requestId, uuid);
171 return buildErrorResponse(responseFormat);
173 resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
174 log.debug("getServiceAbstractStatus: Service Fetching Success");
175 Either<AbstractTemplateInfo, ResponseFormat> resMetadata = abstractTemplateBusinessLogic.getServiceAbstractStatus(assetTypeData.left().value());
176 if (resMetadata.isRight()) {
177 log.debug("getServiceAbstractStatus: Service abstract status get Failed");
178 responseFormat = resMetadata.right().value();
180 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
181 resourceCommonInfo, requestId, uuid);
182 return buildErrorResponse(responseFormat);
184 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
185 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
186 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
187 resourceCommonInfo, requestId, uuid);
189 return buildOkResponse(responseFormat, result);
190 } catch (Exception e) {
191 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch abstract status of service");
192 log.debug("getServiceAbstractStatus: Fetch abstract status of service with exception", e);
199 * @param instanceIdHeader
201 * @param authorization
206 @Path("/abstract/service/serviceUUID/{uuid}/copy")
207 @Produces(MediaType.APPLICATION_JSON)
208 @Operation(description = "Copy a new service based on the existing service", method = "POST",
209 summary = "Return whether the copy service is successful", responses = {@ApiResponse(responseCode = "200",
210 description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
211 content = @Content(array = @ArraySchema(schema = @Schema(implementation = AbstractTemplateInfo.class)))),
212 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
213 @ApiResponse(responseCode = "401",
214 description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
215 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
216 @ApiResponse(responseCode = "404",
217 description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
218 @ApiResponse(responseCode = "405",
219 description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
220 @ApiResponse(responseCode = "500",
221 description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000"),
222 @ApiResponse(responseCode = "409", description = "Service already exist")})
223 @PermissionAllowed(AafPermission.PermNames.WRITE_VALUE)
224 public Response copyExistService(
225 @Parameter(description = "The user id",
226 required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
227 @Parameter(description = "X-ECOMP-RequestID header",
228 required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
229 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
230 value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
231 @Parameter(description = "Determines the format of the body of the response",
232 required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
233 @Parameter(description = "The username and password",
234 required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
235 @Parameter(description = "The requested asset uuid",
236 required = true) @PathParam("uuid") final String uuid,
237 @Parameter(hidden = true) String data) throws IOException {
240 String url = request.getMethod() + " " + request.getRequestURI();
241 log.debug("copyExistService: Start handle request of {}", url);
242 User modifier = new User();
243 modifier.setUserId(userId);
244 log.debug("modifier id is {}", userId);
245 loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, StatusCode.STARTED, "Starting to create a service by user {} ", userId);
247 validateNotEmptyBody(data);
249 Either<CopyServiceInfo, ResponseFormat> convertResponse = parseToCopyServiceInfo(data, modifier);
250 if (convertResponse.isRight()) {
251 throw new ByResponseFormatComponentException(convertResponse.right().value());
254 String assetType = "services";
255 CopyServiceInfo copyServiceInfo = convertResponse.left().value();
256 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
258 if (assetTypeData.isRight() || assetTypeData.left().value().size() != 1) {
259 log.debug("getServiceAbstractStatus: Service Fetching Failed");
260 throw new ByResponseFormatComponentException(assetTypeData.right().value());
263 log.debug("getServiceAbstractStatus: Service Fetching Success");
265 Service service = (Service) assetTypeData.left().value().get(0);
266 List<String> tags = service.getTags();
267 if (tags != null && !tags.isEmpty()) {
268 for (int i = tags.size() - 1; i >= 0; i--) {
269 String tag = tags.get(i);
270 if (service.getName().equals(tag)) {
275 service.setName(copyServiceInfo.getNewServiceName());
276 tags.add(copyServiceInfo.getNewServiceName());
277 Either<Service, ResponseFormat> actionResponse = serviceBusinessLogic.createService(service, modifier);
279 if (actionResponse.isRight()) {
280 log.debug("Failed to create service");
281 throw new ByResponseFormatComponentException(actionResponse.right().value());
284 loggerSupportability.log(LoggerSupportabilityActions.CREATE_SERVICE, service.getComponentMetadataForSupportLog(), StatusCode.COMPLETE, "Service {} has been copyied by user {} ", service.getName(), userId);
286 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
290 public Either<CopyServiceInfo, ResponseFormat> parseToCopyServiceInfo(String serviceJson, User user) {
291 return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, CopyServiceInfo.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE);