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