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 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;
47 import javax.inject.Singleton;
48 import javax.servlet.ServletContext;
49 import javax.servlet.http.HttpServletRequest;
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;
62 * This Servlet serves external users for retrieving component metadata.
68 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
70 @Api(value = "Asset Metadata External Servlet", description = "This Servlet serves external users for retrieving component metadata.")
72 public class AssetsDataServlet extends AbstractValidationsServlet {
75 private HttpServletRequest request;
77 private static final Logger log = LoggerFactory.getLogger(AssetsDataServlet.class);
82 * @param instanceIdHeader
84 * @param authorization
88 * @param distributionStatus
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) {
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);
122 AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
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);
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);
137 ServletContext context = request.getSession().getServletContext();
138 ElementBusinessLogic elementLogic = getElementBL(context);
140 AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
141 Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
143 if (category != null) {
144 filters.put(FilterKeyEnum.CATEGORY, category);
146 if (subCategory != null) {
147 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
149 if (distributionStatus != null) {
150 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
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);
160 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
163 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query);
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);
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);
179 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
180 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
181 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
183 response = buildOkResponse(responseFormat, result);
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));
196 * @param instanceIdHeader
198 * @param authorization
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) {
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);
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);
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);
246 ServletContext context = request.getSession().getServletContext();
247 ElementBusinessLogic elementLogic = getElementBL(context);
248 AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
250 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
252 if (assetTypeData.isRight()) {
253 log.debug("getAssetList: Asset Fetching Failed");
254 responseFormat = assetTypeData.right().value();
255 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
257 return buildErrorResponse(responseFormat);
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);
268 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
269 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
270 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
272 response = buildOkResponse(responseFormat, result);
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));
285 * @param instanceIdHeader
287 * @param authorization
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) {
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);
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);
333 ComponentBusinessLogic componentBL = getComponentBL(componentType, context);
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);
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);
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);
364 private String removeDuplicateSlashSeparator(String requestUri) {
365 return requestUri.substring(0, requestUri.length()-1);