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=========================================================
21 package org.openecomp.sdc.be.externalapi.servlet;
23 import com.jcabi.aspects.Loggable;
24 import fj.data.Either;
25 import io.swagger.v3.oas.annotations.Operation;
26 import io.swagger.v3.oas.annotations.Parameter;
27 import io.swagger.v3.oas.annotations.media.ArraySchema;
28 import io.swagger.v3.oas.annotations.media.Content;
29 import io.swagger.v3.oas.annotations.media.Schema;
30 import io.swagger.v3.oas.annotations.responses.ApiResponse;
31 import io.swagger.v3.oas.annotations.servers.Server;
32 import io.swagger.v3.oas.annotations.servers.Servers;
33 import io.swagger.v3.oas.annotations.tags.Tag;
34 import io.swagger.v3.oas.annotations.tags.Tags;
35 import org.apache.commons.lang3.tuple.ImmutablePair;
36 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
37 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;
38 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
39 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
40 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
41 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
42 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
43 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
44 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
45 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
46 import org.openecomp.sdc.be.config.BeEcompErrorManager;
47 import org.openecomp.sdc.be.dao.api.ActionStatus;
48 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
49 import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
50 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
51 import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
52 import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;
53 import org.openecomp.sdc.be.impl.ComponentsUtils;
54 import org.openecomp.sdc.be.impl.ServletUtils;
55 import org.openecomp.sdc.be.model.Component;
56 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
57 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
58 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
59 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
60 import org.openecomp.sdc.be.servlets.RepresentationUtils;
61 import org.openecomp.sdc.be.user.UserBusinessLogic;
62 import org.openecomp.sdc.common.api.Constants;
63 import org.openecomp.sdc.common.log.wrappers.Logger;
64 import org.openecomp.sdc.common.util.GeneralUtility;
65 import org.openecomp.sdc.exception.ResponseFormat;
66 import org.springframework.stereotype.Controller;
68 import javax.inject.Inject;
69 import javax.servlet.http.HttpServletRequest;
70 import javax.ws.rs.GET;
71 import javax.ws.rs.HeaderParam;
72 import javax.ws.rs.Path;
73 import javax.ws.rs.PathParam;
74 import javax.ws.rs.Produces;
75 import javax.ws.rs.QueryParam;
76 import javax.ws.rs.core.Context;
77 import javax.ws.rs.core.MediaType;
78 import javax.ws.rs.core.Response;
79 import java.io.ByteArrayInputStream;
80 import java.io.IOException;
81 import java.io.InputStream;
82 import java.util.EnumMap;
83 import java.util.HashMap;
84 import java.util.List;
87 import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE;
90 * This Servlet serves external users for retrieving component metadata.
96 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
98 @Tags({@Tag(name = "SDC External APIs")})
99 @Servers({@Server(url = "/sdc")})
101 public class AssetsDataServlet extends AbstractValidationsServlet {
104 private HttpServletRequest request;
106 private static final Logger log = Logger.getLogger(AssetsDataServlet.class);
108 private final ElementBusinessLogic elementBusinessLogic;
109 private final AssetMetadataConverter assetMetadataConverter;
110 private final ServiceBusinessLogic serviceBusinessLogic;
111 private final ResourceBusinessLogic resourceBusinessLogic;
112 private final ComponentBusinessLogicProvider componentBusinessLogicProvider;
115 public AssetsDataServlet(UserBusinessLogic userBusinessLogic, ComponentInstanceBusinessLogic componentInstanceBL,
116 ComponentsUtils componentsUtils, ServletUtils servletUtils, ResourceImportManager resourceImportManager,
117 ElementBusinessLogic elementBusinessLogic, AssetMetadataConverter assetMetadataConverter,
118 ComponentBusinessLogicProvider componentBusinessLogicProvider, ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
119 super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
120 this.elementBusinessLogic = elementBusinessLogic;
121 this.assetMetadataConverter = assetMetadataConverter;
122 this.serviceBusinessLogic = serviceBusinessLogic;
123 this.resourceBusinessLogic = resourceBusinessLogic;
124 this.componentBusinessLogicProvider = componentBusinessLogicProvider;
128 @Path("/{assetType}")
129 @Produces(MediaType.APPLICATION_JSON)
130 @Operation(description = "Fetch list of assets", method = "GET", summary = "Returns list of assets", responses = {
131 @ApiResponse(responseCode = "200",
132 description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
133 content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
134 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
135 @ApiResponse(responseCode = "401",
136 description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
137 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
138 @ApiResponse(responseCode = "405",
139 description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
140 @ApiResponse(responseCode = "500",
141 description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
142 @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
143 public Response getAssetListExternal(
144 @Parameter(description = "X-ECOMP-RequestID header",
145 required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
146 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
147 value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
148 @Parameter(description = "Determines the format of the body of the response",
149 required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
150 @Parameter(description = "The username and password",
151 required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
152 @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),
153 required = true) @PathParam("assetType") final String assetType,
154 @Parameter(description = "The filter key (resourceType only for resources)",
155 required = false) @QueryParam("category") String category,
156 @Parameter(description = "The filter key (resourceType only for resources)",
157 required = false) @QueryParam("subCategory") String subCategory,
158 @Parameter(description = "The filter key (resourceType only for resources)",
159 required = false) @QueryParam("distributionStatus") String distributionStatus,
160 @Parameter(description = "The filter key (resourceType only for resources)",
161 required = false) @QueryParam("resourceType") String resourceType) throws IOException {
163 Response response = null;
164 ResponseFormat responseFormat = null;
165 String query = request.getQueryString();
166 String requestURI = request.getRequestURI().endsWith("/")?
167 removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
168 String url = request.getMethod() + " " + requestURI;
169 log.debug("Start handle request of {}", url);
171 AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
173 String resourceUrl = query == null ? requestURI : requestURI + "?" + query;
174 DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);
177 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
178 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
179 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
180 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
181 return buildErrorResponse(responseFormat);
185 Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
187 if (category != null) {
188 filters.put(FilterKeyEnum.CATEGORY, category);
190 if (subCategory != null) {
191 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
193 if (distributionStatus != null) {
194 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
196 if (resourceType != null) {
197 ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
198 if (resourceTypeEnum == null) {
199 log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
200 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
201 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
202 return buildErrorResponse(responseFormat);
204 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
207 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getFilteredCatalogComponents(assetType, filters, query);
209 if (assetTypeData.isRight()) {
210 log.debug("getAssetList: Asset Fetching Failed");
211 responseFormat = assetTypeData.right().value();
212 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
213 return buildErrorResponse(responseFormat);
215 log.debug("getAssetList: Asset Fetching Success");
216 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
217 if (resMetadata.isRight()) {
218 log.debug("getAssetList: Asset conversion Failed");
219 responseFormat = resMetadata.right().value();
220 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
221 return buildErrorResponse(responseFormat);
223 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
224 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
225 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
227 response = buildOkResponse(responseFormat, result);
230 } catch (Exception e) {
231 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
232 log.debug("getAssetList: Fetch list of assets failed with exception", e);
240 * @param instanceIdHeader
242 * @param authorization
248 @Path("/{assetType}/{uuid}/metadata")
249 @Produces(MediaType.APPLICATION_JSON)
250 @Operation(description = "Detailed metadata of asset by uuid", method = "GET",
251 summary = "Returns detailed metadata of an asset by uuid", responses = {@ApiResponse(responseCode = "200",
252 description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
253 content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
254 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
255 @ApiResponse(responseCode = "401",
256 description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
257 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
258 @ApiResponse(responseCode = "404",
259 description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
260 @ApiResponse(responseCode = "405",
261 description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
262 @ApiResponse(responseCode = "500",
263 description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
264 @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
265 public Response getAssetSpecificMetadataByUuidExternal(
266 @Parameter(description = "X-ECOMP-RequestID header",
267 required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
268 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
269 value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
270 @Parameter(description = "Determines the format of the body of the response",
271 required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
272 @Parameter(description = "The username and password",
273 required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
274 @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),
275 required = true) @PathParam("assetType") final String assetType,
276 @Parameter(description = "The requested asset uuid",
277 required = true) @PathParam("uuid") final String uuid) throws IOException {
279 Response response = null;
280 ResponseFormat responseFormat = null;
281 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
282 String requestURI = request.getRequestURI();
283 String url = request.getMethod() + " " + requestURI;
284 log.debug("Start handle request of {}", url);
286 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
287 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
288 DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
290 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
291 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
292 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
293 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
294 resourceCommonInfo, requestId, uuid);
295 return buildErrorResponse(responseFormat);
300 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
302 if (assetTypeData.isRight()) {
303 log.debug("getAssetList: Asset Fetching Failed");
304 responseFormat = assetTypeData.right().value();
305 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
306 resourceCommonInfo, requestId, uuid);
308 return buildErrorResponse(responseFormat);
310 resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
311 log.debug("getAssetList: Asset Fetching Success");
312 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
313 if (resMetadata.isRight()) {
314 log.debug("getAssetList: Asset conversion Failed");
315 responseFormat = resMetadata.right().value();
317 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
318 resourceCommonInfo, requestId, uuid);
319 return buildErrorResponse(responseFormat);
321 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
322 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
323 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
324 resourceCommonInfo, requestId, uuid);
326 response = buildOkResponse(responseFormat, result);
329 } catch (Exception e) {
330 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
331 log.debug("getAssetList: Fetch list of assets failed with exception", e);
336 private ComponentBusinessLogic getComponentBLByType(ComponentTypeEnum componentTypeEnum) {
337 if(componentTypeEnum.equals(RESOURCE)) {
338 return resourceBusinessLogic;
340 // Implementation is the same for any ComponentBusinessLogic
341 return serviceBusinessLogic;
348 * @param instanceIdHeader
350 * @param authorization
357 @Path("/{assetType}/{uuid}/toscaModel")
358 @Produces(MediaType.APPLICATION_OCTET_STREAM)
359 @Operation(description = "Fetch assets CSAR", method = "GET", summary = "Returns asset csar", responses = {
360 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
361 @ApiResponse(responseCode = "200",
362 description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
363 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
364 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
365 @ApiResponse(responseCode = "401",
366 description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
367 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
368 @ApiResponse(responseCode = "404",
369 description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
370 @ApiResponse(responseCode = "405",
371 description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
372 @ApiResponse(responseCode = "500",
373 description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
374 @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
375 public Response getToscaModelExternal(
376 @Parameter(description = "X-ECOMP-RequestID header",
377 required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
378 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
379 value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
380 @Parameter(description = "Determines the format of the body of the response",
381 required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
382 @Parameter(description = "The username and password",
383 required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
384 @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),
385 required = true) @PathParam("assetType") final String assetType,
386 @Parameter(description = "The requested asset uuid",
387 required = true) @PathParam("uuid") final String uuid) {
389 String url = request.getRequestURI();
390 log.debug("Start handle request of {} {}", request.getMethod(), url);
391 Response response = null;
392 ResponseFormat responseFormat = null;
393 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
394 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
396 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
397 DistributionData distributionData = new DistributionData(instanceIdHeader, url);
399 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
400 log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
401 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
402 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
403 resourceCommonInfo, requestId, uuid);
404 return buildErrorResponse(responseFormat);
408 ComponentBusinessLogic componentBusinessLogic = getComponentBLByType(componentType);
409 ImmutablePair<String, byte[]> csarArtifact = componentBusinessLogic.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);
410 byte[] value = csarArtifact.getRight();
411 InputStream is = new ByteArrayInputStream(value);
412 String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
413 Map<String, String> headers = new HashMap<>();
414 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.getLeft()));
415 headers.put(Constants.MD5_HEADER, contenetMD5);
416 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
417 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
418 resourceCommonInfo, requestId, uuid);
419 response = buildOkResponse(responseFormat, is, headers);
422 } catch (ComponentException e) {
423 responseFormat = e.getResponseFormat();
424 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
425 resourceCommonInfo, requestId, uuid);
426 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
427 log.debug("failed to get asset tosca model", e);
428 response = buildErrorResponse(responseFormat);
429 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
430 resourceCommonInfo, requestId, uuid);
436 private String removeDuplicateSlashSeparator(String requestUri) {
437 return requestUri.substring(0, requestUri.length()-1);