2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.externalapi.servlet;
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;
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;
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;
64 import com.jcabi.aspects.Loggable;
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;
74 * This Servlet serves external users for retrieving component metadata.
80 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
82 @Api(value = "Asset Metadata External Servlet", description = "This Servlet serves external users for retrieving component metadata.")
84 public class AssetsDataServlet extends AbstractValidationsServlet {
87 private HttpServletRequest request;
89 private static Logger log = LoggerFactory.getLogger(AssetsDataServlet.class.getName());
94 * @param instanceIdHeader
96 * @param authorization
100 * @param distributionStatus
101 * @param resourceType
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) {
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);
134 AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
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);
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);
149 ServletContext context = request.getSession().getServletContext();
150 ElementBusinessLogic elementLogic = getElementBL(context);
152 AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
153 Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
155 if (category != null) {
156 filters.put(FilterKeyEnum.CATEGORY, category);
158 if (subCategory != null) {
159 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
161 if (distributionStatus != null) {
162 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
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);
172 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
175 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query);
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);
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);
191 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
192 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
193 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
195 response = buildOkResponse(responseFormat, result);
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));
208 * @param instanceIdHeader
210 * @param authorization
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) {
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);
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_SERVICE_INSTANCE_ID, uuid);
247 if (componentType == null) {
248 log.debug("getMetaData: assetType parameter {} is not valid", assetType);
249 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
250 return buildErrorResponse(responseFormat);
252 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue());
255 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
256 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
257 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
258 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
259 return buildErrorResponse(responseFormat);
263 ServletContext context = request.getSession().getServletContext();
264 ElementBusinessLogic elementLogic = getElementBL(context);
265 AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
267 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
269 if (assetTypeData.isRight()) {
270 log.debug("getAssetList: Asset Fetching Failed");
271 responseFormat = assetTypeData.right().value();
272 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
274 return buildErrorResponse(responseFormat);
276 log.debug("getAssetList: Asset Fetching Success");
277 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, assetTypeData.left().value().iterator().next().getName());
278 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
279 if (resMetadata.isRight()) {
280 log.debug("getAssetList: Asset conversion Failed");
281 responseFormat = resMetadata.right().value();
282 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
283 return buildErrorResponse(responseFormat);
285 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
286 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
287 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
289 response = buildOkResponse(responseFormat, result);
292 } catch (Exception e) {
293 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
294 log.debug("getAssetList: Fetch list of assets failed with exception", e);
295 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
302 * @param instanceIdHeader
304 * @param authorization
310 @Path("/{assetType}/{uuid}/toscaModel")
311 @Produces(MediaType.APPLICATION_OCTET_STREAM)
312 @ApiOperation(value = "Fetch assets CSAR", httpMethod = "GET", notes = "Returns asset csar", response = String.class)
313 @ApiResponses(value = {
314 @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = String.class),
315 @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
316 @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
317 @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
318 @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
319 @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
320 @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")})
321 public Response getToscaModelExternal(
322 @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
323 @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
324 @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
325 @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
326 @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
327 @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
329 String url = request.getRequestURI();
330 log.debug("Start handle request of {} {}", request.getMethod(), url);
331 Response response = null;
332 ResponseFormat responseFormat = null;
333 ServletContext context = request.getSession().getServletContext();
334 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
335 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_TOSCA_MODEL;
336 EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
337 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
338 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, url);
339 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID, uuid);
341 if (componentType == null) {
342 log.debug("getToscaModel: assetType parameter {} is not valid", assetType);
343 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
344 return buildErrorResponse(responseFormat);
346 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_TYPE, componentType.getValue());
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, additionalParam);
353 return buildErrorResponse(responseFormat);
357 ComponentBusinessLogic componentBL = getComponentBL(componentType, context);
359 Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, additionalParam);
360 if (csarArtifact.isRight()) {
361 responseFormat = csarArtifact.right().value();
362 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
363 response = buildErrorResponse(responseFormat);
365 byte[] value = csarArtifact.left().value().getRight();
366 InputStream is = new ByteArrayInputStream(value);
367 String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
368 Map<String, String> headers = new HashMap<>();
369 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft()));
370 headers.put(Constants.MD5_HEADER, contenetMD5);
371 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
372 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
373 response = buildOkResponse(responseFormat, is, headers);
377 } catch (Exception e) {
378 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
379 log.debug("falied to get asset tosca model", e);
380 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
381 response = buildErrorResponse(responseFormat);
382 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
388 private String removeDuplicateSlashSeparator(String requestUri) {
389 return requestUri.substring(0, requestUri.length()-1);