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