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.resources.data.auditing.model.DistributionData;
39 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
40 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
41 import org.openecomp.sdc.be.servlets.RepresentationUtils;
42 import org.openecomp.sdc.common.api.Constants;
43 import org.openecomp.sdc.common.log.wrappers.Logger;
44 import org.openecomp.sdc.common.util.GeneralUtility;
45 import org.openecomp.sdc.exception.ResponseFormat;
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 = Logger.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 String resourceUrl = query == null ? requestURI : requestURI + "?" + query;
125 DistributionData distributionData = new DistributionData(instanceIdHeader, resourceUrl);
128 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
129 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
130 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
131 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
132 return buildErrorResponse(responseFormat);
136 ServletContext context = request.getSession().getServletContext();
137 ElementBusinessLogic elementLogic = getElementBL(context);
139 AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
140 Map<FilterKeyEnum, String> filters = new EnumMap<>(FilterKeyEnum.class);
142 if (category != null) {
143 filters.put(FilterKeyEnum.CATEGORY, category);
145 if (subCategory != null) {
146 filters.put(FilterKeyEnum.SUB_CATEGORY, subCategory);
148 if (distributionStatus != null) {
149 filters.put(FilterKeyEnum.DISTRIBUTION_STATUS, distributionStatus);
151 if (resourceType != null) {
152 ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
153 if (resourceTypeEnum == null) {
154 log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
155 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
156 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
157 return buildErrorResponse(responseFormat);
159 filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeEnum.name());
162 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getFilteredCatalogComponents(assetType, filters, query);
164 if (assetTypeData.isRight()) {
165 log.debug("getAssetList: Asset Fetching Failed");
166 responseFormat = assetTypeData.right().value();
167 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
168 return buildErrorResponse(responseFormat);
170 log.debug("getAssetList: Asset Fetching Success");
171 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, false);
172 if (resMetadata.isRight()) {
173 log.debug("getAssetList: Asset conversion Failed");
174 responseFormat = resMetadata.right().value();
175 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
176 return buildErrorResponse(responseFormat);
178 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value());
179 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
180 getComponentsUtils().auditExternalGetAssetList(responseFormat, auditingActionEnum, distributionData, requestId);
182 response = buildOkResponse(responseFormat, result);
185 } catch (Exception e) {
186 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Fetch filtered list of assets");
187 log.debug("getAssetList: Fetch list of assets failed with exception", e);
188 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
195 * @param instanceIdHeader
197 * @param authorization
203 @Path("/{assetType}/{uuid}/metadata")
204 @Produces(MediaType.APPLICATION_JSON)
205 @ApiOperation(value = "Detailed metadata of asset by uuid", httpMethod = "GET", notes = "Returns detailed metadata of an asset by uuid")
206 @ApiResponses(value = {
207 @ApiResponse(code = 200, message = "ECOMP component is authenticated and list of Catalog Assets Metadata is returned", response = AssetMetadata.class, responseContainer="List"),
208 @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
209 @ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
210 @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
211 @ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
212 @ApiResponse(code = 405, message = "Method Not Allowed : Invalid HTTP method type used ( PUT,DELETE,POST will be rejected) - POL4050"),
213 @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")})
214 public Response getAssetSpecificMetadataByUuidExternal(
215 @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
216 @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
217 @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
218 @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
219 @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
220 @ApiParam(value = "The requested asset uuid", required = true)@PathParam("uuid") final String uuid) {
222 Response response = null;
223 ResponseFormat responseFormat = null;
224 AuditingActionEnum auditingActionEnum = AuditingActionEnum.GET_ASSET_METADATA;
225 String requestURI = request.getRequestURI();
226 String url = request.getMethod() + " " + requestURI;
227 log.debug("Start handle request of {}", url);
229 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
230 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
231 DistributionData distributionData = new DistributionData(instanceIdHeader, requestURI);
233 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
234 log.debug("getAssetList: Missing X-ECOMP-InstanceID header");
235 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
236 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
237 resourceCommonInfo, requestId, uuid);
238 return buildErrorResponse(responseFormat);
242 ServletContext context = request.getSession().getServletContext();
243 ElementBusinessLogic elementLogic = getElementBL(context);
244 AssetMetadataConverter assetMetadataUtils = getAssetUtils(context);
246 Either<List<? extends Component>, ResponseFormat> assetTypeData = elementLogic.getCatalogComponentsByUuidAndAssetType(assetType, uuid);
248 if (assetTypeData.isRight()) {
249 log.debug("getAssetList: Asset Fetching Failed");
250 responseFormat = assetTypeData.right().value();
251 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
252 resourceCommonInfo, requestId, uuid);
254 return buildErrorResponse(responseFormat);
256 resourceCommonInfo.setResourceName(assetTypeData.left().value().iterator().next().getName());
257 log.debug("getAssetList: Asset Fetching Success");
258 Either<List<? extends AssetMetadata>, ResponseFormat> resMetadata = assetMetadataUtils.convertToAssetMetadata(assetTypeData.left().value(), requestURI, true);
259 if (resMetadata.isRight()) {
260 log.debug("getAssetList: Asset conversion Failed");
261 responseFormat = resMetadata.right().value();
263 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
264 resourceCommonInfo, requestId, uuid);
265 return buildErrorResponse(responseFormat);
267 Object result = RepresentationUtils.toRepresentation(resMetadata.left().value().iterator().next());
268 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
269 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
270 resourceCommonInfo, requestId, uuid);
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;
320 ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentType.getValue());
321 DistributionData distributionData = new DistributionData(instanceIdHeader, url);
323 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
324 log.debug("getToscaModel: Missing X-ECOMP-InstanceID header");
325 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
326 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
327 resourceCommonInfo, requestId, uuid);
328 return buildErrorResponse(responseFormat);
332 ComponentBusinessLogic componentBL = getComponentBL(componentType, context);
335 Either<ImmutablePair<String, byte[]>, ResponseFormat> csarArtifact = componentBL.getToscaModelByComponentUuid(componentType, uuid, resourceCommonInfo);
336 if (csarArtifact.isRight()) {
337 responseFormat = csarArtifact.right().value();
338 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
339 resourceCommonInfo, requestId, uuid);
340 response = buildErrorResponse(responseFormat);
342 byte[] value = csarArtifact.left().value().getRight();
343 InputStream is = new ByteArrayInputStream(value);
344 String contenetMD5 = GeneralUtility.calculateMD5Base64EncodedByByteArray(value);
345 Map<String, String> headers = new HashMap<>();
346 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(csarArtifact.left().value().getLeft()));
347 headers.put(Constants.MD5_HEADER, contenetMD5);
348 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
349 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
350 resourceCommonInfo, requestId, uuid);
351 response = buildOkResponse(responseFormat, is, headers);
355 } catch (Exception e) {
356 BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get asset tosca model");
357 log.debug("falied to get asset tosca model", e);
358 responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
359 response = buildErrorResponse(responseFormat);
360 getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, distributionData,
361 resourceCommonInfo, requestId, uuid);
367 private String removeDuplicateSlashSeparator(String requestUri) {
368 return requestUri.substring(0, requestUri.length()-1);