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