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