catalog-be servlets refactoring
[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
21 package org.openecomp.sdc.be.externalapi.servlet;
22
23 import com.jcabi.aspects.Loggable;
24 import fj.data.Either;
25 import io.swagger.annotations.Api;
26 import io.swagger.annotations.ApiOperation;
27 import io.swagger.annotations.ApiParam;
28 import io.swagger.annotations.ApiResponse;
29 import io.swagger.annotations.ApiResponses;
30 import javax.inject.Inject;
31 import javax.ws.rs.GET;
32 import javax.ws.rs.HeaderParam;
33 import javax.ws.rs.Path;
34 import javax.ws.rs.PathParam;
35 import javax.ws.rs.Produces;
36 import javax.ws.rs.QueryParam;
37 import org.apache.commons.lang3.tuple.ImmutablePair;
38 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
39 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogicProvider;
40 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
41 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
42 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager;
44 import org.openecomp.sdc.be.dao.api.ActionStatus;
45 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
46 import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
47 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
48 import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter;
49 import org.openecomp.sdc.be.externalapi.servlet.representation.AssetMetadata;
50 import org.openecomp.sdc.be.impl.ComponentsUtils;
51 import org.openecomp.sdc.be.impl.ServletUtils;
52 import org.openecomp.sdc.be.model.Component;
53 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
54 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
55 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
56 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
57 import org.openecomp.sdc.be.servlets.RepresentationUtils;
58 import org.openecomp.sdc.be.user.UserBusinessLogic;
59 import org.openecomp.sdc.common.api.Constants;
60 import org.openecomp.sdc.common.log.wrappers.Logger;
61 import org.openecomp.sdc.common.util.GeneralUtility;
62 import org.openecomp.sdc.exception.ResponseFormat;
63
64 import javax.inject.Singleton;
65 import javax.servlet.http.HttpServletRequest;
66 import javax.ws.rs.core.Context;
67 import javax.ws.rs.core.MediaType;
68 import javax.ws.rs.core.Response;
69 import java.io.ByteArrayInputStream;
70 import java.io.InputStream;
71 import java.util.EnumMap;
72 import java.util.HashMap;
73 import java.util.List;
74 import java.util.Map;
75
76 /**
77  * This Servlet serves external users for retrieving component metadata.
78  * 
79  * @author tgitelman
80  *
81  */
82
83 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
84 @Path("/v1/catalog")
85 @Api(value = "Asset Metadata External Servlet", description = "This Servlet serves external users for retrieving component metadata.")
86 @Singleton
87 public class AssetsDataServlet extends AbstractValidationsServlet {
88
89     @Context
90     private HttpServletRequest request;
91
92     private static final Logger log = Logger.getLogger(AssetsDataServlet.class);
93     private final ElementBusinessLogic elementBusinessLogic;
94     private final AssetMetadataConverter assetMetadataConverter;
95     private final ComponentBusinessLogicProvider componentBusinessLogicProvider;
96
97     @Inject
98     public AssetsDataServlet(UserBusinessLogic userBusinessLogic,
99         ComponentInstanceBusinessLogic componentInstanceBL,
100         ComponentsUtils componentsUtils, ServletUtils servletUtils,
101         ResourceImportManager resourceImportManager,
102         ElementBusinessLogic elementBusinessLogic,
103         AssetMetadataConverter assetMetadataConverter,
104         ComponentBusinessLogicProvider componentBusinessLogicProvider) {
105         super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager);
106         this.elementBusinessLogic = elementBusinessLogic;
107         this.assetMetadataConverter = assetMetadataConverter;
108         this.componentBusinessLogicProvider = componentBusinessLogicProvider;
109     }
110
111     /**
112      *
113      * @param requestId
114      * @param instanceIdHeader
115      * @param accept
116      * @param authorization
117      * @param assetType
118      * @param category
119      * @param subCategory
120      * @param distributionStatus
121      * @param resourceType
122      * @return
123      */
124     @GET
125     @Path("/{assetType}")
126     @Produces(MediaType.APPLICATION_JSON)
127     @ApiOperation(value = "Fetch list of assets", httpMethod = "GET", notes = "Returns list of assets")
128     @ApiResponses(value = {
129             @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
130             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
131             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
132             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
133             @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
134             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
135     public Response getAssetListExternal(
136             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
137             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
138             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
139             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
140             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
141             @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("category") String category,
142             @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("subCategory") String subCategory,
143             @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("distributionStatus") String distributionStatus,
144             @ApiParam(value = "The filter key (resourceType only for resources)", required = false)@QueryParam("resourceType") String resourceType) {
145
146         Response response = null;
147         ResponseFormat responseFormat = null;
148         String query = request.getQueryString();
149         String requestURI = request.getRequestURI().endsWith("/")?
150                 removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
151         String url = request.getMethod() + " " + requestURI;
152         log.debug("Start handle request of {}", url);
153
154         AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
155
156         String resourceUrl = query == null ? requestURI : requestURI + "?" + query;
157         DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);
158
159         // Mandatory
160         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
161             log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
162             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
163             getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
164             return buildErrorResponse(responseFormat);
165         }
166
167         try {
168             Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
169
170             if (category != null) {
171                 filters.put(FilterKeyEnum.CATEGORY, category);
172             }
173             if (subCategory != null) {
174                 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
175             }
176             if (distributionStatus != null) {
177                 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
178             }
179             if (resourceType != null) {
180                 ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
181                 if (resourceTypeEnum == null) {
182                     log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
183                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
184                     getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
185                     return buildErrorResponse(responseFormat);
186                 }
187                 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
188             }
189
190             Either<List<? extends Component>, ResponseFormat> assetTypeData = elementBusinessLogic.getFilteredCatalogComponents(assetType, filters, query);
191
192             if (assetTypeData.isRight()) {
193                 log.debug("getAssetList: Asset Fetching Failed");
194                 responseFormat = assetTypeData.right().value();
195                 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
196                 return buildErrorResponse(responseFormat);
197             } else {
198                 log.debug("getAssetList: Asset Fetching Success");
199                 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
200                     .convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
201                 if (resMetadata.isRight()) {
202                     log.debug("getAssetList: Asset conversion Failed");
203                     responseFormat = resMetadata.right().value();
204                     getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
205                     return buildErrorResponse(responseFormat);
206                 }
207                 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
208                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
209                 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
210
211                 response = buildOkResponse(responseFormat, result);
212                 return response;
213             }
214         } catch (Exception e) {
215             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
216             log.debug("getAssetList: Fetch list of assets failed with exception", e);
217             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
218         }
219     }
220
221     /**
222      *
223      * @param requestId
224      * @param instanceIdHeader
225      * @param accept
226      * @param authorization
227      * @param assetType
228      * @param uuid
229      * @return
230      */
231     @GET
232     @Path("/{assetType}/{uuid}/metadata")
233     @Produces(MediaType.APPLICATION_JSON)
234     @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid")
235     @ApiResponses(value = {
236             @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
237             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
238             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
239             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
240             @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
241             @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
242             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
243     public Response getAssetSpecificMetadataByUuidExternal(
244             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
245             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
246             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
247             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
248             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
249             @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
250
251         Response response = null;
252         ResponseFormat responseFormat = null;
253         AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
254         String requestURI = request.getRequestURI();
255         String url = request.getMethod() + " " + requestURI;
256         log.debug("Start handle request of {}", url);
257
258         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
259         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
260         DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
261         // Mandatory
262         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
263             log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
264             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
265             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
266                     resourceCommonInfo, requestId, uuid);
267             return buildErrorResponse(responseFormat);
268         }
269
270         try {
271             Either<List<? extends Component>, ResponseFormat> assetTypeData =
272                 elementBusinessLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
273
274             if (assetTypeData.isRight()) {
275                 log.debug("getAssetList: Asset Fetching Failed");
276                 responseFormat = assetTypeData.right().value();
277                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
278                         resourceCommonInfo, requestId, uuid);
279
280                 return buildErrorResponse(responseFormat);
281             }
282             resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
283             log.debug("getAssetList: Asset Fetching Success");
284             Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataConverter
285                 .convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
286             if (resMetadata.isRight()) {
287                 log.debug("getAssetList: Asset conversion Failed");
288                 responseFormat = resMetadata.right().value();
289
290                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
291                         resourceCommonInfo, requestId, uuid);
292                 return buildErrorResponse(responseFormat);
293             }
294             Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
295             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
296             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
297                     resourceCommonInfo, requestId, uuid);
298
299             response = buildOkResponse(responseFormat, result);
300             return response;
301
302         } catch (Exception e) {
303             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
304             log.debug("getAssetList: Fetch list of assets failed with exception", e);
305             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
306         }
307     }
308
309     /**
310      *
311      * @param requestId
312      * @param instanceIdHeader
313      * @param accept
314      * @param authorization
315      * @param assetType
316      * @param uuid
317      * @return
318      */
319     @GET
320     @Path("/{assetType}/{uuid}/toscaModel")
321     @Produces(MediaType.APPLICATION_OCTET_STREAM)
322     @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class)
323     @ApiResponses(value = {
324             @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class),
325             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
326             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
327             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
328             @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
329             @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
330             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem. ECOMP Component should continue the attempts to get the needed information - POL5000")})
331     public Response getToscaModelExternal(
332             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
333             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
334             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
335             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
336             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
337             @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
338
339         String url = request.getRequestURI();
340         log.debug("Start handle request of {} {}", request.getMethod(), url);
341         Response response = null;
342         ResponseFormat responseFormat = null;
343         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
344         AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
345
346         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
347         DistributionData distributionData = new DistributionData(instanceIdHeader, url);
348
349         if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
350             log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
351             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
352             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
353                     resourceCommonInfo, requestId, uuid);
354             return buildErrorResponse(responseFormat);
355         }
356
357         try {
358             ComponentBusinessLogic componentBL = componentBusinessLogicProvider.getInstance(componentType);
359
360
361             Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);
362             if (csarArtifact.isRight()) {
363                 responseFormat = csarArtifact.right().value();
364                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
365                         resourceCommonInfo, requestId, uuid);
366                 response = buildErrorResponse(responseFormat);
367             } else {
368                 byte[] value = csarArtifact.left().value().getRight();
369                 InputStream is = new ByteArrayInputStream(value);
370                 String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
371                 Map<String, String> headers = new HashMap<>();
372                 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft()));
373                 headers.put(Constants.MD5_HEADER, contenetMD5);
374                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
375                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
376                         resourceCommonInfo, requestId, uuid);
377                 response = buildOkResponse(responseFormat, is, headers);
378             }
379             return response;
380
381         } catch (Exception e) {
382             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
383             log.debug("falied to get asset tosca model", e);
384             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
385             response = buildErrorResponse(responseFormat);
386             getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
387                     resourceCommonInfo, requestId, uuid);
388             return response;
389         }
390     }
391
392
393     private String removeDuplicateSlashSeparator(String requestUri) {
394         return requestUri.substring(0, requestUri.length()-1);
395     }
396
397
398 }