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