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.Comparator;
39 import java.util.EnumMap;
40 import java.util.HashMap;
41 import java.util.List;
43 import javax.inject.Inject;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.ws.rs.GET;
46 import javax.ws.rs.HeaderParam;
47 import javax.ws.rs.Path;
48 import javax.ws.rs.PathParam;
49 import javax.ws.rs.Produces;
50 import javax.ws.rs.QueryParam;
51 import javax.ws.rs.core.Context;
52 import javax.ws.rs.core.MediaType;
53 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.exceptions.ComponentException;
63 import org.openecomp.sdc.be.config.BeEcompErrorManager;
64 import org.openecomp.sdc.be.dao.api.ActionStatus;
65 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
66 import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
67 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
68 import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
69 import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;
70 import org.openecomp.sdc.be.externalapi.servlet.representation.ServiceAssetMetadata;
71 import org.openecomp.sdc.be.impl.ComponentsUtils;
72 import org.openecomp.sdc.be.impl.ServletUtils;
73 import org.openecomp.sdc.be.model.Component;
74 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
75 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
76 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
77 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
78 import org.openecomp.sdc.be.servlets.RepresentationUtils;
79 import org.openecomp.sdc.common.api.Constants;
80 import org.openecomp.sdc.common.log.wrappers.Logger;
81 import org.openecomp.sdc.common.util.GeneralUtility;
82 import org.openecomp.sdc.exception.ResponseFormat;
83 import org.springframework.stereotype.Controller;
86 * This Servlet serves external users for retrieving component metadata.
90 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
92 @Tag(name = "SDCE-7 APIs")
95 public class AssetsDataServlet extends AbstractValidationsServlet {
97 private static final Logger log = Logger.getLogger(AssetsDataServlet.class);
98 private final ElementBusinessLogic elementBL;
99 private final AssetMetadataConverter assetMetadataConverter;
100 private final ServiceBusinessLogic serviceBL;
101 private final ResourceBusinessLogic resourceBL;
103 private HttpServletRequest request;
106 public AssetsDataServlet(ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils, ServletUtils servletUtils,
107 ResourceImportManager resourceImportManager, ElementBusinessLogic elementBL,
108 AssetMetadataConverter assetMetadataConverter, ServiceBusinessLogic serviceBL,
109 ResourceBusinessLogic resourceBL) {
110 super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
111 this.elementBL = elementBL;
112 this.assetMetadataConverter = assetMetadataConverter;
113 this.serviceBL = serviceBL;
114 this.resourceBL = resourceBL;
118 @Path("/{assetType}")
119 @Produces(MediaType.APPLICATION_JSON)
120 @Operation(description = "Fetch list of assets", method = "GET", summary = "Returns list of assets", responses = {
121 @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)))),
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 = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
126 @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")})
127 public Response getAssetListExternal(
128 @Parameter(description = "X-ECOMP-RequestID header") @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
129 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
130 @Parameter(description = "Determines the format of the body of the response") @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
131 @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
132 @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
133 "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 = "Additional metadata keys to include in the response, not all keys are supported.\nSupported keys: lastUpdateDate, creationDate, description, uniqueId and category specific metadata keys")
140 @QueryParam("include") List<String> additionalMetadataKeysToInclude,
141 @Parameter(description = "The version(s) to filter the result set on\n" +
142 "Syntax: /services?version=(highestMatchingVersionOnly|lessThan|greaterThan|equals)(:=)(value)",
145 name = "An example request to get each service with highest version",
146 value = "highestMatchingVersionOnly:true"),
148 name = "An example request to get all services with version less than 2.1",
149 value = "lessThan:2.1"),
151 name = "An example request to get all services with version equal 2.0",
152 value = "equals:2.0"),
154 name = "An example request to get all services with version greater than 1.1",
155 value = "greaterThan:1.1")})
156 @QueryParam("version") String version,
157 @Parameter(description = "The keys of the metadata to include in the entries in the result set. Only applicable when assetType = services\n" +
158 "Only category specific metadata keys are supported\n" +
159 "Syntax: /services?metadata=<KEY1>(:=)<VALUE1>&metadata=<KEY2>(:=)<VALUE2> ...",
162 name = "An example request to get all services matching following Category Specific Metadata condition 'ETSI Version=3.3.1'",
163 value = "ETSI Version:3.3.1")})
164 @QueryParam("metadata") List<String> metadata) throws IOException {
165 ResponseFormat responseFormat;
166 final String query = request.getQueryString();
167 final String requestURI =
168 request.getRequestURI().endsWith("/") ? removeDuplicateSlashSeparator(request.getRequestURI()) : request.getRequestURI();
169 final String url = request.getMethod() + " " + requestURI;
170 log.debug("Start handle request of {}", url);
171 final AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
172 final String resourceUrl = query == null ? requestURI : requestURI + "?" + query;
173 final DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);
175 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
176 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
177 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
178 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
179 return buildErrorResponse(responseFormat);
182 final Map<FilterKeyEnum, Object> filters = new EnumMap<>(FilterKeyEnum.class);
183 if (category != null) {
184 filters.put(FilterKeyEnum.CATEGORY, category);
186 if (subCategory != null) {
187 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
189 if (distributionStatus != null) {
190 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
192 if (version != null) {
193 filters.put(FilterKeyEnum.VERSION, version);
195 if (CollectionUtils.isNotEmpty(metadata)) {
196 filters.put(FilterKeyEnum.METADATA, metadata);
198 if (resourceType != null) {
199 ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
200 if (resourceTypeEnum == null) {
201 log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
202 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
203 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
204 return buildErrorResponse(responseFormat);
206 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
208 final Either<List<? extends Component>, ResponseFormat> componentList = elementBL.getFilteredCatalogComponents(assetType, filters, query);
209 if (componentList.isRight()) {
210 log.debug("getAssetList: Asset Fetching Failed");
211 responseFormat = componentList.right().value();
212 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
213 return buildErrorResponse(responseFormat);
215 log.debug("getAssetList: Asset Fetching Success");
216 final Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
217 .convertToAssetMetadata(componentList.left().value(), requestURI, false, additionalMetadataKeysToInclude);
218 if (resMetadata.isRight()) {
219 log.debug("getAssetList: Asset conversion Failed");
220 responseFormat = resMetadata.right().value();
221 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
222 return buildErrorResponse(responseFormat);
224 final Object result = RepresentationUtils.toRepresentation(sortIfNeed(resMetadata.left().value(), additionalMetadataKeysToInclude));
225 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
226 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
227 return buildOkResponse(responseFormat, result);
229 } catch (Exception e) {
230 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
231 log.debug("getAssetList: Fetch list of assets failed with exception", e);
238 * @param instanceIdHeader
240 * @param authorization
246 @Path("/{assetType}/{uuid}/metadata")
247 @Produces(MediaType.APPLICATION_JSON)
248 @Operation(description = "Detailed metadata of asset by uuid", method = "GET", summary = "Returns detailed metadata of an asset by uuid", responses = {
249 @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)))),
250 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
251 @ApiResponse(responseCode = "401", description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
252 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
253 @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
254 @ApiResponse(responseCode = "405", description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
255 @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")})
256 public Response getAssetSpecificMetadataByUuidExternal(
257 @Parameter(description = "X-ECOMP-RequestID header") @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
258 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
259 @Parameter(description = "Determines the format of the body of the response") @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
260 @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
261 @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
262 "services"}), required = true) @PathParam("assetType") final String assetType,
263 @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) throws IOException {
264 ResponseFormat responseFormat = null;
265 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
266 String requestURI = request.getRequestURI();
267 String url = request.getMethod() + " " + requestURI;
268 log.debug("Start handle request of {}", url);
269 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
270 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
271 DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
273 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
274 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
275 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
276 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
277 return buildErrorResponse(responseFormat);
280 final Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBL.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, null);
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)) {
312 // Implementation is the same for any ComponentBusinessLogic
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 public Response getToscaModelExternal(
339 @Parameter(description = "X-ECOMP-RequestID header") @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
340 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
341 @Parameter(description = "Determines the format of the body of the response") @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
342 @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
343 @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
344 "services"}), required = true) @PathParam("assetType") final String assetType,
345 @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) {
346 String url = request.getRequestURI();
347 log.debug("Start handle request of {} {}", request.getMethod(), url);
348 ResponseFormat responseFormat = null;
349 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
350 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
351 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
352 DistributionData distributionData = new DistributionData(instanceIdHeader, url);
353 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
354 log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
355 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
356 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
357 return buildErrorResponse(responseFormat);
360 ComponentBusinessLogic componentBusinessLogic = getComponentBLByType(componentType);
361 ImmutablePair<String, byte[]> csarArtifact = componentBusinessLogic.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);
362 byte[] value = csarArtifact.getRight();
363 InputStream is = new ByteArrayInputStream(value);
364 String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
365 Map<String, String> headers = new HashMap<>();
366 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.getLeft()));
367 headers.put(Constants.MD5_HEADER, contenetMD5);
368 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
369 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
370 return buildOkResponse(responseFormat, is, headers);
371 } catch (ComponentException e) {
372 responseFormat = e.getResponseFormat();
373 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
374 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
375 log.debug("failed to get asset tosca model", e);
376 Response response = buildErrorResponse(responseFormat);
377 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
382 private String removeDuplicateSlashSeparator(String requestUri) {
383 return requestUri.substring(0, requestUri.length() - 1);
386 private List<? extends AssetMetadata> sortIfNeed(final List<? extends AssetMetadata> assetMetadataList,
387 final List<String> additionalMetadataKeysToInclude) {
388 if (additionalMetadataKeysToInclude.contains("creationDate")) {
389 assetMetadataList.sort(
390 Comparator.comparing((AssetMetadata am) -> ((ServiceAssetMetadata) am).getAdditionalRequestedMetadata().get("creationDate")));
392 return assetMetadataList;