Initial OpenECOMP SDC commit
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / distribution / servlet / DistributionCatalogServlet.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.distribution.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.Map;
28
29 import javax.inject.Singleton;
30 import javax.servlet.ServletContext;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.ws.rs.Consumes;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.PathParam;
36 import javax.ws.rs.Produces;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.Response;
40
41 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
42 import org.openecomp.sdc.be.config.BeEcompErrorManager;
43 import org.openecomp.sdc.be.dao.api.ActionStatus;
44 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
45 import org.openecomp.sdc.be.servlets.BeGenericServlet;
46 import org.openecomp.sdc.common.api.Constants;
47 import org.openecomp.sdc.common.config.EcompErrorName;
48 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
49 import org.openecomp.sdc.exception.ResponseFormat;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 import com.jcabi.aspects.Loggable;
54 import com.wordnik.swagger.annotations.ApiOperation;
55 import com.wordnik.swagger.annotations.ApiResponse;
56 import com.wordnik.swagger.annotations.ApiResponses;
57
58 import fj.data.Either;
59
60 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
61 @Path("/v1/catalog")
62 @Singleton
63 public class DistributionCatalogServlet extends BeGenericServlet {
64
65         private static Logger log = LoggerFactory.getLogger(DistributionCatalogServlet.class.getName());
66
67         // *******************************************************
68         // Download (GET) artifacts
69         // **********************************************************/
70
71         @GET
72         @Path("/services/{serviceName}/{serviceVersion}/artifacts/{artifactName}")
73         @Consumes(MediaType.APPLICATION_JSON)
74         @Produces(MediaType.APPLICATION_OCTET_STREAM)
75         @ApiOperation(value = "Download service artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
76         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact downloaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
77                         @ApiResponse(code = 404, message = "Artifact not found") })
78         public Response downloadServiceArtifact(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @PathParam("artifactName") final String artifactName,
79                         @Context final HttpServletRequest request) {
80                 Response response = null;
81                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
82                 String requestURI = request.getRequestURI();
83                 AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD;
84                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
85                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
86                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
87
88                 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
89                         log.debug("Missing X-ECOMP-InstanceID header");
90                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
91                         getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
92                         return buildErrorResponse(responseFormat);
93                 }
94
95                 try {
96                         ServletContext context = request.getSession().getServletContext();
97                         ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
98                         Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadServiceArtifactByNames(serviceName, serviceVersion, artifactName);
99                         if (downloadRsrcArtifactEither.isRight()) {
100                                 ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
101                                 getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
102                                 response = buildErrorResponse(responseFormat);
103                         } else {
104                                 byte[] value = downloadRsrcArtifactEither.left().value();
105                                 InputStream is = new ByteArrayInputStream(value);
106
107                                 Map<String, String> headers = new HashMap<>();
108                                 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
109                                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
110                                 getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
111                                 response = buildOkResponse(responseFormat, is, headers);
112                         }
113                         return response;
114
115                 } catch (Exception e) {
116                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download Murano package artifact for service - external API");
117                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download Murano package artifact for service - external API");
118                         log.debug("download artifact failed with exception", e);
119                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
120                 }
121         }
122
123         @GET
124         @Path("/services/{serviceName}/{serviceVersion}/resources/{resourceName}/{resourceVersion}/artifacts/{artifactName}")
125         @Consumes(MediaType.APPLICATION_JSON)
126         @Produces(MediaType.APPLICATION_OCTET_STREAM)
127         @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
128         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact downloaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
129                         @ApiResponse(code = 404, message = "Artifact not found") })
130         public Response downloadResourceArtifact(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @PathParam("resourceName") final String resourceName,
131                         @PathParam("resourceVersion") final String resourceVersion, @PathParam("artifactName") final String artifactName, @Context final HttpServletRequest request) {
132                 Response response = null;
133                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
134                 String requestURI = request.getRequestURI();
135                 AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD;
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, requestURI);
139
140                 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
141                         log.debug("Missing X-ECOMP-InstanceID header");
142                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
143                         getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
144                         return buildErrorResponse(responseFormat);
145                 }
146
147                 try {
148                         ServletContext context = request.getSession().getServletContext();
149                         ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
150                         Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcArtifactByNames(serviceName, serviceVersion, resourceName, resourceVersion, artifactName);
151                         if (downloadRsrcArtifactEither.isRight()) {
152                                 ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
153                                 getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
154                                 response = buildErrorResponse(responseFormat);
155                         } else {
156                                 byte[] value = downloadRsrcArtifactEither.left().value();
157                                 // Returning 64-encoded as it was received during upload
158                                 InputStream is = new ByteArrayInputStream(value);
159                                 Map<String, String> headers = new HashMap<>();
160                                 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
161                                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
162                                 getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
163                                 response = buildOkResponse(responseFormat, is, headers);
164                         }
165                         return response;
166
167                 } catch (Exception e) {
168                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API");
169                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
170                         log.debug("download artifact failed with exception", e);
171                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
172                 }
173         }
174
175         // --------------------------------
176
177         @GET
178         @Path("/services/{serviceName}/{serviceVersion}/resourceInstances/{resourceInstanceName}/artifacts/{artifactName}")
179         @Consumes(MediaType.APPLICATION_JSON)
180         @Produces(MediaType.APPLICATION_OCTET_STREAM)
181         @ApiOperation(value = "Download resource artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
182         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact downloaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
183                         @ApiResponse(code = 404, message = "Artifact not found") })
184         public Response downloadResourceInstanceArtifact(@PathParam("serviceName") final String serviceName, @PathParam("serviceVersion") final String serviceVersion, @PathParam("resourceInstanceName") final String resourceInstanceName,
185                         @PathParam("artifactName") final String artifactName, @Context final HttpServletRequest request) {
186                 Response response = null;
187                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
188                 String requestURI = request.getRequestURI();
189                 AuditingActionEnum auditingActionEnum = AuditingActionEnum.DISTRIBUTION_ARTIFACT_DOWNLOAD;
190                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
191                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_CONSUMER_ID, instanceIdHeader);
192                 additionalParam.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_RESOURCE_URL, requestURI);
193
194                 if (instanceIdHeader == null || instanceIdHeader.isEmpty()) {
195                         log.debug("Missing X-ECOMP-InstanceID header");
196                         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
197                         getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
198                         return buildErrorResponse(responseFormat);
199                 }
200
201                 try {
202                         ServletContext context = request.getSession().getServletContext();
203                         ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
204                         Either<byte[], ResponseFormat> downloadRsrcArtifactEither = artifactsLogic.downloadRsrcInstArtifactByNames(serviceName, serviceVersion, resourceInstanceName, artifactName);
205                         if (downloadRsrcArtifactEither.isRight()) {
206                                 ResponseFormat responseFormat = downloadRsrcArtifactEither.right().value();
207                                 getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
208                                 response = buildErrorResponse(responseFormat);
209                         } else {
210                                 byte[] value = downloadRsrcArtifactEither.left().value();
211                                 // Returning 64-encoded as it was received during upload
212                                 InputStream is = new ByteArrayInputStream(value);
213                                 Map<String, String> headers = new HashMap<>();
214                                 headers.put(Constants.CONTENT_DISPOSITION_HEADER, getContentDispositionValue(artifactName));
215                                 ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
216                                 getComponentsUtils().auditDistributionDownload(responseFormat, auditingActionEnum, additionalParam);
217                                 response = buildOkResponse(responseFormat, is, headers);
218                         }
219                         return response;
220
221                 } catch (Exception e) {
222                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeRestApiGeneralError, "download interface artifact for resource - external API");
223                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError("download interface artifact for resource - external API");
224                         log.debug("download artifact failed with exception", e);
225                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
226                 }
227         }
228
229         // --------------------------------
230 }