b634abba82b1a67e6882dfbff691a98c8ee4ae53
[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             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             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             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             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             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 = { @ApiResponse(code = 200, message = "Artifact Deleted"), @ApiResponse(code = 401, message = "Authorization required"), @ApiResponse(code = 403, message = "Restricted operation"),
569             @ApiResponse(code = 404, message = "Asset not found") })*/
570     @ApiResponses(value = {
571             @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
572             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
573             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
574             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
575             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
576             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
577             @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"),
578             @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
579             @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
580             @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
581             @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
582             @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"),
583             @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")})
584     public Response deleteArtifact(
585             @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,
586             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
587             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
588             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
589             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
590             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
591             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
592             @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) {
593
594         Wrapper<Response> responseWrapper = new Wrapper<>();
595         ResponseFormat responseFormat = null;
596         String requestURI = request.getRequestURI();
597         String url = request.getMethod() + " " + requestURI;
598         log.debug("{} {}", startLog, url);
599         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
600         String componentTypeValue = componentType == null ? null : componentType.getValue();
601         EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
602         additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
603         if (componentType == null) {
604             log.debug("deleteArtifact: assetType parameter {} is not valid", assetType);
605             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
606             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
607         }
608         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
609             log.debug("deleteArtifact: Missing X-ECOMP-InstanceID header");
610             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
611             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
612         }
613         if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
614             log.debug("deleteArtifact: Missing USER_ID header");
615             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
616             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
617         }
618         try {
619             if (responseWrapper.isEmpty()) {
620                 ServletContext context = request.getSession().getServletContext();
621                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
622                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnComponentByUUID(request, componentType, uuid, artifactUUID,
623                         additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
624                 if (uploadArtifactEither.isRight()) {
625                     log.debug("failed to delete artifact");
626                     responseFormat = uploadArtifactEither.right().value();
627                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
628                 } else {
629                     Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
630                     Map<String, String> headers = new HashMap<>();
631                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
632                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
633                     responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
634                 }
635             }
636         } catch (Exception e) {
637             final String message = "failed to delete an artifact of a resource or service";
638             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
639             log.debug(message, e);
640             responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
641         } finally {
642             getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
643         }
644         return responseWrapper.getInnerElement();
645     }
646
647     /**
648      * deletes an artifact of a resource instance
649      *
650      * @param assetType
651      * @param uuid
652      * @param resourceInstanceName
653      * @return
654      */
655     @DELETE
656     @Path("{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
657     @Produces(MediaType.APPLICATION_JSON)
658     @ApiOperation(value = "deletes an artifact of a resource insatnce", httpMethod = "DELETE", notes = "deletes an artifact of a resource insatnce", response = Response.class)
659     @ApiResponses(value = {
660             @ApiResponse(code = 200, message = "Artifact deleted", response = ArtifactDefinition.class),
661             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
662             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
663             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
664             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
665             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
666             @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"),
667             @ApiResponse(code = 400, message = "Invalid artifactType was defined as input - SVC4122"),
668             @ApiResponse(code = 400, message = "Artifact type (mandatory field) is missing in request - SVC4124"),
669             @ApiResponse(code = 400, message = "Invalid MD5 header - SVC4127"),
670             @ApiResponse(code = 400, message = "Artifact name is missing in input - SVC4128"),
671             @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"),
672             @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")})
673     public Response deleteArtifactOnResourceInstance(
674             @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,
675             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
676             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
677             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
678             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
679             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
680             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
681             @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,
682             @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
683
684         Wrapper<Response> responseWrapper = new Wrapper<>();
685         ResponseFormat responseFormat = null;
686         String requestURI = request.getRequestURI();
687         String url = request.getMethod() + " " + requestURI;
688         log.debug("{} {}", startLog, url);
689         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
690         String componentTypeValue = componentType == null ? null : componentType.getValue();
691         EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
692         additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
693         additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
694         if (componentType == null) {
695             log.debug("deleteArtifactOnResourceInsatnce: assetType parameter {} is not valid", assetType);
696             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
697             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
698         }
699         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
700             log.debug("deleteArtifactOnResourceInsatnce: Missing X-ECOMP-InstanceID header");
701             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
702             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
703         }
704         if (responseWrapper.isEmpty() && (userId == null || userId.isEmpty())) {
705             log.debug("deleteArtifactOnResourceInsatnce: Missing USER_ID header");
706             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_USER_ID);
707             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
708         }
709         try {
710             if (responseWrapper.isEmpty()) {
711                 ServletContext context = request.getSession().getServletContext();
712                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
713                 Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic.deleteArtifactOnRiByUUID(request, componentType, uuid, resourceInstanceName, artifactUUID,
714                         additionalParams, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.DELETE));
715                 if (uploadArtifactEither.isRight()) {
716                     log.debug("failed to delete artifact");
717                     responseFormat = uploadArtifactEither.right().value();
718                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
719                 } else {
720                     Object representation = RepresentationUtils.toRepresentation(uploadArtifactEither.left().value());
721                     Map<String, String> headers = new HashMap<>();
722                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByString((String) representation));
723                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
724                     responseWrapper.setInnerElement(buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), representation, headers));
725                 }
726             }
727         } catch (Exception e) {
728             final String message = "failed to delete an artifact of a resource instance";
729             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
730             log.debug(message, e);
731             responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
732         } finally {
733             getComponentsUtils().auditExternalDeleteArtifact(responseFormat, componentTypeValue, request, additionalParams);
734         }
735         return responseWrapper.getInnerElement();
736     }
737
738     /**
739      * downloads an artifact of a component (either a service or a resource) by artifactUUID
740      *
741      * @param assetType
742      * @param uuid
743      * @param artifactUUID
744      * @return
745      */
746     @GET
747     @Path("/{assetType}/{uuid}/artifacts/{artifactUUID}")
748     @Produces(MediaType.APPLICATION_OCTET_STREAM)
749     @ApiOperation(value = "Download component artifact", httpMethod = "GET", notes = "Returns downloaded artifact")
750     @ApiResponses(value = {
751             @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
752             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
753             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
754             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
755             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
756             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
757             @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"),
758             @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
759     public Response downloadComponentArtifact(
760             @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,
761             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
762             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
763             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
764             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
765             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
766             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
767             @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) {
768
769         Wrapper<Response> responseWrapper = new Wrapper<>();
770         ResponseFormat responseFormat = null;
771         String requestURI = request.getRequestURI();
772         String url = request.getMethod() + " " + requestURI;
773         log.debug("{} {}", startLog, url);
774         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
775         String componentTypeValue = componentType == null ? null : componentType.getValue();
776         EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
777         additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
778         if (componentType == null) {
779             log.debug("downloadComponentArtifact: assetType parameter {} is not valid", assetType);
780             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
781             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
782         }
783         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
784             log.debug("downloadComponentArtifact: Missing X-ECOMP-InstanceID header");
785             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
786             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
787         }
788         try {
789             if (responseWrapper.isEmpty()) {
790                 ServletContext context = request.getSession().getServletContext();
791                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
792                 Either<byte[], ResponseFormat> downloadComponentArtifactEither = artifactsLogic.downloadComponentArtifactByUUIDs(componentType, uuid, artifactUUID, additionalParams);
793                 if (downloadComponentArtifactEither.isRight()) {
794                     responseFormat = downloadComponentArtifactEither.right().value();
795                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
796                 } else {
797                     byte[] value = downloadComponentArtifactEither.left().value();
798                     InputStream is = new ByteArrayInputStream(value);
799                     Map<String, String> headers = new HashMap<>();
800                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
801                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
802                     responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
803                 }
804             }
805         } catch (Exception e) {
806             final String message = "failed to download an artifact of a resource or service";
807             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
808             log.debug(message, e);
809             responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
810         } finally {
811             getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
812         }
813         return responseWrapper.getInnerElement();
814     }
815
816     /**
817      * downloads an artifact of a resource instance of a component (either a service or a resource) by artifactUUID
818      *
819      * @param assetType
820      * @param uuid
821      * @param resourceInstanceName
822      * @param artifactUUID
823      * @return
824      */
825     @GET
826     @Path("/{assetType}/{uuid}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}")
827     @Produces(MediaType.APPLICATION_OCTET_STREAM)
828     @ApiOperation(value = "Download resource instance artifact", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
829     @ApiResponses(value = {
830             @ApiResponse(code = 200, message = "Artifact downloaded", response = String.class),
831             @ApiResponse(code = 400, message = "Missing  'X-ECOMP-InstanceID'  HTTP header - POL5001"),
832             @ApiResponse(code = 401, message = "ECOMP component  should authenticate itself  and  to  re-send  again  HTTP  request  with its Basic  Authentication credentials - POL5002"),
833             @ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
834             @ApiResponse(code = 404, message = "Specified resource is not found - SVC4063"),
835             @ApiResponse(code = 405, message = "Method  Not Allowed: Invalid HTTP method type used (PUT,DELETE,POST will be rejected) - POL4050"),
836             @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"),
837             @ApiResponse(code = 404, message = "Artifact was not found - SVC4505")})
838     public Response downloadResourceInstanceArtifact(
839             @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,
840             @ApiParam(value = "X-ECOMP-RequestID header", required = false)@HeaderParam(value = Constants.X_ECOMP_REQUEST_ID_HEADER) String requestId,
841             @ApiParam(value = "X-ECOMP-InstanceID header", required = true)@HeaderParam(value = Constants.X_ECOMP_INSTANCE_ID_HEADER) final String instanceIdHeader,
842             @ApiParam(value = "Determines the format of the body of the response", required = false)@HeaderParam(value = Constants.ACCEPT_HEADER) String accept,
843             @ApiParam(value = "The username and password", required = true)@HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization,
844             @ApiParam(value = "The requested asset type", required = true, allowableValues = "resources, services")@PathParam("assetType") final String assetType,
845             @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid,
846             @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,
847             @ApiParam(value = "The component instance name (as publishedin the response of the detailed query)", required = true)@PathParam("resourceInstanceName") final String resourceInstanceName) {
848
849         Wrapper<Response> responseWrapper = new Wrapper<>();
850         ResponseFormat responseFormat = null;
851         String requestURI = request.getRequestURI();
852         String url = request.getMethod() + " " + requestURI;
853         log.debug("{} {}", startLog, url);
854         ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(assetType);
855         String componentTypeValue = componentType == null ? null : componentType.getValue();
856         EnumMap<AuditingFieldsKeysEnum, Object> additionalParams = new EnumMap<>(AuditingFieldsKeysEnum.class);
857         additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
858         additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
859         if (componentType == null) {
860             log.debug("downloadResourceInstanceArtifact: assetType parameter {} is not valid", assetType);
861             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
862             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
863         }
864         if (responseWrapper.isEmpty() && (instanceIdHeader == null || instanceIdHeader.isEmpty())) {
865             log.debug("downloadResourceInstanceArtifact: Missing X-ECOMP-InstanceID header");
866             responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.MISSING_X_ECOMP_INSTANCE_ID);
867             responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
868         }
869         try {
870             if (responseWrapper.isEmpty()) {
871                 ServletContext context = request.getSession().getServletContext();
872                 ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
873                 Either<byte[], ResponseFormat> downloadResourceArtifactEither = artifactsLogic.downloadResourceInstanceArtifactByUUIDs(componentType, uuid, resourceInstanceName, artifactUUID, additionalParams);
874                 if (downloadResourceArtifactEither.isRight()) {
875                     responseFormat = downloadResourceArtifactEither.right().value();
876                     responseWrapper.setInnerElement(buildErrorResponse(responseFormat));
877                 } else {
878                     byte[] value = downloadResourceArtifactEither.left().value();
879                     InputStream is = new ByteArrayInputStream(value);
880                     Map<String, String> headers = new HashMap<>();
881                     headers.put(Constants.MD5_HEADER, GeneralUtility.calculateMD5Base64EncodedByByteArray(value));
882                     responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
883                     responseWrapper.setInnerElement(buildOkResponse(responseFormat, is, headers));
884                 }
885             }
886         } catch (Exception e) {
887             final String message = "failed to download an artifact of a resource instance";
888             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(message);
889             log.debug(message, e);
890             responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)));
891         } finally {
892             getComponentsUtils().auditExternalDownloadArtifact(responseFormat, componentTypeValue, request, additionalParams);
893         }
894         return responseWrapper.getInnerElement();
895     }
896 }