Merge "[1707-OS] Updated license text according to the"
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / externalapi / servlet / ArtifactExternalServlet.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.Map;
28
29 import javax.inject.Singleton;
30 import javax.servlet.ServletContext;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.ws.rs.DELETE;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.POST;
35 import javax.ws.rs.Path;
36 import javax.ws.rs.PathParam;
37 import javax.ws.rs.Produces;
38 import javax.ws.rs.core.Context;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.Response;
41
42 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
43 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
47 import org.openecomp.sdc.be.model.ArtifactDefinition;
48 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
49 import org.openecomp.sdc.be.servlets.RepresentationUtils;
50 import org.openecomp.sdc.common.api.Constants;
51 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
52 import org.openecomp.sdc.common.datastructure.Wrapper;
53 import org.openecomp.sdc.common.util.GeneralUtility;
54 import org.openecomp.sdc.exception.ResponseFormat;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 import com.jcabi.aspects.Loggable;
59 import io.swagger.annotations.Api;
60 import io.swagger.annotations.ApiOperation;
61 import io.swagger.annotations.ApiParam;
62 import io.swagger.annotations.ApiResponse;
63 import io.swagger.annotations.ApiResponses;
64
65 import fj.data.Either;
66
67 /**
68  * This Servlet serves external users operations on artifacts.
69  * 
70  * @author mshitrit
71  *
72  */
73 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
74 @Path("/v1/catalog")
75 @Api(value = "Artifact External Servlet", description = "Servlet serves external users operations on artifacts.")
76 @Singleton
77 public class ArtifactExternalServlet extends AbstractValidationsServlet {
78
79         @Context
80         private HttpServletRequest request;
81
82         private static Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class.getName());
83         
84         private static String startLog = "Start handle request of ";
85
86         /**
87          * Uploads an artifact to resource or service
88          * 
89          * @param assetType
90          * @param uuid
91          * @return
92          */
93         @POST
94         @Path("/{assetType}/{uuid}/artifacts")
95         @Produces(MediaType.APPLICATION_JSON)
96         @ApiOperation(value = "uploads of artifact to a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service", response = Response.class)
97         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact uploaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
98                         @ApiResponse(code = 404, message = "Asset not found") })
99         public Response uploadArtifact(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @ApiParam(value = "json describe the artifact", required = true) String data) {
100                 init(log);
101                 
102                 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
103                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
104                 String requestURI = request.getRequestURI();
105                 String userId = request.getHeader(Constants.USER_ID_HEADER);
106                 String url = request.getMethod() + " " + requestURI;
107                 log.debug("{} {}", startLog, url);
108                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
109                 String componentTypeValue = componentType == null ? null : componentType.getValue();
110                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
111                 
112                 if (componentType == null) {
113                         log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
114                         responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
115                 }
116                 if (responseWrapper.isEmpty()) {
117                         validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
118                 }
119                 if (responseWrapper.isEmpty() ) {
120                         validateHttpCspUserIdHeader(userId, responseWrapper);
121                 }
122                 Response response = null;
123                 try {
124                         if (responseWrapper.isEmpty()) {
125                                 ServletContext context = request.getSession().getServletContext();
126                                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
127                                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid,
128                                                 additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create));
129                                 if (uploadArtifactEither.isRight()) {
130                                         log.debug("failed to upload artifact");
131                                         responseWrapper.setInnerElement(uploadArtifactEither.right().value());
132                                 } else {
133                                         Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
134                                         Map<String, String> headers = new HashMap<>();
135                                         headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
136                                         responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK));
137                                         response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers);
138                                 }
139                         } 
140                         if( response == null ){
141                                 response = buildErrorResponse(responseWrapper.getInnerElement());
142                         }
143                         return response;
144                 } catch (Exception e) {
145                         final String message = "failed to upload artifact to a resource or service";
146                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
147                         log.debug(message, e);
148                         return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
149                 } finally {
150                         getComponentsUtils().auditExternalUploadArtifact(responseWrapper.getInnerElement(), componentTypeValue, request, additionalParams);
151                 }
152         }
153
154         /**
155          * Uploads an artifact to resource instance
156          * 
157          * @param assetType
158          * @param uuid
159          * @param resourceInstanceName
160          * @return
161          */
162         @POST
163         @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts")
164         @Produces(MediaType.APPLICATION_JSON)
165         @ApiOperation(value = "uploads an artifact to a resource instance", httpMethod = "POST", notes = "uploads an artifact to a resource instance", response = Response.class)
166         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact uploaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
167                         @ApiResponse(code = 404, message = "Asset not found") })
168         public Response uploadArtifactToInstance(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @PathParam("resourceInstanceName") final String resourceInstanceName,
169                         @ApiParam(value = "json describe the artifact", required = true) String data) {
170
171                 Wrapper<Response> responseWrapper = new Wrapper<>();
172                 ResponseFormat responseFormat = null;
173                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
174                 String requestURI = request.getRequestURI();
175                 String userId = request.getHeader(Constants.USER_ID_HEADER);
176                 String url = request.getMethod() + " " + requestURI;
177                 log.debug("{} {}", startLog, url);
178                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
179                 String componentTypeValue = componentType == null ? null : componentType.getValue();
180                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
181                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
182                 if (componentType == null) {
183                         log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
184                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
185                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
186                 }
187                 if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
188                         log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");
189                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
190                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
191                 }
192                 if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
193                         log.debug("uploadArtifact: Missing USER_ID header");
194                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
195                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
196                 }
197                 try {
198                         if (responseWrapper.isEmpty()) {
199                                 ServletContext context = request.getSession().getServletContext();
200                                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
201                                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName,
202                                                 additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Create));
203                                 if (uploadArtifactEither.isRight()) {
204                                         log.debug("failed to upload artifact");
205                                         responseFormat = uploadArtifactEither.right().value();
206                                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
207                                 } else {
208                                         Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
209                                         Map<String, String> headers = new HashMap<>();
210                                         headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
211                                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
212                                         responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
213                                 }
214                         } 
215                 }catch (Exception e) {
216                         final String message = "failed to upload artifact to a resource instance";
217                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
218                         log.debug(message, e);
219                         responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
220                 } finally {
221                         getComponentsUtils().auditExternalUploadArtifact(responseFormat, componentTypeValue, request, additionalParams);
222                 }
223                 return responseWrapper.getInnerElement();
224         }
225
226         /**
227          * updates an artifact on a resource or service
228          * 
229          * @param assetType
230          * @param uuid
231          * @param artifactUUID
232          * @return
233          */
234         @POST
235         @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
236         @Produces(MediaType.APPLICATION_JSON)
237         @ApiOperation(value = "updates an artifact on a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service", response = Response.class)
238         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Updated"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
239                         @ApiResponse(code = 404, message = "Asset not found") })
240         public Response updateArtifact(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @PathParam("artifactUUID") final String artifactUUID,
241                         @ApiParam(value = "json describe the artifact", required = true) String data) {
242
243                 Wrapper<Response> responseWrapper = new Wrapper<>();
244                 ResponseFormat responseFormat = null;
245                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
246                 String requestURI = request.getRequestURI();
247                 String userId = request.getHeader(Constants.USER_ID_HEADER);
248                 String url = request.getMethod() + " " + requestURI;
249                 log.debug("{} {}", startLog, url);
250                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
251                 String componentTypeValue = componentType == null ? null : componentType.getValue();
252                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
253                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
254                 if (componentType == null) {
255                         log.debug("updateArtifact: assetType parameter {} is not valid", assetType);
256                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
257                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
258                 }
259                 if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
260                         log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
261                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
262                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
263                 }
264                 if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
265                         log.debug("updateArtifact: Missing USER_ID");
266                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
267                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
268                 }
269                 try {
270                         if (responseWrapper.isEmpty()) {
271                                 ServletContext context = request.getSession().getServletContext();
272                                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
273                                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID,
274                                                 additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update));
275                                 if (uploadArtifactEither.isRight()) {
276                                         log.debug("failed to update artifact");
277                                         responseFormat = uploadArtifactEither.right().value();
278                                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
279                                 } else {
280                                         Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
281                                         Map<String, String> headers = new HashMap<>();
282                                         headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
283                                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
284                                         responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
285                                 }
286                         }
287                 } catch (Exception e) {
288                         final String message = "failed to update artifact on a resource or service";
289                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
290                         log.debug(message, e);
291                         responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
292                 } finally {
293                         getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams);
294                 }
295                 return responseWrapper.getInnerElement();
296         }
297
298         /**
299          * updates an artifact on a resource instance
300          * 
301          * @param assetType
302          * @param uuid
303          * @param resourceInstanceName
304          * @param artifactUUID
305          * @return
306          */
307         @POST
308         @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
309         @Produces(MediaType.APPLICATION_JSON)
310         @ApiOperation(value = "updates an artifact on a resource instance", httpMethod = "POST", notes = "uploads of artifact to a resource or service", response = Response.class)
311         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Updated"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
312                         @ApiResponse(code = 404, message = "Asset not found") })
313         public Response updateArtifactOnResourceInstance(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @PathParam("resourceInstanceName") final String resourceInstanceName,
314                         @PathParam("artifactUUID") final String artifactUUID, @ApiParam(value = "json describe the artifact", required = true) String data) {
315
316                 Wrapper<Response> responseWrapper = new Wrapper<>();
317                 ResponseFormat responseFormat = null;
318                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
319                 String requestURI = request.getRequestURI();
320                 String userId = request.getHeader(Constants.USER_ID_HEADER);
321                 String url = request.getMethod() + " " + requestURI;
322                 log.debug("{} {}", startLog, url);
323                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
324                 String componentTypeValue = componentType == null ? null : componentType.getValue();
325                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
326                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
327                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
328                 if (componentType == null) {
329                         log.debug("updateArtifactOnResourceInstance: assetType parameter {} is not valid", assetType);
330                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
331                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
332                 }
333                 if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
334                         log.debug("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header");
335                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
336                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
337                 }
338                 if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
339                         log.debug("updateArtifactOnResourceInstance: Missing USER_ID header");
340                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
341                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
342                 }
343                 try {
344                         if (responseWrapper.isEmpty()) {
345                                 ServletContext context = request.getSession().getServletContext();
346                                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
347                                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID,
348                                                 additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Update));
349                                 if (uploadArtifactEither.isRight()) {
350                                         log.debug("failed to update artifact");
351                                         responseFormat = uploadArtifactEither.right().value();
352                                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
353                                 } else {
354                                         Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
355                                         Map<String, String> headers = new HashMap<>();
356                                         headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
357                                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
358                                         responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
359                                 }
360                         }
361                 } catch (Exception e) {
362                         final String message = "failed to update artifact on resource instance";
363                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
364                         log.debug(message, e);
365                         responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
366                 } finally {
367                         getComponentsUtils().auditExternalUpdateArtifact(responseFormat, componentTypeValue, request, additionalParams);
368                 }
369                 return responseWrapper.getInnerElement();
370         }
371
372         /**
373          * deletes an artifact of a resource or service
374          * 
375          * @param assetType
376          * @param uuid
377          * @param artifactUUID
378          * @return
379          */
380         @DELETE
381         @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
382         @Produces(MediaType.APPLICATION_JSON)
383         @ApiOperation(value = "deletes an artifact of a resource or service", httpMethod = "DELETE", notes = "deletes an artifact of a resource or service", response = Response.class)
384         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Deleted"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
385                         @ApiResponse(code = 404, message = "Asset not found") })
386         public Response deleteArtifact(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @PathParam("artifactUUID") final String artifactUUID) {
387
388                 Wrapper<Response> responseWrapper = new Wrapper<>();
389                 ResponseFormat responseFormat = null;
390                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
391                 String userId = request.getHeader(Constants.USER_ID_HEADER);
392                 String requestURI = request.getRequestURI();
393                 String url = request.getMethod() + " " + requestURI;
394                 log.debug("{} {}", startLog, url);
395                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
396                 String componentTypeValue = componentType == null ? null : componentType.getValue();
397                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
398                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
399                 if (componentType == null) {
400                         log.debug("deleteArtifact: assetType parameter {} is not valid", assetType);
401                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
402                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
403                 }
404                 if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
405                         log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header");
406                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
407                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
408                 }
409                 if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
410                         log.debug("deleteArtifact: Missing USER_ID header");
411                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
412                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
413                 }
414                 try {
415                         if (responseWrapper.isEmpty()) {
416                                 ServletContext context = request.getSession().getServletContext();
417                                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
418                                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID,
419                                                 additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete));
420                                 if (uploadArtifactEither.isRight()) {
421                                         log.debug("failed to delete artifact");
422                                         responseFormat = uploadArtifactEither.right().value();
423                                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
424                                 } else {
425                                         Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
426                                         Map<String, String> headers = new HashMap<>();
427                                         headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
428                                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
429                                         responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
430                                 }
431                         }
432                 } catch (Exception e) {
433                         final String message = "failed to delete an artifact of a resource or service";
434                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
435                         log.debug(message, e);
436                         responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
437                 } finally {
438                         getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
439                 }
440                 return responseWrapper.getInnerElement();
441         }
442
443         /**
444          * deletes an artifact of a resource instance
445          * 
446          * @param assetType
447          * @param uuid
448          * @param resourceInstanceName
449          * @return
450          */
451         @DELETE
452         @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
453         @Produces(MediaType.APPLICATION_JSON)
454         @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class)
455         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact Deleted"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
456                         @ApiResponse(code = 404, message = "Asset not found") })
457         public Response deleteArtifactOnResourceInstance(@PathParam("assetType") final String assetType, @PathParam("uuid") final String uuid, @PathParam("resourceInstanceName") final String resourceInstanceName,
458                         @PathParam("artifactUUID") final String artifactUUID) {
459
460                 Wrapper<Response> responseWrapper = new Wrapper<>();
461                 ResponseFormat responseFormat = null;
462                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
463                 String userId = request.getHeader(Constants.USER_ID_HEADER);
464                 String requestURI = request.getRequestURI();
465                 String url = request.getMethod() + " " + requestURI;
466                 log.debug("{} {}", startLog, url);
467                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
468                 String componentTypeValue = componentType == null ? null : componentType.getValue();
469                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
470                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
471                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
472                 if (componentType == null) {
473                         log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType);
474                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
475                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
476                 }
477                 if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
478                         log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header");
479                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
480                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
481                 }
482                 if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
483                         log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header");
484                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
485                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
486                 }
487                 try {
488                         if (responseWrapper.isEmpty()) {
489                                 ServletContext context = request.getSession().getServletContext();
490                                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
491                                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID,
492                                                 additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.Delete));
493                                 if (uploadArtifactEither.isRight()) {
494                                         log.debug("failed to delete artifact");
495                                         responseFormat = uploadArtifactEither.right().value();
496                                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
497                                 } else {
498                                         Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
499                                         Map<String, String> headers = new HashMap<>();
500                                         headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByString((String) representation));
501                                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
502                                         responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
503                                 }
504                         } 
505                 } catch (Exception e) {
506                         final String message = "failed to delete an artifact of a resource instance";
507                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
508                         log.debug(message, e);
509                         responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
510                 } finally {
511                         getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
512                 }
513                 return responseWrapper.getInnerElement();
514         }
515
516         /**
517          * downloads an artifact of a component (either a service or a resource) by artifactUUID
518          * 
519          * @param assetType
520          * @param uuid
521          * @param artifactUUID
522          * @return
523          */
524         @GET
525         @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
526         @Produces(MediaType.APPLICATION_OCTET_STREAM)
527         @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
528         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact downloaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
529                         @ApiResponse(code = 404, message = "Artifact not found") })
530         public Response downloadComponentArtifact(
531                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("assetType") final String assetType,
532                         @PathParam("uuid") final String uuid, @PathParam("artifactUUID") final String artifactUUID) {
533
534                 Wrapper<Response> responseWrapper = new Wrapper<>();
535                 ResponseFormat responseFormat = null;
536                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
537                 String requestURI = request.getRequestURI();
538                 String url = request.getMethod() + " " + requestURI;
539                 log.debug("{} {}", startLog, url);
540                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
541                 String componentTypeValue = componentType == null ? null : componentType.getValue();
542                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
543                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
544                 if (componentType == null) {
545                         log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType);
546                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
547                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
548                 }
549                 if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
550                         log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header");
551                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
552                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
553                 }
554                 try {
555                         if (responseWrapper.isEmpty()) {
556                                 ServletContext context = request.getSession().getServletContext();
557                                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
558                                 Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams);
559                                 if (downloadComponentArtifactEither.isRight()) {
560                                         responseFormat = downloadComponentArtifactEither.right().value();
561                                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
562                                 } else {
563                                         byte[] value = downloadComponentArtifactEither.left().value();
564                                         InputStream is = new ByteArrayInputStream(value);
565                                         Map<String, String> headers = new HashMap<>();
566                                         headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByByteArray(value));
567                                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
568                                         responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
569                                 }
570                         }
571                 } catch (Exception e) {
572                         final String message = "failed to download an artifact of a resource or service";
573                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
574                         log.debug(message, e);
575                         responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
576                 } finally {
577                         getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
578                 }
579                 return responseWrapper.getInnerElement();
580         }
581
582         /**
583          * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID
584          * 
585          * @param assetType
586          * @param uuid
587          * @param resourceInstanceName
588          * @param artifactUUID
589          * @return
590          */
591         @GET
592         @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
593         @Produces(MediaType.APPLICATION_OCTET_STREAM)
594         @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
595         @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact downloaded"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
596                         @ApiResponse(code = 404, message = "Artifact not found") })
597         public Response downloadResourceInstanceArtifact(
598                         @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("assetType") final String assetType,
599                         @PathParam("uuid") final String uuid, @PathParam("resourceInstanceName") final String resourceInstanceName, @PathParam("artifactUUID") final String artifactUUID) {
600
601                 Wrapper<Response> responseWrapper = new Wrapper<>();
602                 ResponseFormat responseFormat = null;
603                 String instanceIdHeader = request.getHeader(Constants.X_ECOMP_INSTANCE_ID_HEADER);
604                 String requestURI = request.getRequestURI();
605                 String url = request.getMethod() + " " + requestURI;
606                 log.debug("{} {}", startLog, url);
607                 ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
608                 String componentTypeValue = componentType == null ? null : componentType.getValue();
609                 EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
610                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
611                 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
612                 if (componentType == null) {
613                         log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType);
614                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
615                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
616                 }
617                 if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
618                         log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header");
619                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
620                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
621                 }
622                 try {
623                         if (responseWrapper.isEmpty()) {
624                                 ServletContext context = request.getSession().getServletContext();
625                                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
626                                 Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams);
627                                 if (downloadResourceArtifactEither.isRight()) {
628                                         responseFormat = downloadResourceArtifactEither.right().value();
629                                         responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
630                                 } else {
631                                         byte[] value = downloadResourceArtifactEither.left().value();
632                                         InputStream is = new ByteArrayInputStream(value);
633                                         Map<String, String> headers = new HashMap<>();
634                                         headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5ByByteArray(value));
635                                         responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
636                                         responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
637                                 }
638                         }
639                 } catch (Exception e) {
640                         final String message = "failed to download an artifact of a resource instance";
641                         BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
642                         log.debug(message, e);
643                         responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
644                 } finally {
645                         getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
646                 }
647                 return responseWrapper.getInnerElement();
648         }
649 }