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 ResponseFormat responseFormat = null;
164 String query = request.getQueryString();
165 String requestURI = request.getRequestURI().endsWith("/")?
166 removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
167 String url = request.getMethod() + " " + requestURI;
168 log.debug("Start handle request of {}", url);
170 AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
172 String resourceUrl = query == null ? requestURI : requestURI + "?" + query;
173 DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);
176 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
177 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
178 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
179 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
180 return buildErrorResponse(responseFormat);
184 Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
186 if (category != null) {
187 filters.put(FilterKeyEnum.CATEGORY, category);
189 if (subCategory != null) {
190 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
192 if (distributionStatus != null) {
193 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
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());
206 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getFilteredCatalogComponents(assetType, filters, query);
208 if (assetTypeData.isRight()) {
209 log.debug("getAssetList: Asset Fetching Failed");
210 responseFormat = assetTypeData.right().value();
211 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
212 return buildErrorResponse(responseFormat);
214 log.debug("getAssetList: Asset Fetching Success");
215 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter.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);
226 return buildOkResponse(responseFormat, result);
228 } catch (Exception e) {
229 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
230 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",
249 summary = "Returns detailed metadata of an asset by uuid", responses = {@ApiResponse(responseCode = "200",
250 description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
251 content = @Content(array = @ArraySchema(schema = @Schema(implementation = AssetMetadata.class)))),
252 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
253 @ApiResponse(responseCode = "401",
254 description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
255 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
256 @ApiResponse(responseCode = "404",
257 description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
258 @ApiResponse(responseCode = "405",
259 description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
260 @ApiResponse(responseCode = "500",
261 description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
262 @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
263 public Response getAssetSpecificMetadataByUuidExternal(
264 @Parameter(description = "X-ECOMP-RequestID header",
265 required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
266 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
267 value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
268 @Parameter(description = "Determines the format of the body of the response",
269 required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
270 @Parameter(description = "The username and password",
271 required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
272 @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),
273 required = true) @PathParam("assetType") final String assetType,
274 @Parameter(description = "The requested asset uuid",
275 required = true) @PathParam("uuid") final String uuid) throws IOException {
277 ResponseFormat responseFormat = null;
278 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
279 String requestURI = request.getRequestURI();
280 String url = request.getMethod() + " " + requestURI;
281 log.debug("Start handle request of {}", url);
283 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
284 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
285 DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
287 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
288 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
289 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
290 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
291 resourceCommonInfo, requestId, uuid);
292 return buildErrorResponse(responseFormat);
297 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
299 if (assetTypeData.isRight()) {
300 log.debug("getAssetList: Asset Fetching Failed");
301 responseFormat = assetTypeData.right().value();
302 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
303 resourceCommonInfo, requestId, uuid);
305 return buildErrorResponse(responseFormat);
307 resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
308 log.debug("getAssetList: Asset Fetching Success");
309 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
310 if (resMetadata.isRight()) {
311 log.debug("getAssetList: Asset conversion Failed");
312 responseFormat = resMetadata.right().value();
314 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
315 resourceCommonInfo, requestId, uuid);
316 return buildErrorResponse(responseFormat);
318 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
319 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
320 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
321 resourceCommonInfo, requestId, uuid);
323 return buildOkResponse(responseFormat, result);
324 } catch (Exception e) {
325 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
326 log.debug("getAssetList: Fetch list of assets failed with exception", e);
331 private ComponentBusinessLogic getComponentBLByType(ComponentTypeEnum componentTypeEnum) {
332 if(componentTypeEnum.equals(RESOURCE)) {
333 return resourceBusinessLogic;
335 // Implementation is the same for any ComponentBusinessLogic
336 return serviceBusinessLogic;
343 * @param instanceIdHeader
345 * @param authorization
352 @Path("/{assetType}/{uuid}/toscaModel")
353 @Produces(MediaType.APPLICATION_OCTET_STREAM)
354 @Operation(description = "Fetch assets CSAR", method = "GET", summary = "Returns asset csar", responses = {
355 @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
356 @ApiResponse(responseCode = "200",
357 description = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned",
358 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
359 @ApiResponse(responseCode = "400", description = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
360 @ApiResponse(responseCode = "401",
361 description = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
362 @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
363 @ApiResponse(responseCode = "404",
364 description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
365 @ApiResponse(responseCode = "405",
366 description = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
367 @ApiResponse(responseCode = "500",
368 description = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
369 @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
370 public Response getToscaModelExternal(
371 @Parameter(description = "X-ECOMP-RequestID header",
372 required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
373 @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(
374 value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
375 @Parameter(description = "Determines the format of the body of the response",
376 required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
377 @Parameter(description = "The username and password",
378 required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
379 @Parameter(description = "The requested asset type",schema = @Schema(allowableValues = {"resources", "services"}),
380 required = true) @PathParam("assetType") final String assetType,
381 @Parameter(description = "The requested asset uuid",
382 required = true) @PathParam("uuid") final String uuid) {
384 String url = request.getRequestURI();
385 log.debug("Start handle request of {} {}", request.getMethod(), url);
386 ResponseFormat responseFormat = null;
387 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
388 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
390 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
391 DistributionData distributionData = new DistributionData(instanceIdHeader, url);
393 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
394 log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
395 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
396 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
397 resourceCommonInfo, requestId, uuid);
398 return buildErrorResponse(responseFormat);
402 ComponentBusinessLogic componentBusinessLogic = getComponentBLByType(componentType);
403 ImmutablePair<String, byte[]> csarArtifact = componentBusinessLogic.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);
404 byte[] value = csarArtifact.getRight();
405 InputStream is = new ByteArrayInputStream(value);
406 String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
407 Map<String, String> headers = new HashMap<>();
408 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.getLeft()));
409 headers.put(Constants.MD5_HEADER, contenetMD5);
410 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
411 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
412 resourceCommonInfo, requestId, uuid);
413 return buildOkResponse(responseFormat, is, headers);
415 } catch (ComponentException e) {
416 responseFormat = e.getResponseFormat();
417 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
418 resourceCommonInfo, requestId, uuid);
419 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
420 log.debug("failed to get asset tosca model", e);
421 Response response = buildErrorResponse(responseFormat);
422 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
423 resourceCommonInfo, requestId, uuid);
429 private String removeDuplicateSlashSeparator(String requestUri) {
430 return requestUri.substring(0, requestUri.length()-1);