31bc165ee09ed85b82a53765e39772c5a33ae892
[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 com.jcabi.aspects.Loggable;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.Map;
31
32 import fj.data.Either;
33 import io.swagger.annotations.Api;
34 import io.swagger.annotations.ApiImplicitParam;
35 import io.swagger.annotations.ApiImplicitParams;
36 import io.swagger.annotations.ApiOperation;
37 import io.swagger.annotations.ApiParam;
38 import io.swagger.annotations.ApiResponse;
39 import io.swagger.annotations.ApiResponses;
40 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
41 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
42 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager;
44 import org.openecomp.sdc.be.dao.api.ActionStatus;
45 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
46 import org.openecomp.sdc.be.model.ArtifactDefinition;
47 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
48 import org.openecomp.sdc.be.resources.data.auditing.model.DistributionData;
49 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
50 import org.openecomp.sdc.be.servlets.AbstractValidationsServlet;
51 import org.openecomp.sdc.be.servlets.RepresentationUtils;
52 import org.openecomp.sdc.common.api.Constants;
53 import org.openecomp.sdc.common.datastructure.Wrapper;
54 import org.openecomp.sdc.common.util.GeneralUtility;
55 import org.openecomp.sdc.exception.ResponseFormat;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import javax.inject.Singleton;
60 import javax.servlet.ServletContext;
61 import javax.servlet.http.HttpServletRequest;
62 import javax.ws.rs.DELETE;
63 import javax.ws.rs.GET;
64 import javax.ws.rs.HeaderParam;
65 import javax.ws.rs.POST;
66 import javax.ws.rs.Path;
67 import javax.ws.rs.PathParam;
68 import javax.ws.rs.Produces;
69 import javax.ws.rs.core.Context;
70 import javax.ws.rs.core.HttpHeaders;
71 import javax.ws.rs.core.MediaType;
72 import javax.ws.rs.core.Response;
73 import java.io.ByteArrayInputStream;
74 import java.io.IOException;
75 import java.io.InputStream;
76 import java.util.EnumMap;
77 import java.util.HashMap;
78 import java.util.Map;
79 /**
80  * This Servlet serves external users operations on artifacts.
81  *
82  * @author mshitrit
83  *
84  */
85 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
86 @Path("/v1/catalog")
87 @Api(value = "Artifact External Servlet", description = "Servlet serves external users operations on artifacts.")
88 @Singleton
89 public class ArtifactExternalServlet extends AbstractValidationsServlet {
90
91     private static final String FAILED_TO_UPDATE_ARTIFACT = "failed to update artifact";
92
93     @Context
94     private HttpServletRequest request;
95
96     private static final Logger log = LoggerFactory.getLogger(ArtifactExternalServlet.class);
97
98     private static String startLog = "Start handle request of ";
99
100     @POST
101     @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}")
102     @Produces(MediaType.APPLICATION_JSON)
103     @ApiOperation(value = "uploads of artifact to VF operation workflow", httpMethod = "POST", notes = "uploads of artifact to VF operation workflow")
104     @ApiResponses(value = {
105             @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
106             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
107             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
108             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
109             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
110             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
111             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
112             @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
113             @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
114             @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
115             @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
116             @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
117             @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
118             @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
119     @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
120     public Response uploadInterfaceOperationArtifact(
121             @ApiParam(value = "Determines the format of the body of the request", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contenType,
122             @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true) @HeaderParam(value = Constants.MD5_HEADER) String checksum,
123             @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true) @HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
124             @ApiParam(value = "X-ECOMP-RequestID header", required = false) @HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
125             @ApiParam(value = "X-ECOMP-InstanceID header", required = true) @HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
126             @ApiParam(value = "Determines the format of the body of the response", required = false) @HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
127             @ApiParam(value = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
128             @ApiParam(value = "Asset type") @PathParam("assetType") String assetType,
129             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
130             @ApiParam(value = "The uuid of the interface", required = true)@PathParam("interfaceUUID") final String interfaceUUID,
131             @ApiParam(value = "The uuid of the operation", required = true)@PathParam("operationUUID") final String operationUUID,
132             @ApiParam(value = "The uuid of the artifact", required = true)@PathParam("artifactUUID") final String artifactUUID,
133             @ApiParam( hidden = true) String data) {
134         Wrapper<Response> responseWrapper = new Wrapper<>();
135         ResponseFormat responseFormat = null;
136         String requestURI = request.getRequestURI();
137         String url = request.getMethod() + " " + requestURI;
138         log.debug("{} {}", startLog, url);
139         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(assetType);
140         ArtifactDefinition artifactDefinition = null;
141
142         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
143             log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
144             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
145             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
146         }
147         if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
148             log.debug("updateArtifact: Missing USER_ID");
149             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
150             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
151         }
152         try {
153             if (responseWrapper.isEmpty()) {
154                 ServletContext context = request.getSession().getServletContext();
155                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
156                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic
157                         .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum
158                                         .findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID,
159                         resourceCommonInfo, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
160                 if (uploadArtifactEither.isRight()) {
161                     log.debug(FAILED_TO_UPDATE_ARTIFACT);
162                     responseFormat = uploadArtifactEither.right().value();
163                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
164                 } else {
165                     artifactDefinition=uploadArtifactEither.left().value();
166                     Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
167                     Map<String, String> headers = new HashMap<>();
168                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
169                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
170                     responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
171                 }
172             }
173         } catch (Exception e) {
174             final String message = "failed to update artifact on a resource or service";
175             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
176             log.debug(message, e);
177             responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
178         } finally {
179             getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,
180                     resourceCommonInfo, request, artifactDefinition, null);
181         }
182         return responseWrapper.getInnerElement();
183     }
184
185     /**
186      * Uploads an artifact to resource or service
187      *
188      * @param contenType
189      * @param checksum
190      * @param userId
191      * @param requestId
192      * @param instanceIdHeader
193      * @param accept
194      * @param authorization
195      * @param assetType
196      * @param uuid
197      * @param data
198      * @return
199      */
200     @POST
201     @Path("/{assetType}/{uuid}/artifacts")
202     @Produces(MediaType.APPLICATION_JSON)
203     @ApiOperation(value = "uploads of artifact to a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
204     @ApiResponses(value = {
205             @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
206             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
207             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
208             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
209             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
210             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
211             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
212             @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
213             @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
214             @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
215             @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
216             @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
217             @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
218             @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
219     @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
220     public Response uploadArtifact(
221             @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
222             @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
223             @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
224             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
225             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
226             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
227             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
228             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
229             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
230             @ApiParam( hidden = true) String data) {
231
232         init();
233
234         Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
235         String requestURI = request.getRequestURI();
236         String url = request.getMethod() + " " + requestURI;
237         log.debug("{} {}", startLog, url);
238         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
239         String componentTypeValue = componentType == null ? null : componentType.getValue();
240         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
241
242         if (componentType == null) {
243             log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
244             responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
245         }
246         if (responseWrapper.isEmpty()) {
247             validateXECOMPInstanceIDHeader(instanceIdHeader, responseWrapper);
248         }
249         if (responseWrapper.isEmpty() ) {
250             validateHttpCspUserIdHeader(userId, responseWrapper);
251         }
252         Response response = null;
253         ArtifactDefinition artifactDefinition = null;
254         try {
255             if (responseWrapper.isEmpty()) {
256                 ServletContext context = request.getSession().getServletContext();
257                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
258                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToComponentByUUID(data, request, componentType, uuid,
259                         resourceCommonInfo, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
260                 if (uploadArtifactEither.isRight()) {
261                     log.debug("failed to upload artifact");
262                     responseWrapper.setInnerElement(uploadArtifactEither.right().value());
263                 } else {
264                     artifactDefinition = uploadArtifactEither.left().value();
265                     Object representation = RepresentationUtils.toRepresentation(artifactDefinition);
266                     Map<String, String> headers = new HashMap<>();
267                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
268                     responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.OK));
269                     response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers);
270                 }
271             }
272         } catch (IOException e) {
273             final String message = "failed to upload artifact to a resource or service";
274             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
275             log.debug(message, e);
276             responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
277             response = buildErrorResponse(responseWrapper.getInnerElement());
278         }   catch (ComponentException e){
279             responseWrapper.setInnerElement(getComponentsUtils().getResponseFormat(e));
280         }finally {
281             if( response == null ){
282                 response = buildErrorResponse(responseWrapper.getInnerElement());
283             }
284             getComponentsUtils().auditExternalCrudApi(responseWrapper.getInnerElement(), AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,
285                     resourceCommonInfo, request, artifactDefinition, null);
286         }
287         return response;
288     }
289
290     /**
291      * Uploads an artifact to resource instance
292      *
293      * @param assetType
294      * @param uuid
295      * @param resourceInstanceName
296      * @return
297      */
298     @POST
299     @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts")
300     @Produces(MediaType.APPLICATION_JSON)
301     @ApiOperation(value = "uploads an artifact to a resource instance", httpMethod = "POST", notes = "uploads an artifact to a resource instance")
302     @ApiResponses(value = {
303             @ApiResponse(code = 200, message = "Artifact uploaded", response = ArtifactDefinition.class),
304             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
305             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
306             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
307             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
308             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
309             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
310             @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
311             @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
312             @ApiResponse(code = 400, message = "Artifact name given in input already exists in the context of the asset - SVC4125"),
313             @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
314             @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
315             @ApiResponse(code = 400, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
316             @ApiResponse(code = 400, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
317     @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
318     public Response uploadArtifactToInstance(
319             @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
320             @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
321             @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
322             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
323             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
324             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
325             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
326             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
327             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
328             @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName,
329             @ApiParam( hidden = true) String data) {
330
331         Wrapper<Response> responseWrapper = new Wrapper<>();
332         ResponseFormat responseFormat = null;
333         String requestURI = request.getRequestURI();
334         String url = request.getMethod() + " " + requestURI;
335         log.debug("{} {}", startLog, url);
336         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
337         String componentTypeValue = componentType == null ? null : componentType.getValue();
338         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);
339         ArtifactDefinition artifactDefinition = null;
340
341         if (componentType == null) {
342             log.debug("uploadArtifact: assetType parameter {} is not valid", assetType);
343             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
344             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
345         }
346         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
347             log.debug("uploadArtifact: Missing X-ECOMP-InstanceID header");
348             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
349             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
350         }
351         if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
352             log.debug("uploadArtifact: Missing USER_ID header");
353             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
354             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
355         }
356         try {
357             if (responseWrapper.isEmpty()) {
358                 ServletContext context = request.getSession().getServletContext();
359                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
360                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.uploadArtifactToRiByUUID(data, request, componentType, uuid, resourceInstanceName,
361                         artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.CREATE));
362                 if (uploadArtifactEither.isRight()) {
363                     log.debug("failed to upload artifact");
364                     responseFormat = uploadArtifactEither.right().value();
365                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
366                 } else {
367                     Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
368                     Map<String, String> headers = new HashMap<>();
369                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
370                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
371                     responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
372                 }
373             }
374         }catch (IOException e) {
375             final String message = "failed to upload artifact to a resource instance";
376             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
377             log.debug(message, e);
378             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
379             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
380         }catch (ComponentException e){
381             responseFormat = getComponentsUtils().getResponseFormat(e);
382         }finally {
383             getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API,
384                     resourceCommonInfo, request, artifactDefinition, null);
385         }
386         return responseWrapper.getInnerElement();
387     }
388
389     /**
390      *
391      * @param contenType
392      * @param checksum
393      * @param userId
394      * @param requestId
395      * @param instanceIdHeader
396      * @param accept
397      * @param authorization
398      * @param assetType
399      * @param uuid
400      * @param artifactUUID
401      * @param data
402      * @return
403      */
404     @POST
405     @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
406     @Produces(MediaType.APPLICATION_JSON)
407     @ApiOperation(value = "updates an artifact on a resource or service", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
408     @ApiResponses(value = {
409             @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class),
410             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
411             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
412             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
413             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
414             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
415             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
416             @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
417             @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
418             @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
419             @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
420             @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
421             @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
422     @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
423     public Response updateArtifact(
424             @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
425             @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
426             @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
427             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
428             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
429             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
430             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
431             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
432             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
433             @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
434             @ApiParam(hidden = true) String data) {
435
436         Wrapper<Response> responseWrapper = new Wrapper<>();
437         ResponseFormat responseFormat = null;
438         String requestURI = request.getRequestURI();
439         String url = request.getMethod() + " " + requestURI;
440         log.debug("{} {}", startLog, url);
441         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
442         String componentTypeValue = componentType == null ? null : componentType.getValue();
443         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
444         if (componentType == null) {
445             log.debug("updateArtifact: assetType parameter {} is not valid", assetType);
446             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
447             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
448         }
449         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
450             log.debug("updateArtifact: Missing X-ECOMP-InstanceID header");
451             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
452             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
453         }
454         if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
455             log.debug("updateArtifact: Missing USER_ID");
456             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
457             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
458         }
459         ArtifactDefinition artifactDefinition = null;
460         try {
461             if (responseWrapper.isEmpty()) {
462                 ServletContext context = request.getSession().getServletContext();
463                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
464                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnComponentByUUID(data, request, componentType, uuid, artifactUUID,
465                         resourceCommonInfo, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
466                 if (uploadArtifactEither.isRight()) {
467                     log.debug(FAILED_TO_UPDATE_ARTIFACT);
468                     responseFormat = uploadArtifactEither.right().value();
469                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
470                 } else {
471                     Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
472                     Map<String, String> headers = new HashMap<>();
473                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
474                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
475                     responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
476                 }
477             }
478         } catch (IOException e) {
479             final String message = "failed to update artifact on a resource or service";
480             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
481             log.debug(message, e);
482             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
483             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
484         }  catch (ComponentException e){
485             responseFormat = getComponentsUtils().getResponseFormat(e);
486         }
487         finally{
488             getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo,
489                     request, artifactDefinition, artifactUUID);
490         }
491         return responseWrapper.getInnerElement();
492     }
493
494     /**
495      * updates an artifact on a resource instance
496      *
497      * @param assetType
498      * @param uuid
499      * @param resourceInstanceName
500      * @param artifactUUID
501      * @return
502      */
503     @POST
504     @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
505     @Produces(MediaType.APPLICATION_JSON)
506     @ApiOperation(value = "updates an artifact on a resource instance", httpMethod = "POST", notes = "uploads of artifact to a resource or service")
507     @ApiResponses(value = {
508             @ApiResponse(code = 200, message = "Artifact updated", response = ArtifactDefinition.class),
509             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
510             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
511             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
512             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
513             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
514             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
515             @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
516             @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
517             @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
518             @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
519             @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
520             @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
521     @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "org.openecomp.sdc.be.model.ArtifactDefinition", paramType = "body", value = "json describe the artifact")})
522     public Response updateArtifactOnResourceInstance(
523             @ApiParam(value = "Determines the format of the body of the request", required = true)@HeaderParam(value = Constants.CONTENT_TYPE_HEADER) String contenType,
524             @ApiParam(value = "The value for this header must be the MD5 checksum over the whole json body", required = true)@HeaderParam(value = Constants.MD5_HEADER) String checksum,
525             @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
526             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
527             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
528             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
529             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
530             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
531             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
532             @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
533             @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName,
534             @ApiParam( hidden = true) String data) {
535
536         Wrapper<Response> responseWrapper = new Wrapper<>();
537         ResponseFormat responseFormat = null;
538         String requestURI = request.getRequestURI();
539         String url = request.getMethod() + " " + requestURI;
540         log.debug("{} {}", startLog, url);
541         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
542         String componentTypeValue = componentType == null ? null : componentType.getValue();
543         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);
544         if (componentType == null) {
545             log.debug("updateArtifactOnResourceInstance: 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("updateArtifactOnResourceInstance: Missing X-ECOMP-InstanceID header");
551             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
552             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
553         }
554         if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
555             log.debug("updateArtifactOnResourceInstance: Missing USER_ID header");
556             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
557             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
558         }
559         ArtifactDefinition artifactDefinition = null;
560         try {
561             if (responseWrapper.isEmpty()) {
562                 ServletContext context = request.getSession().getServletContext();
563                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
564                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.updateArtifactOnRiByUUID(data, request, componentType, uuid, resourceInstanceName, artifactUUID,
565                          artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE));
566                 if (uploadArtifactEither.isRight()) {
567                     log.debug(FAILED_TO_UPDATE_ARTIFACT);
568                     responseFormat = uploadArtifactEither.right().value();
569                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
570                 } else {
571                     Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
572                     Map<String, String> headers = new HashMap<>();
573                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
574                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
575                     responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
576                 }
577             }
578         } catch (IOException e) {
579             final String message = "failed to update artifact on resource instance";
580             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
581             log.debug(message, e);
582             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
583             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
584         }  catch (ComponentException e){
585             responseFormat = getComponentsUtils().getResponseFormat(e);
586         }
587         finally{
588             getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_UPDATE_BY_API, resourceCommonInfo,
589                     request, artifactDefinition, artifactUUID);
590         }
591         return responseWrapper.getInnerElement();
592     }
593
594     /**
595      * deletes an artifact of a resource or service
596      *
597      * @param assetType
598      * @param uuid
599      * @param artifactUUID
600      * @return
601      */
602     @DELETE
603     @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
604     @Produces(MediaType.APPLICATION_JSON)
605     @ApiOperation(value = "deletes an artifact of a resource or service", httpMethod = "DELETE", notes = "deletes an artifact of a resource or service", response = Response.class)
606     @ApiResponses(value = {
607             @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
608             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
609             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
610             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
611             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
612             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
613             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
614             @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
615             @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
616             @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
617             @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
618             @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
619             @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
620     public Response deleteArtifact(
621             @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
622             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
623             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
624             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
625             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
626             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
627             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
628             @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) {
629
630         Wrapper<Response> responseWrapper = new Wrapper<>();
631         ResponseFormat responseFormat = null;
632         String requestURI = request.getRequestURI();
633         String url = request.getMethod() + " " + requestURI;
634         log.debug("{} {}", startLog, url);
635         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
636         String componentTypeValue = componentType == null ? null : componentType.getValue();
637         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
638         ArtifactDefinition artifactDefinition = null;
639         if (componentType == null) {
640             log.debug("deleteArtifact: assetType parameter {} is not valid", assetType);
641             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
642             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
643         }
644         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
645             log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header");
646             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
647             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
648         }
649         if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
650             log.debug("deleteArtifact: Missing USER_ID header");
651             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
652             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
653         }
654         try {
655             if (responseWrapper.isEmpty()) {
656                 ServletContext context = request.getSession().getServletContext();
657                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
658                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID,
659                         resourceCommonInfo, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
660                 if (uploadArtifactEither.isRight()) {
661                     log.debug("failed to delete artifact");
662                     responseFormat = uploadArtifactEither.right().value();
663                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
664                 } else {
665                     Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
666                     Map<String, String> headers = new HashMap<>();
667                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
668                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
669                     responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
670                 }
671             }
672         } catch (IOException e) {
673             final String message = "failed to delete an artifact of a resource or service";
674             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
675             log.debug(message, e);
676             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
677             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
678         }  catch (ComponentException e){
679             responseFormat = getComponentsUtils().getResponseFormat(e);
680         }
681         finally{
682             getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo,
683                     request, artifactDefinition, artifactUUID);
684         }
685         return responseWrapper.getInnerElement();
686     }
687
688     /**
689      * deletes an artifact of a resource instance
690      *
691      * @param assetType
692      * @param uuid
693      * @param resourceInstanceName
694      * @return
695      */
696     @DELETE
697     @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
698     @Produces(MediaType.APPLICATION_JSON)
699     @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class)
700     @ApiResponses(value = {
701             @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
702             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
703             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
704             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
705             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
706             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
707             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
708             @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
709             @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
710             @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
711             @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
712             @ApiResponse(code = 403, message = "Asset is being edited by different user. Only one user can checkout and edit an asset on given time. The asset will be available for checkout after the other user will checkin the asset - SVC4086"),
713             @ApiResponse(code = 409, message = "Restricted Operation – the user provided does not have role of Designer or the asset is being used by another designer - SVC4301")})
714     public Response deleteArtifactOnResourceInstance(
715             @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
716             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
717             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
718             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
719             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
720             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
721             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
722             @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
723             @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
724
725         Wrapper<Response> responseWrapper = new Wrapper<>();
726         ResponseFormat responseFormat = null;
727         String requestURI = request.getRequestURI();
728         String url = request.getMethod() + " " + requestURI;
729         log.debug("{} {}", startLog, url);
730         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
731         String componentTypeValue = componentType == null ? null : componentType.getValue();
732         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(resourceInstanceName, componentTypeValue);
733         if (componentType == null) {
734             log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType);
735             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
736             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
737         }
738         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
739             log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header");
740             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
741             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
742         }
743         if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
744             log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header");
745             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
746             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
747         }
748         ArtifactDefinition artifactDefinition = null;
749         try {
750             if (responseWrapper.isEmpty()) {
751                 ServletContext context = request.getSession().getServletContext();
752                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
753                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID,
754                          artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
755                 if (uploadArtifactEither.isRight()) {
756                     log.debug("failed to delete artifact");
757                     responseFormat = uploadArtifactEither.right().value();
758                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
759                 } else {
760                     Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
761                     Map<String, String> headers = new HashMap<>();
762                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
763                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
764                     responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
765                 }
766             }
767         } catch (IOException e) {
768             final String message = "failed to delete an artifact of a resource instance";
769             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
770             log.debug(message, e);
771             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
772             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
773         }  catch (ComponentException e){
774             responseFormat = getComponentsUtils().getResponseFormat(e);
775         }
776         finally{
777             getComponentsUtils().auditExternalCrudApi(responseFormat, AuditingActionEnum.ARTIFACT_DELETE_BY_API, resourceCommonInfo,
778                     request, artifactDefinition, artifactUUID);
779         }
780         return responseWrapper.getInnerElement();
781     }
782
783     /**
784      * downloads an artifact of a component (either a service or a resource) by artifactUUID
785      *
786      * @param assetType
787      * @param uuid
788      * @param artifactUUID
789      * @return
790      */
791     @GET
792     @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
793     @Produces(MediaType.APPLICATION_OCTET_STREAM)
794     @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact")
795     @ApiResponses(value = {
796             @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
797             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
798             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
799             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
800             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
801             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
802             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
803             @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
804     public Response downloadComponentArtifact(
805             @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
806             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
807             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
808             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
809             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
810             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
811             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
812             @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID) {
813
814         Wrapper<Response> responseWrapper = new Wrapper<>();
815         ResponseFormat responseFormat = null;
816         String requestURI = request.getRequestURI();
817         String url = request.getMethod() + " " + requestURI;
818         log.debug("{} {}", startLog, url);
819         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
820         String componentTypeValue = componentType == null ? null : componentType.getValue();
821         if (componentType == null) {
822             log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType);
823             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
824             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
825         }
826         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
827             log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header");
828             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
829             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
830         }
831         ResourceCommonInfo resourceCommonInfo = new ResourceCommonInfo(componentTypeValue);
832         try {
833             if (responseWrapper.isEmpty()) {
834                 ServletContext context = request.getSession().getServletContext();
835                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
836                 Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, resourceCommonInfo);
837                 if (downloadComponentArtifactEither.isRight()) {
838                     responseFormat = downloadComponentArtifactEither.right().value();
839                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
840                 } else {
841                     byte[] value = downloadComponentArtifactEither.left().value();
842                     InputStream is = new ByteArrayInputStream(value);
843                     Map<String, String> headers = new HashMap<>();
844                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
845                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
846                     responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
847                 }
848             }
849         }  catch (ComponentException e){
850             responseFormat = getComponentsUtils().getResponseFormat(e);
851         }
852         finally{
853             getComponentsUtils().auditExternalDownloadArtifact(responseFormat, resourceCommonInfo,
854                     new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId);
855         }
856         return responseWrapper.getInnerElement();
857     }
858
859     /**
860      * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID
861      *
862      * @param assetType
863      * @param uuid
864      * @param resourceInstanceName
865      * @param artifactUUID
866      * @return
867      */
868     @GET
869     @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
870     @Produces(MediaType.APPLICATION_OCTET_STREAM)
871     @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
872     @ApiResponses(value = {
873             @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
874             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
875             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
876             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
877             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
878             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
879             @ApiResponse(code = 500, message = "The GET request failed either due to internal SDC problem or Cambria Service failure. ECOMP Component should continue the attempts to get the needed information - POL5000"),
880             @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
881     public Response downloadResourceInstanceArtifact(
882             @ApiParam(value = "The user ID of the DCAE Designer. This user must also have Designer role in SDC", required = true)@HeaderParam(value = Constants.USER_ID_HEADER) final String userId,
883             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
884             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
885             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
886             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
887             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
888             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
889             @ApiParam(value = "The uuid of the artifact as published in the asset detailed metadata or in the response of the upload / update operation", required = true)@PathParam("artifactUUID") final String artifactUUID,
890             @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
891
892         Wrapper<Response> responseWrapper = new Wrapper<>();
893         ResponseFormat responseFormat = null;
894         String requestURI = request.getRequestURI();
895         String url = request.getMethod() + " " + requestURI;
896         log.debug("{} {}", startLog, url);
897         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
898         String componentTypeValue = componentType == null ? null : componentType.getValue();
899         if (componentType == null) {
900             log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType);
901             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
902             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
903         }
904         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
905             log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header");
906             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
907             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
908         }
909         try {
910             if (responseWrapper.isEmpty()) {
911                 ServletContext context = request.getSession().getServletContext();
912                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
913                 Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID);
914                 if (downloadResourceArtifactEither.isRight()) {
915                     responseFormat = downloadResourceArtifactEither.right().value();
916                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
917                 } else {
918                     byte[] value = downloadResourceArtifactEither.left().value();
919                     InputStream is = new ByteArrayInputStream(value);
920                     Map<String, String> headers = new HashMap<>();
921                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
922                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
923                     responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
924                 }
925             }
926         }  catch (ComponentException e){
927             responseFormat = getComponentsUtils().getResponseFormat(e);
928         }
929         finally{
930             getComponentsUtils().auditExternalDownloadArtifact(responseFormat, new ResourceCommonInfo(resourceInstanceName, componentTypeValue),
931                     new DistributionData(instanceIdHeader, requestURI), requestId, artifactUUID, userId);
932         }
933         return responseWrapper.getInnerElement();
934     }
935 }