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