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.externalapi.servlet;
22 import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE;
24 import com.jcabi.aspects.Loggable;
25 import fj.data.Either;
26 import io.swagger.v3.oas.annotations.Operation;
27 import io.swagger.v3.oas.annotations.Parameter;
28 import io.swagger.v3.oas.annotations.media.ArraySchema;
29 import io.swagger.v3.oas.annotations.media.Content;
30 import io.swagger.v3.oas.annotations.media.ExampleObject;
31 import io.swagger.v3.oas.annotations.media.Schema;
32 import io.swagger.v3.oas.annotations.responses.ApiResponse;
33 import io.swagger.v3.oas.annotations.servers.Server;
34 import io.swagger.v3.oas.annotations.tags.Tag;
35 import java.io.ByteArrayInputStream;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.util.EnumMap;
39 import java.util.HashMap;
40 import java.util.List;
42 import javax.inject.Inject;
43 import javax.servlet.http.HttpServletRequest;
44 import javax.ws.rs.GET;
45 import javax.ws.rs.HeaderParam;
46 import javax.ws.rs.Path;
47 import javax.ws.rs.PathParam;
48 import javax.ws.rs.Produces;
49 import javax.ws.rs.QueryParam;
50 import javax.ws.rs.core.Context;
51 import javax.ws.rs.core.MediaType;
52 import javax.ws.rs.core.Response;
54 import org.apache.commons.collections4.CollectionUtils;
55 import org.apache.commons.lang3.tuple.ImmutablePair;
56 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
57 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
58 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
59 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
60 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
61 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
62 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
63 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
64 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
65 import org.openecomp.sdc.be.config.BeEcompErrorManager;
66 import org.openecomp.sdc.be.dao.api.ActionStatus;
67 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
68 import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
69 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
70 import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
71 import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;
72 import org.openecomp.sdc.be.impl.ComponentsUtils;
73 import org.openecomp.sdc.be.impl.ServletUtils;
74 import org.openecomp.sdc.be.model.Component;
75 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
76 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
77 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
78 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
79 import org.openecomp.sdc.be.servlets.RepresentationUtils;
80 import org.openecomp.sdc.common.api.Constants;
81 import org.openecomp.sdc.common.log.wrappers.Logger;
82 import org.openecomp.sdc.common.util.GeneralUtility;
83 import org.openecomp.sdc.exception.ResponseFormat;
84 import org.springframework.stereotype.Controller;
87 * This Servlet serves external users for retrieving component metadata.
91 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
93 @Tag(name = "SDCE-7 APIs")
96 public class AssetsDataServlet extends AbstractValidationsServlet {
98 private static final Logger log = Logger.getLogger(AssetsDataServlet.class);
99 private final ElementBusinessLogic elementBusinessLogic;
100 private final AssetMetadataConverter assetMetadataConverter;
101 private final ServiceBusinessLogic serviceBusinessLogic;
102 private final ResourceBusinessLogic resourceBusinessLogic;
104 private HttpServletRequest request;
107 public AssetsDataServlet(ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, ServletUtils servletUtils,
108 ResourceImportManager resourceImportManager, ElementBusinessLogic elementBusinessLogic,
109 AssetMetadataConverter assetMetadataConverter, ServiceBusinessLogic serviceBusinessLogic,
110 ResourceBusinessLogic resourceBusinessLogic) {
111 super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
112 this.elementBusinessLogic = elementBusinessLogic;
113 this.assetMetadataConverter = assetMetadataConverter;
114 this.serviceBusinessLogic = serviceBusinessLogic;
115 this.resourceBusinessLogic = resourceBusinessLogic;
119 @Path("/{assetType}")
120 @Produces(MediaType.APPLICATION_JSON)
121 @Operation(description = "Fetch list of assets", method = "GET", summary = "Returns list of assets", responses = {
122 @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
123 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
124 @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
125 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
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 getAssetListExternal(
130 @Parameter(description = "X-ECOMP-RequestID header") @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") @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 type", schema = @Schema(allowableValues = {"resources", "services"}), required = true) @PathParam("assetType") final String assetType,
135 @Parameter(description = "The category to filter the result set on") @QueryParam("category") String category,
136 @Parameter(description = "The sub category to filter the result set on. Only applicable when assetType = resources") @QueryParam("subCategory") String subCategory,
137 @Parameter(description = "The distribution status to filter the result set on") @QueryParam("distributionStatus") String distributionStatus,
138 @Parameter(description = "The resource type to filter the result set on. Only applicable when assetType = resources") @QueryParam("resourceType") String resourceType,
139 @Parameter(description = "The version(s) to filter the result set on\n" +
140 "Syntax: /services?version=(highestMatchingVersionOnly|lessThan|greaterThan|equals)(:=)(value)",
143 name = "An example request to get each service with highest version",
144 value = "highestMatchingVersionOnly:true"),
146 name = "An example request to get all services with version less than 2.1",
147 value = "lessThan:2.1"),
149 name = "An example request to get all services with version equal 2.0",
150 value = "equals:2.0"),
152 name = "An example request to get all services with version greater than 1.1",
153 value = "greaterThan:1.1")})
154 @QueryParam("version") String version,
155 @Parameter(description = "The keys of the metadata to include in the entries in the result set. Only applicable when assetType = services\n" +
156 "Only category specific metadata keys are supported\n" +
157 "Syntax: /services?metadata=<KEY1>(:=)<VALUE1>&metadata=<KEY2>(:=)<VALUE2> ...",
160 name = "An example request to get all services matching following Category Specific Metadata condition 'ETSI Version=3.3.1'",
161 value = "ETSI Version:3.3.1")})
162 @QueryParam("metadata") List<String> metadata) throws IOException {
163 ResponseFormat responseFormat;
164 String query = request.getQueryString();
165 String requestURI = request.getRequestURI().endsWith("/") ? removeDuplicateSlashSeparator(request.getRequestURI()) : request.getRequestURI();
166 String url = request.getMethod() + " " + requestURI;
167 log.debug("Start handle request of {}", url);
168 AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
169 String resourceUrl = query == null ? requestURI : requestURI + "?" + query;
170 DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);
172 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
173 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
174 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
175 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
176 return buildErrorResponse(responseFormat);
179 Map<FilterKeyEnum, Object> filters = new EnumMap<>(FilterKeyEnum.class);
180 if (category != null) {
181 filters.put(FilterKeyEnum.CATEGORY, category);
183 if (subCategory != null) {
184 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
186 if (distributionStatus != null) {
187 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
189 if (version != null) {
190 filters.put(FilterKeyEnum.VERSION, version);
192 if (CollectionUtils.isNotEmpty(metadata)) {
193 filters.put(FilterKeyEnum.METADATA, metadata);
195 if (resourceType != null) {
196 ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
197 if (resourceTypeEnum == null) {
198 log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
199 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
200 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
201 return buildErrorResponse(responseFormat);
203 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
205 Either<List<? extends Component>, ResponseFormat> assetTypeData
206 = elementBusinessLogic.getFilteredCatalogComponents(assetType, filters, query);
207 if (assetTypeData.isRight()) {
208 log.debug("getAssetList: Asset Fetching Failed");
209 responseFormat = assetTypeData.right().value();
210 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
211 return buildErrorResponse(responseFormat);
213 log.debug("getAssetList: Asset Fetching Success");
214 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
215 .convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
216 if (resMetadata.isRight()) {
217 log.debug("getAssetList: Asset conversion Failed");
218 responseFormat = resMetadata.right().value();
219 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
220 return buildErrorResponse(responseFormat);
222 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
223 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
224 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
225 return buildOkResponse(responseFormat, result);
227 } catch (Exception e) {
228 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
229 log.debug("getAssetList: Fetch list of assets failed with exception", e);
236 * @param instanceIdHeader
238 * @param authorization
244 @Path("/{assetType}/{uuid}/metadata")
245 @Produces(MediaType.APPLICATION_JSON)
246 @Operation(description = "Detailed metadata of asset by uuid", method = "GET", summary = "Returns detailed metadata of an asset by uuid", responses = {
247 @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
248 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
249 @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
250 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
251 @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
252 @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
253 @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")})
254 @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
255 public Response getAssetSpecificMetadataByUuidExternal(
256 @Parameter(description = "X-ECOMP-RequestID header") @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
257 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
258 @Parameter(description = "Determines the format of the body of the response") @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
259 @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
260 @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
261 "services"}), required = true) @PathParam("assetType") final String assetType,
262 @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) throws IOException {
263 ResponseFormat responseFormat = null;
264 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
265 String requestURI = request.getRequestURI();
266 String url = request.getMethod() + " " + requestURI;
267 log.debug("Start handle request of {}", url);
268 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
269 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
270 DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
272 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
273 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
274 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
275 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
276 return buildErrorResponse(responseFormat);
279 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
280 .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
281 if (assetTypeData.isRight()) {
282 log.debug("getAssetList: Asset Fetching Failed");
283 responseFormat = assetTypeData.right().value();
284 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
285 return buildErrorResponse(responseFormat);
287 resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
288 log.debug("getAssetList: Asset Fetching Success");
289 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
290 .convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
291 if (resMetadata.isRight()) {
292 log.debug("getAssetList: Asset conversion Failed");
293 responseFormat = resMetadata.right().value();
294 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
295 return buildErrorResponse(responseFormat);
297 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
298 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
299 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
300 return buildOkResponse(responseFormat, result);
301 } catch (Exception e) {
302 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
303 log.debug("getAssetList: Fetch list of assets failed with exception", e);
308 private ComponentBusinessLogic getComponentBLByType(ComponentTypeEnum componentTypeEnum) {
309 if (componentTypeEnum.equals(RESOURCE)) {
310 return resourceBusinessLogic;
312 // Implementation is the same for any ComponentBusinessLogic
313 return serviceBusinessLogic;
319 * @param instanceIdHeader
321 * @param authorization
327 @Path("/{assetType}/{uuid}/toscaModel")
328 @Produces(MediaType.APPLICATION_OCTET_STREAM)
329 @Operation(description = "Fetch assets CSAR", method = "GET", summary = "Returns asset csar", responses = {
330 @ApiResponse(description = "default response", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
331 @ApiResponse(responseCode = "200", description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
332 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
333 @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
334 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
335 @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
336 @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
337 @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")})
338 @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
339 public Response getToscaModelExternal(
340 @Parameter(description = "X-ECOMP-RequestID header") @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
341 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
342 @Parameter(description = "Determines the format of the body of the response") @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
343 @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
344 @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
345 "services"}), required = true) @PathParam("assetType") final String assetType,
346 @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) {
347 String url = request.getRequestURI();
348 log.debug("Start handle request of {} {}", request.getMethod(), url);
349 ResponseFormat responseFormat = null;
350 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
351 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
352 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
353 DistributionData distributionData = new DistributionData(instanceIdHeader, url);
354 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
355 log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
356 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
357 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
358 return buildErrorResponse(responseFormat);
361 ComponentBusinessLogic componentBusinessLogic = getComponentBLByType(componentType);
362 ImmutablePair<String, byte[]> csarArtifact = componentBusinessLogic.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);
363 byte[] value = csarArtifact.getRight();
364 InputStream is = new ByteArrayInputStream(value);
365 String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
366 Map<String, String> headers = new HashMap<>();
367 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.getLeft()));
368 headers.put(Constants.MD5_HEADER, contenetMD5);
369 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
370 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
371 return buildOkResponse(responseFormat, is, headers);
372 } catch (ComponentException e) {
373 responseFormat = e.getResponseFormat();
374 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
375 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
376 log.debug("failed to get asset tosca model", e);
377 Response response = buildErrorResponse(responseFormat);
378 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
383 private String removeDuplicateSlashSeparator(String requestUri) {
384 return requestUri.substring(0, requestUri.length() - 1);