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