update code
[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().endsWith("/")?
130                                 removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
131                 String url = request.getMethod() + " " + requestURI;
132                 log.debug("Start handle request of {}", url);
133
134                 AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
135
136                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
137                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
138                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, query == null ? requestURI : requestURI + "?" + query);
139
140                 // Mandatory
141                 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
142                         log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
143                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
144                         getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
145                         return buildErrorResponse(responseFormat);
146                 }
147
148                 try {
149                         ServletContext context = request.getSession().getServletContext();
150                         ElementBusinessLogic elementLogic = getElementBL(context);
151
152                         AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
153                         Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
154
155                         if (category != null) {
156                                 filters.put(FilterKeyEnum.CATEGORY, category);
157                         }
158                         if (subCategory != null) {
159                                 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
160                         }
161                         if (distributionStatus != null) {
162                                 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
163                         }
164                         if (resourceType != null) {
165                                 ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
166                                 if (resourceTypeEnum == null) {
167                                         log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
168                                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
169                                         getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
170                                         return buildErrorResponse(responseFormat);
171                                 }
172                                 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
173                         }
174
175                         Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query);
176
177                         if (assetTypeData.isRight()) {
178                                 log.debug("getAssetList: Asset Fetching Failed");
179                                 responseFormat = assetTypeData.right().value();
180                                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
181                                 return buildErrorResponse(responseFormat);
182                         } else {
183                                 log.debug("getAssetList: Asset Fetching Success");
184                                 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
185                                 if (resMetadata.isRight()) {
186                                         log.debug("getAssetList: Asset conversion Failed");
187                                         responseFormat = resMetadata.right().value();
188                                         getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
189                                         return buildErrorResponse(responseFormat);
190                                 }
191                                 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
192                                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
193                                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
194
195                                 response = buildOkResponse(responseFormat, result);
196                                 return response;
197                         }
198                 } catch (Exception e) {
199                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
200                         log.debug("getAssetList: Fetch list of assets failed with exception", e);
201                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
202                 }
203         }
204         
205         /**
206          * 
207          * @param requestId
208          * @param instanceIdHeader
209          * @param accept
210          * @param authorization
211          * @param assetType
212          * @param uuid
213          * @return
214          */
215         @GET
216         @Path("/{assetType}/{uuid}/metadata")
217         @Produces(MediaType.APPLICATION_JSON)
218         @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid")
219         @ApiResponses(value = {
220                         @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
221                         @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
222                         @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
223                         @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
224                         @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
225                         @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
226                         @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")})
227         public Response getAssetSpecificMetadataByUuidExternal(
228                         @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
229                         @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
230                         @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
231                         @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
232                         @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, 
233                         @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
234
235                 Response response = null;
236                 ResponseFormat responseFormat = null;
237                 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
238                 String requestURI = request.getRequestURI();
239                 String url = request.getMethod() + " " + requestURI;
240                 log.debug("Start handle request of {}", url);
241
242                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<>(AuditingFieldsKeysEnum.class);
243                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
244                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
245                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
246                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue());
247                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid);
248
249                 // Mandatory
250                 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
251                         log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
252                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
253                         getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
254                         return buildErrorResponse(responseFormat);
255                 }
256
257                 try {
258                         ServletContext context = request.getSession().getServletContext();
259                         ElementBusinessLogic elementLogic = getElementBL(context);
260                         AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
261
262                         Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
263
264                         if (assetTypeData.isRight()) {
265                                 log.debug("getAssetList: Asset Fetching Failed");
266                                 responseFormat = assetTypeData.right().value();
267                                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
268
269                                 return buildErrorResponse(responseFormat);
270                         } else {
271                                 log.debug("getAssetList: Asset Fetching Success");
272                                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName());
273                                 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
274                                 if (resMetadata.isRight()) {
275                                         log.debug("getAssetList: Asset conversion Failed");
276                                         responseFormat = resMetadata.right().value();
277                                         getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
278                                         return buildErrorResponse(responseFormat);
279                                 }
280                                 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
281                                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
282                                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
283
284                                 response = buildOkResponse(responseFormat, result);
285                                 return response;
286                         }
287                 } catch (Exception e) {
288                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
289                         log.debug("getAssetList: Fetch list of assets failed with exception", e);
290                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
291                 }
292         }
293         
294         /**
295          * 
296          * @param requestId
297          * @param instanceIdHeader
298          * @param accept
299          * @param authorization
300          * @param assetType
301          * @param uuid
302          * @return
303          */
304         @GET
305         @Path("/{assetType}/{uuid}/toscaModel")
306         @Produces(MediaType.APPLICATION_OCTET_STREAM)
307         @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class)
308         @ApiResponses(value = {
309                         @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class),
310                         @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
311                         @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic Authentication credentials - POL5002"),
312                         @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
313                         @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
314                         @ApiResponse(code = 405, message = "Method  Not Allowed  :  Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
315                         @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")})
316         public Response getToscaModelExternal(
317                         @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
318                         @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
319                         @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
320                         @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
321                         @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType, 
322                         @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
323
324                 String url = request.getRequestURI();
325                 log.debug("Start handle request of {} {}", request.getMethod(), url);
326                 Response response = null;
327                 ResponseFormat responseFormat = null;
328                 ServletContext context = request.getSession().getServletContext();
329                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
330                 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
331                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
332                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
333                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url);
334                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue());
335                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid);
336
337                 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
338                         log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
339                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
340                         getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
341                         return buildErrorResponse(responseFormat);
342                 }
343
344                 try {
345                         ComponentBusinessLogic componentBL = getComponentBL(componentType, context);
346
347                         Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, additionalParam);
348                         if (csarArtifact.isRight()) {
349                                 responseFormat = csarArtifact.right().value();
350                                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
351                                 response = buildErrorResponse(responseFormat);
352                         } else {
353                                 byte[] value = csarArtifact.left().value().getRight();
354                                 InputStream is = new ByteArrayInputStream(value);
355                                 String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
356                                 Map<String, String> headers = new HashMap<>();
357                                 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft()));
358                                 headers.put(Constants.MD5_HEADER, contenetMD5);
359                                 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
360                                 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
361                                 response = buildOkResponse(responseFormat, is, headers);
362                         }
363                         return response;
364
365                 } catch (Exception e) {
366                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
367                         log.debug("falied to get asset tosca model", e);
368                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
369                         response = buildErrorResponse(responseFormat);
370                         getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
371                         return response;
372                 }
373         }
374
375
376         private String removeDuplicateSlashSeparator(String requestUri) {
377                 return requestUri.substring(0, requestUri.length()-1);
378         }
379
380
381 }