875b51548e0e5530684eedcebb4630f1e78b43c0
[sdc.git] /
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.sdcrests.action.rest.services;
22
23 import org.apache.commons.codec.digest.DigestUtils;
24 import org.apache.commons.lang3.StringUtils;
25 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
26 import org.openecomp.core.utilities.file.FileUtils;
27 import org.openecomp.core.utilities.json.JsonUtil;
28 import org.openecomp.sdc.action.ActionConstants;
29 import org.openecomp.sdc.action.ActionManager;
30 import org.openecomp.sdc.action.errors.ActionErrorConstants;
31 import org.openecomp.sdc.action.errors.ActionException;
32 import org.openecomp.sdc.action.logging.CategoryLogLevel;
33 import org.openecomp.sdc.action.logging.StatusCode;
34 import org.openecomp.sdc.action.types.*;
35 import org.openecomp.sdc.logging.api.Logger;
36 import org.openecomp.sdc.logging.api.LoggerFactory;
37 import org.openecomp.sdcrests.action.rest.Actions;
38 import org.openecomp.sdcrests.action.rest.mapping.MapActionToActionResponseDto;
39 import org.openecomp.sdcrests.action.types.ActionResponseDto;
40 import org.openecomp.sdcrests.action.types.ActionVersionDto;
41 import org.openecomp.sdcrests.action.types.ListResponseWrapper;
42 import org.openecomp.sdcrests.wrappers.StringWrapperResponse;
43 import org.slf4j.MDC;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.context.annotation.Scope;
46 import org.springframework.stereotype.Service;
47 import org.springframework.validation.annotation.Validated;
48
49 import javax.inject.Named;
50 import javax.servlet.http.HttpServletRequest;
51 import javax.ws.rs.core.Response;
52 import java.io.File;
53 import java.io.FileOutputStream;
54 import java.io.IOException;
55 import java.io.InputStream;
56 import java.util.*;
57
58 import static org.openecomp.sdc.action.ActionConstants.*;
59 import static org.openecomp.sdc.action.errors.ActionErrorConstants.*;
60 import static org.openecomp.sdc.action.util.ActionUtil.*;
61
62 /**
63  * Implements various CRUD API that can be performed on Action
64  */
65 @SuppressWarnings("ALL")
66 @Named
67 @Service("actions")
68 @Scope(value = "prototype")
69 @Validated
70 public class ActionsImpl implements Actions {
71
72   private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(ActionsImpl.class);
73   @Autowired
74   private ActionManager actionManager;
75   private String whitespaceCharacters = "\\s"       /* dummy empty string for homogeneity */
76       + "\\u0009" // CHARACTER TABULATION
77       + "\\u000A" // LINE FEED (LF)
78       + "\\u000B" // LINE TABULATION
79       + "\\u000C" // FORM FEED (FF)
80       + "\\u000D" // CARRIAGE RETURN (CR)
81       + "\\u0020" // SPACE
82       + "\\u0085" // NEXT LINE (NEL)
83       + "\\u00A0" // NO-BREAK SPACE
84       + "\\u1680" // OGHAM SPACE MARK
85       + "\\u180E" // MONGOLIAN VOWEL SEPARATOR
86       + "\\u2000" // EN QUAD
87       + "\\u2001" // EM QUAD
88       + "\\u2002" // EN SPACE
89       + "\\u2003" // EM SPACE
90       + "\\u2004" // THREE-PER-EM SPACE
91       + "\\u2005" // FOUR-PER-EM SPACE
92       + "\\u2006" // SIX-PER-EM SPACE
93       + "\\u2007" // FIGURE SPACE
94       + "\\u2008" // PUNCTUATION SPACE
95       + "\\u2009" // THIN SPACE
96       + "\\u200A" // HAIR SPACE
97       + "\\u2028" // LINE SEPARATOR
98       + "\\u2029" // PARAGRAPH SEPARATOR
99       + "\\u202F" // NARROW NO-BREAK SPACE
100       + "\\u205F" // MEDIUM MATHEMATICAL SPACE
101       + "\\u3000" // IDEOGRAPHIC SPACE
102       ;
103   private String invalidFilenameChars = "#<>$+%!`&*'|{}?\"=/:@\\\\";
104   private String whitespaceRegex = ".*[" + whitespaceCharacters + "].*";
105   private String invalidFilenameRegex = ".*[" + whitespaceCharacters + invalidFilenameChars + "].*";
106
107   /**
108    * Calculate the checksum for a given input
109    *
110    * @param input Byte array for which the checksum has to be calculated
111    * @return Calculated checksum of the input byte array
112    */
113   private static String calculateCheckSum(byte[] input) {
114     String checksum = null;
115     if (input != null) {
116       checksum = DigestUtils.md5Hex(input);
117     }
118     return checksum;
119   }
120
121   @Override
122   public Response getActionsByActionInvariantUuId(String invariantID, String actionUUID,
123                                                   HttpServletRequest servletRequest) {
124     ListResponseWrapper responseList = new ListResponseWrapper();
125
126     try {
127       LOGGER.debug(" entering getActionsByActionInvariantUuId ");
128       initializeRequestMDC(servletRequest, invariantID, ActionRequest.GET_ACTIONS_INVARIANT_ID);
129       MDC.put(SERVICE_INSTANCE_ID, invariantID);
130
131       if (StringUtils.isEmpty(servletRequest.getQueryString())) {
132         responseList = getActionsByInvId(servletRequest, invariantID);
133       } else {
134         Response response = getActionByUUID(servletRequest, invariantID, actionUUID);
135         actionLogPostProcessor(StatusCode.COMPLETE, true);
136         return response;
137       }
138     } catch (ActionException exception) {
139       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
140       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
141       LOGGER.error("");
142       throw exception;
143     } catch (Exception exception) {
144       actionLogPostProcessor(StatusCode.ERROR, true);
145       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
146           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
147       LOGGER.error("");
148       throw exception;
149     } finally {
150       finalAuditMetricsLogProcessor(ActionRequest.GET_ACTIONS_INVARIANT_ID.name());
151     }
152
153     LOGGER.debug(" exit getActionsByActionInvariantUuId ");
154     actionLogPostProcessor(StatusCode.COMPLETE, true);
155     return Response.ok(responseList).build();
156   }
157
158   private ListResponseWrapper getActionsByInvId(HttpServletRequest servletRequest,
159                                                 String invariantID) {
160     LOGGER.debug(" entering getActionsByInvId with invariantID= " + invariantID);
161     ListResponseWrapper responseList = new ListResponseWrapper();
162     if (StringUtils.isEmpty(servletRequest.getQueryString())) {
163       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
164       Map<String, String> queryParamErrors = validateQueryParam(invariantID);
165       errorMap.putAll(queryParamErrors);
166       if (errorMap.isEmpty()) {
167         List<Action> actions = actionManager.getActionsByActionInvariantUuId(invariantID);
168         List<ActionResponseDto> versionList = new ArrayList<>();
169         for (Action action : actions) {
170           ActionResponseDto responseDTO = createResponseDTO(action);
171           versionList.add(responseDTO);
172         }
173         responseList.setVersions(versionList);
174         responseList.setActionList(null);
175
176       } else {
177         checkAndThrowError(errorMap);
178       }
179     }
180     LOGGER.debug(" exit getActionsByInvId with invariantID= " + invariantID);
181     return responseList;
182   }
183
184   private Response getActionByUUID(HttpServletRequest servletRequest, String invariantID,
185                                    String actionUUID) throws ActionException {
186     int noOfFilterParams = 0;
187     Response response = null;
188     LOGGER.debug(" entering getActionByUUID with invariantID= " + invariantID + " and actionUUID= " +
189         actionUUID);
190     if (!StringUtils.isEmpty(actionUUID)) {
191       noOfFilterParams++;
192       response = getActionsByUniqueID(actionUUID, servletRequest, invariantID);
193     }
194     if (noOfFilterParams == 0) {
195       throw new ActionException(ACTION_INVALID_SEARCH_CRITERIA,
196           ACTION_REQUEST_FILTER_PARAM_INVALID);
197     }
198
199     LOGGER.debug(" exit getActionByUUID with invariantID= " + invariantID + " and actionUUID= " +
200         actionUUID);
201     return response;
202   }
203
204   @Override
205   public Response getOpenEcompComponents(HttpServletRequest servletRequest) {
206     try {
207       LOGGER.debug(" entering getEcompComponents ");
208       initializeRequestMDC(servletRequest, "", ActionRequest.GET_OPEN_ECOMP_COMPONENTS);
209       //Validate request syntax before passing to the manager
210       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
211       checkAndThrowError(errorMap);
212       ListResponseWrapper response = new ListResponseWrapper();
213       List<OpenEcompComponent> openEcompComponents = actionManager.getOpenEcompComponents();
214       response.setActionList(null);
215       response.setComponentList(openEcompComponents);
216       LOGGER.debug(" exit getEcompComponents ");
217       actionLogPostProcessor(StatusCode.COMPLETE, true);
218       return Response.ok(response).build();
219     } catch (ActionException exception) {
220       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
221       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
222       LOGGER.error("");
223       throw exception;
224     } catch (Exception exception) {
225       actionLogPostProcessor(StatusCode.ERROR, true);
226       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
227           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
228       LOGGER.error("");
229       throw exception;
230     } finally {
231       finalAuditMetricsLogProcessor(ActionRequest.GET_OPEN_ECOMP_COMPONENTS.name());
232     }
233   }
234
235   @Override
236   public Response getFilteredActions(String vendor, String category, String name, String modelID,
237                                      String componentID, HttpServletRequest servletRequest) {
238     try {
239       LOGGER.debug(" entering getFilteredActions ");
240       Response response;
241       initializeRequestMDC(servletRequest, "", ActionRequest.GET_FILTERED_ACTIONS);
242       int noOfFilterParams = getNoOfFilterParams(vendor, category, name, modelID, componentID);
243       if (StringUtils.isEmpty(servletRequest.getQueryString())) {
244         response = getAllActions(servletRequest);
245         LOGGER.debug(" exit getFilteredActions ");
246         actionLogPostProcessor(StatusCode.COMPLETE, true);
247         return response;
248       }
249       validateNoOfFilterParamsExactly1(noOfFilterParams);
250       if (!StringUtils.isEmpty(vendor)) {
251         response = getActionsByVendor(vendor, servletRequest);
252       } else if (!StringUtils.isEmpty(category)) {
253         response = getActionsByCategory(category, servletRequest);
254       } else if (!StringUtils.isEmpty(name)) {
255         response = getActionsByName(name, servletRequest);
256       } else if (!StringUtils.isEmpty(modelID)) {
257         response = getActionsByModel(modelID, servletRequest);
258       } else if (!StringUtils.isEmpty(componentID)) {
259         response = getActionsByOpenEcompComponents(componentID, servletRequest);
260       } else {
261         throw new ActionException(ACTION_INVALID_PARAM_CODE, ACTION_REQUEST_FILTER_PARAM_INVALID);
262       }
263
264       LOGGER.debug(" exit getFilteredActions ");
265       actionLogPostProcessor(StatusCode.COMPLETE, true);
266       return response;
267     } catch (ActionException exception) {
268       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
269       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
270       LOGGER.error("");
271       throw exception;
272     } catch (Exception exception) {
273       actionLogPostProcessor(StatusCode.ERROR, true);
274       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
275           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
276       LOGGER.error("");
277       throw exception;
278     } finally {
279       finalAuditMetricsLogProcessor(ActionRequest.GET_FILTERED_ACTIONS.name());
280     }
281   }
282
283   private void validateNoOfFilterParamsExactly1(int noOfFilterParams) {
284     if (noOfFilterParams > 1) {
285       throw new ActionException(ACTION_MULT_SEARCH_CRITERIA,
286           ACTION_FILTER_MULTIPLE_QUERY_PARAM_NOT_SUPPORTED);
287     }
288     if (noOfFilterParams == 0) {
289       throw new ActionException(ACTION_INVALID_SEARCH_CRITERIA,
290           ACTION_REQUEST_FILTER_PARAM_INVALID);
291     }
292   }
293
294   private int getNoOfFilterParams(String vendor, String category, String name, String modelID, String componentID) {
295     int noOfFilterParams = 0;
296     if (!StringUtils.isEmpty(vendor)) {
297       noOfFilterParams++;
298     }
299     if (!StringUtils.isEmpty(category)) {
300       noOfFilterParams++;
301     }
302     if (!StringUtils.isEmpty(name)) {
303       noOfFilterParams++;
304     }
305     if (!StringUtils.isEmpty(modelID)) {
306       noOfFilterParams++;
307     }
308     if (!StringUtils.isEmpty(componentID)) {
309       noOfFilterParams++;
310     }
311     return noOfFilterParams;
312   }
313
314   @Override
315   public Response createAction(String requestJSON, HttpServletRequest servletRequest) {
316     try {
317       initializeRequestMDC(servletRequest, null, ActionRequest.CREATE_ACTION);
318       LOGGER.debug(" entering API createAction ");
319       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
320       Map<String, String> requestBodyErrors =
321           validateRequestBody(REQUEST_TYPE_CREATE_ACTION, requestJSON);
322       errorMap.putAll(requestBodyErrors);
323       ActionResponseDto actionResponseDTO = new ActionResponseDto();
324       if (errorMap.isEmpty()) {
325         String user = servletRequest.getRemoteUser();
326         Action action = JsonUtil.json2Object(requestJSON, Action.class);
327         action.setData(requestJSON);
328         Action responseAction = actionManager.createAction(action, user);
329         MDC.put(SERVICE_INSTANCE_ID, responseAction.getActionInvariantUuId());
330         new MapActionToActionResponseDto().doMapping(responseAction, actionResponseDTO);
331       } else {
332         checkAndThrowError(errorMap);
333       }
334       actionLogPostProcessor(StatusCode.COMPLETE, true);
335       LOGGER.debug(" exit API createAction with ActionInvariantUUID= " + MDC.get(SERVICE_INSTANCE_ID));
336       return Response.ok(actionResponseDTO).build();
337     } catch (ActionException exception) {
338       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
339       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
340       LOGGER.error("");
341       throw exception;
342     } catch (Exception exception) {
343       actionLogPostProcessor(StatusCode.ERROR, true);
344       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
345           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
346       LOGGER.error(exception.getMessage());
347       throw exception;
348     } finally {
349       finalAuditMetricsLogProcessor(ActionRequest.CREATE_ACTION.name());
350     }
351
352   }
353
354   @Override
355   public Response updateAction(String invariantUUID, String requestJSON,
356                                HttpServletRequest servletRequest) {
357     ActionResponseDto actionResponseDTO = null;
358     try {
359       initializeRequestMDC(servletRequest, invariantUUID, ActionRequest.UPDATE_ACTION);
360       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
361       Map<String, String> requestBodyErrors =
362           validateRequestBody(REQUEST_TYPE_UPDATE_ACTION, requestJSON);
363       errorMap.putAll(requestBodyErrors);
364       actionResponseDTO = new ActionResponseDto();
365       if (errorMap.isEmpty()) {
366         String user = servletRequest.getRemoteUser();
367         Action action = JsonUtil.json2Object(requestJSON, Action.class);
368         action.setActionInvariantUuId(invariantUUID);
369         action.setData(requestJSON);
370         Action updatedAction = actionManager.updateAction(action, user);
371         new MapActionToActionResponseDto().doMapping(updatedAction, actionResponseDTO);
372       } else {
373         checkAndThrowError(errorMap);
374       }
375       actionLogPostProcessor(StatusCode.COMPLETE, true);
376     } catch (ActionException exception) {
377       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
378       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
379       LOGGER.error("");
380       throw exception;
381     } catch (Exception exception) {
382       actionLogPostProcessor(StatusCode.ERROR, true);
383       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
384           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
385       LOGGER.error(exception.getMessage());
386       throw exception;
387     } finally {
388       finalAuditMetricsLogProcessor(ActionRequest.UPDATE_ACTION.name());
389     }
390
391     return Response.ok(actionResponseDTO).build();
392   }
393
394   @Override
395   public Response deleteAction(String actionInvariantUUID, HttpServletRequest servletRequest) {
396     try {
397       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.DELETE_ACTION);
398       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
399       if (errorMap.isEmpty()) {
400         String user = servletRequest.getRemoteUser();
401         actionManager.deleteAction(actionInvariantUUID, user);
402       } else {
403         checkAndThrowError(errorMap);
404       }
405
406       actionLogPostProcessor(StatusCode.COMPLETE, true);
407       return Response.ok(new ActionResponseDto()).build();
408     } catch (ActionException exception) {
409       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
410       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
411       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
412       throw exception;
413     } catch (Exception exception) {
414       actionLogPostProcessor(StatusCode.ERROR, true);
415       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
416           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
417       LOGGER.error(exception.getMessage());
418       throw exception;
419     } finally {
420       finalAuditMetricsLogProcessor(ActionRequest.DELETE_ACTION.name());
421     }
422   }
423
424   @Override
425   public Response actOnAction(String invariantUUID, String requestJSON,
426                               HttpServletRequest servletRequest) {
427     Response response = null;
428     try {
429       initializeRequestMDC(servletRequest, invariantUUID, ActionRequest.ACTION_VERSIONING);
430       LOGGER.debug("entering actOnAction with invariantUUID= " + invariantUUID + " and requestJSON= " +
431           requestJSON);
432       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
433       Map<String, String> requestBodyErrors =
434           validateRequestBody(REQUEST_TYPE_VERSION_ACTION, requestJSON);
435       errorMap.putAll(requestBodyErrors);
436
437       ActionVersionDto versionDTO = JsonUtil.json2Object(requestJSON, ActionVersionDto.class);
438       checkAndThrowError(errorMap);
439
440       String status = versionDTO.getStatus();
441       Action action = new Action();
442       String user = servletRequest.getRemoteUser();
443       switch (status) {
444         case "Checkout":
445           action = actionManager.checkout(invariantUUID, user);
446           break;
447         case "Undo_Checkout":
448           actionManager.undoCheckout(invariantUUID, user);
449           StringWrapperResponse responseText = new StringWrapperResponse();
450           responseText.setValue(ActionConstants.UNDO_CHECKOUT_RESPONSE_TEXT);
451           response = Response
452               .status(Response.Status.OK)
453               .entity(responseText)
454               .build();
455           return response;
456         case "Checkin":
457           action = actionManager.checkin(invariantUUID, user);
458           break;
459         case "Submit":
460           action = actionManager.submit(invariantUUID, user);
461           break;
462         default:
463           throw new ActionException(ACTION_INVALID_PARAM_CODE,
464               String.format(ACTION_UNSUPPORTED_OPERATION, status));
465       }
466
467       ActionResponseDto actionResponseDTO = new ActionResponseDto();
468       new MapActionToActionResponseDto().doMapping(action, actionResponseDTO);
469       response = Response.ok(actionResponseDTO).build();
470       actionLogPostProcessor(StatusCode.COMPLETE, true);
471     } catch (ActionException exception) {
472       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
473       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
474       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
475       throw exception;
476     } catch (Exception exception) {
477       actionLogPostProcessor(StatusCode.ERROR, true);
478       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
479           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
480       LOGGER.error(exception.getMessage());
481       throw exception;
482     } finally {
483       finalAuditMetricsLogProcessor(ActionRequest.ACTION_VERSIONING.name());
484       LOGGER.debug("exit actOnAction with invariantUUID= " + invariantUUID + " and requestJSON= " +
485           requestJSON);
486     }
487     return response;
488   }
489
490   @Override
491   public Response uploadArtifact(String actionInvariantUUID,
492                                  String artifactName,
493                                  String artifactLabel,
494                                  String artifactCategory,
495                                  String artifactDescription,
496                                  String artifactProtection,
497                                  String checksum,
498                                  Attachment artifactToUpload,
499                                  HttpServletRequest servletRequest) {
500     Response response = null;
501     try {
502       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.UPLOAD_ARTIFACT);
503       LOGGER.debug("entering uploadArtifact with actionInvariantUuId= " + actionInvariantUUID +
504           "artifactName= " + artifactName);
505       response =
506           uploadArtifactInternal(actionInvariantUUID, artifactName, artifactLabel, artifactCategory,
507               artifactDescription, artifactProtection, checksum, artifactToUpload, servletRequest);
508       actionLogPostProcessor(StatusCode.COMPLETE, true);
509       LOGGER.debug("exiting uploadArtifact with actionInvariantUuId= " + actionInvariantUUID +
510           "artifactName= " + artifactName);
511     } catch (ActionException exception) {
512       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
513       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
514       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
515       throw exception;
516     } catch (Exception exception) {
517       actionLogPostProcessor(StatusCode.ERROR, true);
518       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
519           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
520       LOGGER.error(exception.getMessage());
521       throw exception;
522     } finally {
523       finalAuditMetricsLogProcessor(ActionRequest.UPLOAD_ARTIFACT.name());
524     }
525     LOGGER.debug("exiting uploadArtifact with actionInvariantUuId= " + actionInvariantUUID +
526         "artifactName= " + artifactName);
527     return response;
528   }
529
530   private Response uploadArtifactInternal(String actionInvariantUUID, String artifactName,
531                                           String artifactLabel, String artifactCategory,
532                                           String artifactDescription, String artifactProtection,
533                                           String checksum, Attachment artifactToUpload,
534                                           HttpServletRequest servletRequest) {
535     ListResponseWrapper responseList = null;
536     byte[] payload = null;
537     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
538     //Artifact name empty validation
539     if (StringUtils.isEmpty(artifactName)) {
540       errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE,
541           ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_NAME);
542     } else {
543       //Artifact name syntax check for whitespaces and invalid characters
544       if (artifactName.matches(invalidFilenameRegex)) {
545         errorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_ARTIFACT_INVALID_NAME);
546       }
547     }
548
549     //Content-Type Header Validation
550     String contentType = servletRequest.getContentType();
551     if (StringUtils.isEmpty(contentType)) {
552       errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID);
553     }
554
555     if (artifactToUpload == null) {
556       throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE,
557           ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_FILE);
558     }
559
560     try (InputStream artifactInputStream = artifactToUpload.getDataHandler().getInputStream()) {
561       payload = FileUtils.toByteArray(artifactInputStream);
562     } catch (IOException exception) {
563       LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception);
564       throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR);
565     }
566
567     //Validate Artifact size
568     if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) {
569       throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR);
570     }
571
572     //Validate Checksum
573     if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) {
574       errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR);
575     }
576
577     //Validate artifact protection values
578     if (StringUtils.isEmpty(artifactProtection)) {
579       artifactProtection = ActionArtifactProtection.readWrite.name();
580     }
581
582     if (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) &&
583         !artifactProtection.equals(ActionArtifactProtection.readWrite.name())) {
584       errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE,
585           ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE);
586     }
587
588     ActionArtifact uploadedArtifact = new ActionArtifact();
589     if (errorMap.isEmpty()) {
590       String user = servletRequest.getRemoteUser();
591       ActionArtifact upload = new ActionArtifact();
592       upload.setArtifactName(artifactName);
593       upload.setArtifactLabel(artifactLabel);
594       upload.setArtifactDescription(artifactDescription);
595       upload.setArtifact(payload);
596       upload.setArtifactCategory(artifactCategory);
597       upload.setArtifactProtection(artifactProtection);
598       uploadedArtifact = actionManager.uploadArtifact(upload, actionInvariantUUID, user);
599     } else {
600       checkAndThrowError(errorMap);
601     }
602     return Response.ok(uploadedArtifact).build();
603   }
604
605   @Override
606   public Response downloadArtifact(String actionUUID, String artifactUUID,
607                                    HttpServletRequest servletRequest) {
608     Response response = null;
609     try {
610       initializeRequestMDC(servletRequest, "", ActionRequest.DOWNLOAD_ARTIFACT);
611       LOGGER.debug(
612           " entering downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " +
613               artifactUUID);
614       response = downloadArtifactInternal(actionUUID, artifactUUID, servletRequest);
615       actionLogPostProcessor(StatusCode.COMPLETE, true);
616     } catch (ActionException exception) {
617       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
618       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
619       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
620       throw exception;
621     } catch (Exception exception) {
622       actionLogPostProcessor(StatusCode.ERROR, true);
623       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
624           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
625       LOGGER.error(exception.getMessage());
626       throw exception;
627     } finally {
628       finalAuditMetricsLogProcessor(ActionRequest.DOWNLOAD_ARTIFACT.name());
629     }
630     LOGGER.debug(" exit downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " +
631         artifactUUID);
632     return response;
633   }
634
635   private Response downloadArtifactInternal(String actionUUID, String artifactUUID,
636                                             HttpServletRequest servletRequest) {
637     Response response;
638     ActionArtifact actionartifact = null;
639     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
640     Map<String, String> queryParamErrors = validateQueryParam(actionUUID);
641     errorMap.putAll(queryParamErrors);
642     queryParamErrors = validateQueryParam(artifactUUID);
643     errorMap.putAll(queryParamErrors);
644     if (errorMap.isEmpty()) {
645       actionartifact = actionManager.downloadArtifact(actionUUID, artifactUUID);
646     } else {
647       checkAndThrowError(errorMap);
648     }
649     response = createArtifactDownloadResponse(actionartifact);
650     return response;
651   }
652
653   @Override
654   public Response deleteArtifact(String actionInvariantUUID, String artifactUUID,
655                                  HttpServletRequest servletRequest) {
656     Response response = null;
657     try {
658       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.DELETE_ARTIFACT);
659       LOGGER.debug(" entering deleteArtifact with actionInvariantUuId= " + actionInvariantUUID +
660           " and artifactUUID= " + artifactUUID);
661       response = deleteArtifactInternal(actionInvariantUUID, artifactUUID, servletRequest);
662       LOGGER.debug(" exit deleteArtifact with actionInvariantUuId= " + actionInvariantUUID +
663           " and artifactUUID= " + artifactUUID);
664       actionLogPostProcessor(StatusCode.COMPLETE, true);
665     } catch (ActionException exception) {
666       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
667       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
668       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
669       throw exception;
670     } catch (Exception exception) {
671       actionLogPostProcessor(StatusCode.ERROR, true);
672       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
673           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
674       LOGGER.error(exception.getMessage());
675       throw exception;
676     } finally {
677       finalAuditMetricsLogProcessor(ActionRequest.DELETE_ARTIFACT.name());
678     }
679     return response;
680   }
681
682   private Response deleteArtifactInternal(String actionInvariantUUID, String artifactUUID,
683                                           HttpServletRequest servletRequest) {
684     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
685     Map<String, String> queryParamErrors = validateQueryParam(actionInvariantUUID);
686     errorMap.putAll(queryParamErrors);
687     queryParamErrors = validateQueryParam(artifactUUID);
688     errorMap.putAll(queryParamErrors);
689     if (errorMap.isEmpty()) {
690       actionManager
691           .deleteArtifact(actionInvariantUUID, artifactUUID, servletRequest.getRemoteUser());
692     } else {
693       checkAndThrowError(errorMap);
694     }
695     return Response.ok().build();
696   }
697
698   @Override
699   public Response updateArtifact(String actionInvariantUUID, String artifactUUID,
700                                  String artifactName, String artifactLabel, String artifactCategory,
701                                  String artifactDescription, String artifactProtection,
702                                  String checksum, Attachment artifactToUpdate,
703                                  HttpServletRequest servletRequest) {
704     Response response = null;
705     LOGGER.debug(" entering updateArtifact with actionInvariantUuId= " + actionInvariantUUID +
706         " and artifactUUID= " + artifactUUID + " and artifactName= " + artifactName +
707         " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory +
708         " and artifactDescription= " + artifactDescription + " and artifactProtection= " +
709         artifactProtection + " and checksum= " + checksum);
710     try {
711       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.UPDATE_ARTIFACT);
712       response =
713           updateArtifactInternal(actionInvariantUUID, artifactUUID, artifactName, artifactLabel,
714               artifactCategory, artifactDescription, artifactProtection, checksum, artifactToUpdate,
715               servletRequest);
716       actionLogPostProcessor(StatusCode.COMPLETE, true);
717     } catch (ActionException exception) {
718       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
719       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
720       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
721       throw exception;
722     } catch (Exception exception) {
723       actionLogPostProcessor(StatusCode.ERROR, true);
724       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
725           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
726       LOGGER.error(exception.getMessage());
727       throw exception;
728     } finally {
729       finalAuditMetricsLogProcessor(ActionRequest.UPDATE_ARTIFACT.name());
730     }
731     LOGGER.debug(" exit updateArtifact with actionInvariantUuId= " + actionInvariantUUID +
732         " and artifactUUID= " + artifactUUID + " and artifactName= " + artifactName +
733         " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory +
734         " and artifactDescription= " + artifactDescription + " and artifactProtection= " +
735         artifactProtection + " and checksum= " + checksum);
736     return response;
737   }
738
739   private void finalAuditMetricsLogProcessor(String targetServiceName) {
740     MDC.put(TARGET_SERVICE_NAME, targetServiceName);
741     MDC.put(TARGET_ENTITY, TARGET_ENTITY_API);
742     LOGGER.metrics("");
743     LOGGER.audit("");
744   }
745
746   private Response updateArtifactInternal(String actionInvariantUUID, String artifactUUID,
747                                           String artifactName, String artifactLabel,
748                                           String artifactCategory, String artifactDescription,
749                                           String artifactProtection, String checksum,
750                                           Attachment artifactToUpdate,
751                                           HttpServletRequest servletRequest) {
752     byte[] payload = null;
753     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
754
755     //Content-Type Header Validation
756     String contentType = servletRequest.getContentType();
757     if (StringUtils.isEmpty(contentType)) {
758       errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID);
759     }
760
761     if (artifactToUpdate != null) {
762
763       try (InputStream artifactInputStream = artifactToUpdate.getDataHandler().getInputStream()) {
764         payload = FileUtils.toByteArray(artifactInputStream);
765       } catch (IOException exception) {
766         LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception);
767         throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR);
768       }
769
770       //Validate Artifact size
771       if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) {
772         throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE,
773             ACTION_ARTIFACT_TOO_BIG_ERROR);
774       }
775
776       //Validate Checksum
777       if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) {
778         errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR);
779       }
780     }
781
782     if (artifactProtection != null && (artifactProtection.isEmpty() ||
783         (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) &&
784             !artifactProtection.equals(ActionArtifactProtection.readWrite.name())))) {
785       errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE,
786           ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE);
787     }
788
789     ActionArtifact updateArtifact = new ActionArtifact();
790     if (errorMap.isEmpty()) {
791       String user = servletRequest.getRemoteUser();
792       ActionArtifact update = new ActionArtifact();
793       update.setArtifactUuId(artifactUUID);
794       update.setArtifactName(artifactName);
795       update.setArtifactLabel(artifactLabel);
796       update.setArtifactDescription(artifactDescription);
797       update.setArtifact(payload);
798       update.setArtifactCategory(artifactCategory);
799       update.setArtifactProtection(artifactProtection);
800       actionManager.updateArtifact(update, actionInvariantUUID, user);
801     } else {
802       checkAndThrowError(errorMap);
803     }
804     return Response.ok().build();
805   }
806
807   /**
808    * Get List of all actions
809    */
810   private Response getAllActions(HttpServletRequest servletRequest) {
811     ListResponseWrapper responseList = null;
812     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
813     if (errorMap.isEmpty()) {
814       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_NONE, null);
815       responseList = createResponse(actions);
816     } else {
817       checkAndThrowError(errorMap);
818     }
819
820     return Response.ok(responseList).build();
821   }
822
823   /**
824    * Get Actions by OPENECOMP component ID
825    */
826   private Response getActionsByOpenEcompComponents(String componentID,
827                                                    HttpServletRequest servletRequest) {
828     ListResponseWrapper responseList = null;
829     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
830     Map<String, String> queryParamErrors = validateQueryParam(componentID);
831     errorMap.putAll(queryParamErrors);
832     if (errorMap.isEmpty()) {
833       List<Action> actions =
834           actionManager.getFilteredActions(FILTER_TYPE_OPEN_ECOMP_COMPONENT, componentID);
835       responseList = createResponse(actions);
836     } else {
837       checkAndThrowError(errorMap);
838     }
839     return Response.ok(responseList).build();
840   }
841
842   /**
843    * Get Actions by Model ID
844    */
845   private Response getActionsByModel(String modelId, HttpServletRequest servletRequest) {
846     ListResponseWrapper responseList = null;
847     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
848     Map<String, String> queryParamErrors = validateQueryParam(modelId);
849     errorMap.putAll(queryParamErrors);
850     if (errorMap.isEmpty()) {
851       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_MODEL, modelId);
852       responseList = createResponse(actions);
853     } else {
854       checkAndThrowError(errorMap);
855     }
856     return Response.ok(responseList).build();
857   }
858
859   /**
860    * Get all actions with given action name
861    */
862   private Response getActionsByName(String name, HttpServletRequest servletRequest) {
863     ListResponseWrapper responseList = null;
864     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
865     Map<String, String> queryParamErrors = validateQueryParam(name);
866     errorMap.putAll(queryParamErrors);
867     if (errorMap.isEmpty()) {
868       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_NAME, name);
869       responseList = createResponse(actions);
870     } else {
871       checkAndThrowError(errorMap);
872     }
873     return Response.ok(responseList).build();
874   }
875
876   /**
877    * Get an action with given ActionUUID
878    */
879   private Response getActionsByUniqueID(String actionUUID, HttpServletRequest servletRequest,
880                                         String actionInvariantUUID) {
881     LOGGER.debug(
882         " entering getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " +
883             actionUUID);
884     Map<String, Object> responseDTO = new LinkedHashMap<>();
885     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
886     Map<String, String> queryParamErrors = validateQueryParam(actionUUID);
887     errorMap.putAll(queryParamErrors);
888     if (errorMap.isEmpty()) {
889       Action action = actionManager.getActionsByActionUuId(actionUUID);
890       if (action.getActionInvariantUuId() != null &&
891           action.getActionInvariantUuId().equalsIgnoreCase(actionInvariantUUID)) {
892         responseDTO = JsonUtil.json2Object(action.getData(), LinkedHashMap.class);
893         responseDTO.put(STATUS, action.getStatus().name());
894         responseDTO.put(TIMESTAMP, getUtcDateStringFromTimestamp(action.getTimestamp()));
895         responseDTO.put(UPDATED_BY, action.getUser());
896       } else {
897         throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST);
898       }
899     } else {
900       checkAndThrowError(errorMap);
901     }
902     LOGGER.debug(
903         " exit getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " +
904             actionUUID);
905     return Response.ok(responseDTO).build();
906   }
907
908   /**
909    * Get all actions with given Vendor Name
910    */
911   private Response getActionsByVendor(String vendor, HttpServletRequest servletRequest) {
912     //Validate request syntax before passing to the manager
913     ListResponseWrapper responseList = null;
914     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
915     Map<String, String> queryParamErrors = validateQueryParam(vendor);
916     errorMap.putAll(queryParamErrors);
917     if (errorMap.isEmpty()) {
918       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_VENDOR, vendor);
919       responseList = createResponse(actions);
920     } else {
921       checkAndThrowError(errorMap);
922     }
923     return Response.ok(responseList).build();
924   }
925
926   /**
927    * Get all actions with given Category Name
928    */
929   private Response getActionsByCategory(String category, HttpServletRequest servletRequest) {
930     //Validate request syntax before passing to the manager
931     ListResponseWrapper responseList = null;
932     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
933     Map<String, String> queryParamErrors = validateQueryParam(category);
934     errorMap.putAll(queryParamErrors);
935     if (errorMap.isEmpty()) {
936       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_CATEGORY, category);
937       responseList = createResponse(actions);
938     } else {
939       checkAndThrowError(errorMap);
940     }
941     return Response.ok(responseList).build();
942   }
943
944   /**
945    * Validates mandatory headers in the request
946    *
947    * @param servletRequest Servlet Request object
948    * @return Map of error codes and description found in the request headers
949    */
950   private Map<String, String> validateRequestHeaders(HttpServletRequest servletRequest) {
951     Map<String, String> errorMap = new LinkedHashMap<>();
952     //Syntactic generic request parameter validations
953     String openEcompRequestId = servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM);
954     if (StringUtils.isEmpty(openEcompRequestId)) {
955       errorMap.put(ACTION_INVALID_REQUEST_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_REQUEST_ID_INVALID);
956     }
957
958     String opemnEcompInstanceId = servletRequest.getHeader(X_OPEN_ECOMP_INSTANCE_ID_HEADER_PARAM);
959     if (StringUtils.isEmpty(opemnEcompInstanceId)) {
960       errorMap.put(ACTION_INVALID_INSTANCE_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_INSTANCE_ID_INVALID);
961     }
962     return errorMap;
963   }
964
965   /**
966    * Validates query parameter in the request
967    *
968    * @param queryParam Query Parameter to be validated
969    * @return Map of error codes and description found in the query parameter
970    */
971   private Map<String, String> validateQueryParam(String queryParam) {
972     Map<String, String> queryParamErrors = new LinkedHashMap<>();
973     if (StringUtils.isEmpty(queryParam)) {
974       queryParamErrors
975           .put(ACTION_INVALID_PARAM_CODE, ACTION_REQUEST_MISSING_MANDATORY_PARAM + queryParam);
976     }
977     return queryParamErrors;
978   }
979
980   /**
981    * Validate request body based on request type
982    *
983    * @param requestJSON Raw request json body as string
984    * @return Map of error codes and description found in the request body
985    */
986   private Map<String, String> validateRequestBody(String requestType, String requestJSON) {
987     Map<String, String> requestBodyErrorMap = new LinkedHashMap<>();
988     if (StringUtils.isEmpty(requestJSON) || requestJSON.equals(REQUEST_EMPTY_BODY)) {
989       requestBodyErrorMap.put(ACTION_INVALID_REQUEST_BODY_CODE, ACTION_REQUEST_BODY_EMPTY);
990     } else {
991       if(requestType == ActionConstants.REQUEST_TYPE_CREATE_ACTION){
992         //placeholder for future implementation
993       }
994       if(requestType == ActionConstants.REQUEST_TYPE_UPDATE_ACTION){
995         //Semantic request specific validations
996         Action action = JsonUtil.json2Object(requestJSON, Action.class);
997         if(StringUtils.isEmpty(action.getName())){
998           setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_PARAM_NAME,
999               requestBodyErrorMap);
1000         } else {
1001           //Added check for action names not allowing whitespaces
1002           if (action.getName().matches(whitespaceRegex)){
1003             requestBodyErrorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_REQUEST_INVALID_NAME);
1004           }
1005         }
1006
1007         if(action.getSupportedModels() != null && !isIDPresentInMap(action.getSupportedModels(),
1008             SUPPORTED_MODELS_VERSION_ID)){
1009           setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE,
1010               ACTION_REQUEST_PARAM_SUPPORTED_MODELS, requestBodyErrorMap);
1011         }
1012         if(action.getSupportedComponents() != null && !isIDPresentInMap(action
1013             .getSupportedComponents(), SUPPORTED_COMPONENTS_ID)){
1014           setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE,
1015               ACTION_REQUEST_PARAM_SUPPORTED_MODELS, requestBodyErrorMap);
1016         }
1017         if(action.getArtifacts() != null){
1018           setErrorValue(ACTION_UPDATE_NOT_ALLOWED_CODE,
1019               ACTION_REQUEST_ARTIFACT_OPERATION_ALLOWED, requestBodyErrorMap);
1020         }
1021       }
1022
1023     }
1024     return requestBodyErrorMap;
1025   }
1026
1027   /**
1028    * Populates Given Error Map with Given Error Code and Error MEssage
1029    */
1030   private void setErrorValue(String key, String message, Map<String, String> errorMap) {
1031     String errorMessage = errorMap.get(key);
1032     if (errorMessage != null) {
1033       message = errorMessage + ", " + message;
1034     } else {
1035       if(key == ACTION_REQUEST_INVALID_GENERIC_CODE)
1036         message = ACTION_REQUEST_MISSING_MANDATORY_PARAM + message;
1037     }
1038     errorMap.put(key, message);
1039   }
1040
1041   /**
1042    * Returns true if given key exists in List of HashMap
1043    */
1044   private boolean isIDPresentInMap(List<HashMap<String, String>> map, String idName) {
1045     if (map != null && !map.isEmpty()) {
1046       for (HashMap<String, String> entry : map) {
1047         if (StringUtils.isEmpty(entry.get(idName))) {
1048           return false;
1049         }
1050       }
1051     }
1052     return true;
1053   }
1054
1055   /**
1056    * @throws ActionException if given ErrorMap is not empty. All error messages at given time are
1057    *                         thrown in one single exception
1058    */
1059   private void checkAndThrowError(Map<String, String> errorMap) {
1060     if (errorMap.size() > 1) {
1061       //Multiple errors detected .. Send the response with a common error code for multiple errors
1062       throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE,
1063           StringUtils.join(errorMap.values(), ", "));
1064     } else if (errorMap.size() == 1) {
1065       String svcPolicyExceptionCode = errorMap.entrySet().iterator().next().getKey();
1066       throw new ActionException(svcPolicyExceptionCode,
1067           errorMap.get(svcPolicyExceptionCode));
1068     }
1069   }
1070
1071   /**
1072    * Populates ActionResponseDto based on given Action
1073    */
1074   private ActionResponseDto createResponseDTO(Action action) {
1075     String data = action.getData();
1076     ActionResponseDto responseDTO = JsonUtil.json2Object(data, ActionResponseDto.class);
1077     responseDTO.setStatus(action.getStatus().name());
1078     responseDTO.setTimestamp(getUtcDateStringFromTimestamp(action.getTimestamp()));
1079     //if(!action.getUser().equals(DELETE_ACTION_USER))
1080     responseDTO.setUpdatedBy(action.getUser());
1081     return responseDTO;
1082   }
1083
1084   /**
1085    * Creates response based on given list of actions
1086    */
1087   private ListResponseWrapper createResponse(List<Action> actions) {
1088     ListResponseWrapper responseList = new ListResponseWrapper();
1089     for (Action action : actions) {
1090       ActionResponseDto responseDTO = createResponseDTO(action);
1091       responseList.add(responseDTO);
1092     }
1093     return responseList;
1094   }
1095
1096
1097   private Response createArtifactDownloadResponse(ActionArtifact actionartifact) {
1098     if (actionartifact != null && actionartifact.getArtifact() != null) {
1099       byte[] artifactsBytes = actionartifact.getArtifact();
1100       File artifactFile = new File(actionartifact.getArtifactName());
1101       try (FileOutputStream fos = new FileOutputStream(artifactFile)) {
1102         fos.write(artifactsBytes);
1103         fos.close();
1104       } catch (IOException exception) {
1105         LOGGER.error(ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG, exception);
1106         throw new ActionException(ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE,
1107             ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
1108       }
1109       Response.ResponseBuilder responseBuilder = Response.ok(artifactFile);
1110       responseBuilder.header("Content-Disposition",
1111           "attachment; filename=" + actionartifact.getArtifactName());
1112       responseBuilder.header("Content-MD5", CalcMD5CheckSum(artifactsBytes));
1113       responseBuilder.header("Content-Length", artifactFile.length());
1114       return responseBuilder.build();
1115     } else {
1116       throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE,
1117           ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST);
1118     }
1119   }
1120
1121   /**
1122    * Initialize MDC for logging the current request
1123    *
1124    * @param actionInvariantId Action Invariant Id if available (null otherwise)
1125    * @param servletRequest    Request Contecxt object
1126    * @param requestType       Current action request (CRUD of Action, Artifact, Version operations)
1127    */
1128   private void initializeRequestMDC(HttpServletRequest servletRequest, String actionInvariantId,
1129                                     ActionRequest requestType) {
1130     MDC.put(REQUEST_ID, servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM));
1131     MDC.put(PARTNER_NAME, servletRequest.getRemoteUser());
1132     MDC.put(INSTANCE_UUID, MDC_ASDC_INSTANCE_UUID);
1133     MDC.put(SERVICE_METRIC_BEGIN_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
1134     MDC.put(STATUS_CODE, StatusCode.COMPLETE.name());
1135     MDC.put(SERVICE_NAME, requestType.name());
1136     MDC.put(CLIENT_IP, MDC.get(REMOTE_HOST));
1137     MDC.put(SERVICE_INSTANCE_ID, actionInvariantId);
1138     MDC.put(LOCAL_ADDR, MDC.get("ServerIPAddress"));
1139     MDC.put(BE_FQDN, MDC.get("ServerFQDN"));
1140
1141     if (LOGGER.isDebugEnabled()) {
1142       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.DEBUG.name());
1143     } else if (LOGGER.isInfoEnabled()) {
1144       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.INFO.name());
1145     } else if (LOGGER.isWarnEnabled()) {
1146       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.WARN.name());
1147     } else if (LOGGER.isErrorEnabled()) {
1148       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.ERROR.name());
1149     }
1150   }
1151
1152   private String CalcMD5CheckSum(byte[] input) {
1153     String checksum = null;
1154     if (input != null) {
1155       checksum = DigestUtils.md5Hex(input).toUpperCase();
1156       System.out.println("checksum : " + checksum);
1157     }
1158     return checksum;
1159   }
1160 }