cb32f152d0803e748b396e094552c179f1759198
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / externalapi / servlet / AssetsDataServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20 package org.openecomp.sdc.be.externalapi.servlet;
21
22 import static org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum.RESOURCE;
23
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.Schema;
31 import io.swagger.v3.oas.annotations.responses.ApiResponse;
32 import io.swagger.v3.oas.annotations.servers.Server;
33 import io.swagger.v3.oas.annotations.servers.Servers;
34 import io.swagger.v3.oas.annotations.tags.Tag;
35 import io.swagger.v3.oas.annotations.tags.Tags;
36 import java.io.ByteArrayInputStream;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.util.EnumMap;
40 import java.util.HashMap;
41 import java.util.List;
42 import java.util.Map;
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.lang3.tuple.ImmutablePair;
55 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
56 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;
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;
85
86 /**
87  * This Servlet serves external users for retrieving component metadata.
88  *
89  * @author tgitelman
90  */
91 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
92 @Path("/v1/catalog")
93 @Tags({@Tag(name = "SDCE-7 APIs")})
94 @Servers({@Server(url = "/sdc")})
95 @Controller
96 public class AssetsDataServlet extends AbstractValidationsServlet {
97
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;
103     private final ComponentBusinessLogicProvider componentBusinessLogicProvider;
104     @Context
105     private HttpServletRequest request;
106
107     @Inject
108     public AssetsDataServlet(ComponentInstanceBusinessLogic componentInstanceBL, ComponentsUtils componentsUtils,
109                              ServletUtils servletUtils, ResourceImportManager resourceImportManager, ElementBusinessLogic elementBusinessLogic,
110                              AssetMetadataConverter assetMetadataConverter, ComponentBusinessLogicProvider componentBusinessLogicProvider,
111                              ServiceBusinessLogic serviceBusinessLogic, ResourceBusinessLogic resourceBusinessLogic) {
112         super(componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
113         this.elementBusinessLogic = elementBusinessLogic;
114         this.assetMetadataConverter = assetMetadataConverter;
115         this.serviceBusinessLogic = serviceBusinessLogic;
116         this.resourceBusinessLogic = resourceBusinessLogic;
117         this.componentBusinessLogicProvider = componentBusinessLogicProvider;
118     }
119
120     @GET
121     @Path("/{assetType}")
122     @Produces(MediaType.APPLICATION_JSON)
123     @Operation(description = "Fetch list of assets", method = "GET", summary = "Returns list of assets", responses = {
124         @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)))),
125         @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
126         @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
127         @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
128         @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
129         @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")})
130     @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
131     public Response getAssetListExternal(
132         @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
133         @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
134         @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
135         @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
136         @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
137             "services"}), required = true) @PathParam("assetType") final String assetType,
138         @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("category") String category,
139         @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("subCategory") String subCategory,
140         @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("distributionStatus") String distributionStatus,
141         @Parameter(description = "The filter key (resourceType only for resources)", required = false) @QueryParam("resourceType") String resourceType)
142         throws IOException {
143         ResponseFormat responseFormat = null;
144         String query = request.getQueryString();
145         String requestURI = request.getRequestURI().endsWith("/") ? removeDuplicateSlashSeparator(request.getRequestURI()) : request.getRequestURI();
146         String url = request.getMethod() + " " + requestURI;
147         log.debug("Start handle request of {}", url);
148         AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
149         String resourceUrl = query == null ? requestURI : requestURI + "?" + query;
150         DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);
151         // Mandatory
152         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
153             log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
154             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
155             getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
156             return buildErrorResponse(responseFormat);
157         }
158         try {
159             Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
160             if (category != null) {
161                 filters.put(FilterKeyEnum.CATEGORY, category);
162             }
163             if (subCategory != null) {
164                 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
165             }
166             if (distributionStatus != null) {
167                 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
168             }
169             if (resourceType != null) {
170                 ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
171                 if (resourceTypeEnum == null) {
172                     log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
173                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
174                     getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
175                     return buildErrorResponse(responseFormat);
176                 }
177                 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
178             }
179             Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
180                 .getFilteredCatalogComponents(assetType, filters, query);
181             if (assetTypeData.isRight()) {
182                 log.debug("getAssetList: Asset Fetching Failed");
183                 responseFormat = assetTypeData.right().value();
184                 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
185                 return buildErrorResponse(responseFormat);
186             } else {
187                 log.debug("getAssetList: Asset Fetching Success");
188                 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
189                     .convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
190                 if (resMetadata.isRight()) {
191                     log.debug("getAssetList: Asset conversion Failed");
192                     responseFormat = resMetadata.right().value();
193                     getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
194                     return buildErrorResponse(responseFormat);
195                 }
196                 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
197                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
198                 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
199                 return buildOkResponse(responseFormat, result);
200             }
201         } catch (Exception e) {
202             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
203             log.debug("getAssetList: Fetch list of assets failed with exception", e);
204             throw e;
205         }
206     }
207
208     /**
209      * @param requestId
210      * @param instanceIdHeader
211      * @param accept
212      * @param authorization
213      * @param assetType
214      * @param uuid
215      * @return
216      */
217     @GET
218     @Path("/{assetType}/{uuid}/metadata")
219     @Produces(MediaType.APPLICATION_JSON)
220     @Operation(description = "Detailed metadata of asset by uuid", method = "GET", summary = "Returns detailed metadata of an asset by uuid", responses = {
221         @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)))),
222         @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
223         @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
224         @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
225         @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
226         @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
227         @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")})
228     @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
229     public Response getAssetSpecificMetadataByUuidExternal(
230         @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
231         @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
232         @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
233         @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
234         @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
235             "services"}), required = true) @PathParam("assetType") final String assetType,
236         @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) throws IOException {
237         ResponseFormat responseFormat = null;
238         AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
239         String requestURI = request.getRequestURI();
240         String url = request.getMethod() + " " + requestURI;
241         log.debug("Start handle request of {}", url);
242         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
243         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
244         DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
245         // Mandatory
246         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
247             log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
248             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
249             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
250             return buildErrorResponse(responseFormat);
251         }
252         try {
253             Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic
254                 .getCatalogComponentsByUuidAndAssetType(assetType, uuid);
255             if (assetTypeData.isRight()) {
256                 log.debug("getAssetList: Asset Fetching Failed");
257                 responseFormat = assetTypeData.right().value();
258                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
259                 return buildErrorResponse(responseFormat);
260             }
261             resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
262             log.debug("getAssetList: Asset Fetching Success");
263             Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
264                 .convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
265             if (resMetadata.isRight()) {
266                 log.debug("getAssetList: Asset conversion Failed");
267                 responseFormat = resMetadata.right().value();
268                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
269                 return buildErrorResponse(responseFormat);
270             }
271             Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
272             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
273             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
274             return buildOkResponse(responseFormat, result);
275         } catch (Exception e) {
276             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
277             log.debug("getAssetList: Fetch list of assets failed with exception", e);
278             throw e;
279         }
280     }
281
282     private ComponentBusinessLogic getComponentBLByType(ComponentTypeEnum componentTypeEnum) {
283         if (componentTypeEnum.equals(RESOURCE)) {
284             return resourceBusinessLogic;
285         } else {
286             // Implementation is the same for any ComponentBusinessLogic
287             return serviceBusinessLogic;
288         }
289     }
290
291     /**
292      * @param requestId
293      * @param instanceIdHeader
294      * @param accept
295      * @param authorization
296      * @param assetType
297      * @param uuid
298      * @return
299      */
300     @GET
301     @Path("/{assetType}/{uuid}/toscaModel")
302     @Produces(MediaType.APPLICATION_OCTET_STREAM)
303     @Operation(description = "Fetch assets CSAR", method = "GET", summary = "Returns asset csar", responses = {
304         @ApiResponse(description = "default response", content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
305         @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)))),
306         @ApiResponse(responseCode = "400", description = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
307         @ApiResponse(responseCode = "401", description = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
308         @ApiResponse(responseCode = "403", description = "ECOMP component is not authorized - POL5003"),
309         @ApiResponse(responseCode = "404", description = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
310         @ApiResponse(responseCode = "405", description = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
311         @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")})
312     @PermissionAllowed(AafPermission.PermNames.READ_VALUE)
313     public Response getToscaModelExternal(
314         @Parameter(description = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
315         @Parameter(description = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
316         @Parameter(description = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
317         @Parameter(description = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
318         @Parameter(description = "The requested asset type", schema = @Schema(allowableValues = {"resources",
319             "services"}), required = true) @PathParam("assetType") final String assetType,
320         @Parameter(description = "The requested asset uuid", required = true) @PathParam("uuid") final String uuid) {
321         String url = request.getRequestURI();
322         log.debug("Start handle request of {} {}", request.getMethod(), url);
323         ResponseFormat responseFormat = null;
324         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
325         AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
326         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
327         DistributionData distributionData = new DistributionData(instanceIdHeader, url);
328         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
329             log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
330             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
331             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
332             return buildErrorResponse(responseFormat);
333         }
334         try {
335             ComponentBusinessLogic componentBusinessLogic = getComponentBLByType(componentType);
336             ImmutablePair<String, byte[]> csarArtifact = componentBusinessLogic.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);
337             byte[] value = csarArtifact.getRight();
338             InputStream is = new ByteArrayInputStream(value);
339             String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
340             Map<String, String> headers = new HashMap<>();
341             headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.getLeft()));
342             headers.put(Constants.MD5_HEADER, contenetMD5);
343             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
344             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
345             return buildOkResponse(responseFormat, is, headers);
346         } catch (ComponentException e) {
347             responseFormat = e.getResponseFormat();
348             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
349             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
350             log.debug("failed to get asset tosca model", e);
351             Response response = buildErrorResponse(responseFormat);
352             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData, resourceCommonInfo, requestId, uuid);
353             return response;
354         }
355     }
356
357     private String removeDuplicateSlashSeparator(String requestUri) {
358         return requestUri.substring(0, requestUri.length() - 1);
359     }
360 }