53ebf0baabf7e6d557f25949a0ad2f0810997d30
[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     InputStream artifactInputStream = null;
561     try {
562       artifactInputStream = artifactToUpload.getDataHandler().getInputStream();
563     } catch (IOException exception) {
564       LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception);
565       throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR);
566     }
567
568     payload = FileUtils.toByteArray(artifactInputStream);
569     //Validate Artifact size
570     if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) {
571       throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR);
572     }
573
574     //Validate Checksum
575     if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) {
576       errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR);
577     }
578
579     //Validate artifact protection values
580     if (StringUtils.isEmpty(artifactProtection)) {
581       artifactProtection = ActionArtifactProtection.readWrite.name();
582     }
583
584     if (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) &&
585         !artifactProtection.equals(ActionArtifactProtection.readWrite.name())) {
586       errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE,
587           ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE);
588     }
589
590     ActionArtifact uploadedArtifact = new ActionArtifact();
591     if (errorMap.isEmpty()) {
592       String user = servletRequest.getRemoteUser();
593       ActionArtifact upload = new ActionArtifact();
594       upload.setArtifactName(artifactName);
595       upload.setArtifactLabel(artifactLabel);
596       upload.setArtifactDescription(artifactDescription);
597       upload.setArtifact(payload);
598       upload.setArtifactCategory(artifactCategory);
599       upload.setArtifactProtection(artifactProtection);
600       uploadedArtifact = actionManager.uploadArtifact(upload, actionInvariantUUID, user);
601     } else {
602       checkAndThrowError(errorMap);
603     }
604     return Response.ok(uploadedArtifact).build();
605   }
606
607   @Override
608   public Response downloadArtifact(String actionUUID, String artifactUUID,
609                                    HttpServletRequest servletRequest) {
610     Response response = null;
611     try {
612       initializeRequestMDC(servletRequest, "", ActionRequest.DOWNLOAD_ARTIFACT);
613       LOGGER.debug(
614           " entering downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " +
615               artifactUUID);
616       response = downloadArtifactInternal(actionUUID, artifactUUID, servletRequest);
617       actionLogPostProcessor(StatusCode.COMPLETE, true);
618     } catch (ActionException exception) {
619       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
620       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
621       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
622       throw exception;
623     } catch (Exception exception) {
624       actionLogPostProcessor(StatusCode.ERROR, true);
625       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
626           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
627       LOGGER.error(exception.getMessage());
628       throw exception;
629     } finally {
630       finalAuditMetricsLogProcessor(ActionRequest.DOWNLOAD_ARTIFACT.name());
631     }
632     LOGGER.debug(" exit downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " +
633         artifactUUID);
634     return response;
635   }
636
637   private Response downloadArtifactInternal(String actionUUID, String artifactUUID,
638                                             HttpServletRequest servletRequest) {
639     Response response;
640     ActionArtifact actionartifact = null;
641     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
642     Map<String, String> queryParamErrors = validateQueryParam(actionUUID);
643     errorMap.putAll(queryParamErrors);
644     queryParamErrors = validateQueryParam(artifactUUID);
645     errorMap.putAll(queryParamErrors);
646     if (errorMap.isEmpty()) {
647       actionartifact = actionManager.downloadArtifact(actionUUID, artifactUUID);
648     } else {
649       checkAndThrowError(errorMap);
650     }
651     response = createArtifactDownloadResponse(actionartifact);
652     return response;
653   }
654
655   @Override
656   public Response deleteArtifact(String actionInvariantUUID, String artifactUUID,
657                                  HttpServletRequest servletRequest) {
658     Response response = null;
659     try {
660       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.DELETE_ARTIFACT);
661       LOGGER.debug(" entering deleteArtifact with actionInvariantUuId= " + actionInvariantUUID +
662           " and artifactUUID= " + artifactUUID);
663       response = deleteArtifactInternal(actionInvariantUUID, artifactUUID, servletRequest);
664       LOGGER.debug(" exit deleteArtifact with actionInvariantUuId= " + actionInvariantUUID +
665           " and artifactUUID= " + artifactUUID);
666       actionLogPostProcessor(StatusCode.COMPLETE, true);
667     } catch (ActionException exception) {
668       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
669       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
670       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
671       throw exception;
672     } catch (Exception exception) {
673       actionLogPostProcessor(StatusCode.ERROR, true);
674       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
675           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
676       LOGGER.error(exception.getMessage());
677       throw exception;
678     } finally {
679       finalAuditMetricsLogProcessor(ActionRequest.DELETE_ARTIFACT.name());
680     }
681     return response;
682   }
683
684   private Response deleteArtifactInternal(String actionInvariantUUID, String artifactUUID,
685                                           HttpServletRequest servletRequest) {
686     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
687     Map<String, String> queryParamErrors = validateQueryParam(actionInvariantUUID);
688     errorMap.putAll(queryParamErrors);
689     queryParamErrors = validateQueryParam(artifactUUID);
690     errorMap.putAll(queryParamErrors);
691     if (errorMap.isEmpty()) {
692       actionManager
693           .deleteArtifact(actionInvariantUUID, artifactUUID, servletRequest.getRemoteUser());
694     } else {
695       checkAndThrowError(errorMap);
696     }
697     return Response.ok().build();
698   }
699
700   @Override
701   public Response updateArtifact(String actionInvariantUUID, String artifactUUID,
702                                  String artifactName, String artifactLabel, String artifactCategory,
703                                  String artifactDescription, String artifactProtection,
704                                  String checksum, Attachment artifactToUpdate,
705                                  HttpServletRequest servletRequest) {
706     Response response = null;
707     LOGGER.debug(" entering updateArtifact with actionInvariantUuId= " + actionInvariantUUID +
708         " and artifactUUID= " + artifactUUID + " and artifactName= " + artifactName +
709         " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory +
710         " and artifactDescription= " + artifactDescription + " and artifactProtection= " +
711         artifactProtection + " and checksum= " + checksum);
712     try {
713       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.UPDATE_ARTIFACT);
714       response =
715           updateArtifactInternal(actionInvariantUUID, artifactUUID, artifactName, artifactLabel,
716               artifactCategory, artifactDescription, artifactProtection, checksum, artifactToUpdate,
717               servletRequest);
718       actionLogPostProcessor(StatusCode.COMPLETE, true);
719     } catch (ActionException exception) {
720       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
721       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
722       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
723       throw exception;
724     } catch (Exception exception) {
725       actionLogPostProcessor(StatusCode.ERROR, true);
726       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
727           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
728       LOGGER.error(exception.getMessage());
729       throw exception;
730     } finally {
731       finalAuditMetricsLogProcessor(ActionRequest.UPDATE_ARTIFACT.name());
732     }
733     LOGGER.debug(" exit updateArtifact with actionInvariantUuId= " + actionInvariantUUID +
734         " and artifactUUID= " + artifactUUID + " and artifactName= " + artifactName +
735         " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory +
736         " and artifactDescription= " + artifactDescription + " and artifactProtection= " +
737         artifactProtection + " and checksum= " + checksum);
738     return response;
739   }
740
741   private void finalAuditMetricsLogProcessor(String targetServiceName) {
742     MDC.put(TARGET_SERVICE_NAME, targetServiceName);
743     MDC.put(TARGET_ENTITY, TARGET_ENTITY_API);
744     LOGGER.metrics("");
745     LOGGER.audit("");
746   }
747
748   private Response updateArtifactInternal(String actionInvariantUUID, String artifactUUID,
749                                           String artifactName, String artifactLabel,
750                                           String artifactCategory, String artifactDescription,
751                                           String artifactProtection, String checksum,
752                                           Attachment artifactToUpdate,
753                                           HttpServletRequest servletRequest) {
754     byte[] payload = null;
755     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
756
757     //Content-Type Header Validation
758     String contentType = servletRequest.getContentType();
759     if (StringUtils.isEmpty(contentType)) {
760       errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID);
761     }
762
763     if (artifactToUpdate != null) {
764       InputStream artifactInputStream = null;
765       try {
766         artifactInputStream = artifactToUpdate.getDataHandler().getInputStream();
767       } catch (IOException exception) {
768         LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception);
769         throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR);
770       }
771
772       payload = FileUtils.toByteArray(artifactInputStream);
773       //Validate Artifact size
774       if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) {
775         throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE,
776             ACTION_ARTIFACT_TOO_BIG_ERROR);
777       }
778
779       //Validate Checksum
780       if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) {
781         errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR);
782       }
783     }
784
785     if (artifactProtection != null && (artifactProtection.isEmpty() ||
786         (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) &&
787             !artifactProtection.equals(ActionArtifactProtection.readWrite.name())))) {
788       errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE,
789           ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE);
790     }
791
792     ActionArtifact updateArtifact = new ActionArtifact();
793     if (errorMap.isEmpty()) {
794       String user = servletRequest.getRemoteUser();
795       ActionArtifact update = new ActionArtifact();
796       update.setArtifactUuId(artifactUUID);
797       update.setArtifactName(artifactName);
798       update.setArtifactLabel(artifactLabel);
799       update.setArtifactDescription(artifactDescription);
800       update.setArtifact(payload);
801       update.setArtifactCategory(artifactCategory);
802       update.setArtifactProtection(artifactProtection);
803       actionManager.updateArtifact(update, actionInvariantUUID, user);
804     } else {
805       checkAndThrowError(errorMap);
806     }
807     return Response.ok().build();
808   }
809
810   /**
811    * Get List of all actions
812    */
813   private Response getAllActions(HttpServletRequest servletRequest) {
814     ListResponseWrapper responseList = null;
815     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
816     if (errorMap.isEmpty()) {
817       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_NONE, null);
818       responseList = createResponse(actions);
819     } else {
820       checkAndThrowError(errorMap);
821     }
822
823     return Response.ok(responseList).build();
824   }
825
826   /**
827    * Get Actions by OPENECOMP component ID
828    */
829   private Response getActionsByOpenEcompComponents(String componentID,
830                                                    HttpServletRequest servletRequest) {
831     ListResponseWrapper responseList = null;
832     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
833     Map<String, String> queryParamErrors = validateQueryParam(componentID);
834     errorMap.putAll(queryParamErrors);
835     if (errorMap.isEmpty()) {
836       List<Action> actions =
837           actionManager.getFilteredActions(FILTER_TYPE_OPEN_ECOMP_COMPONENT, componentID);
838       responseList = createResponse(actions);
839     } else {
840       checkAndThrowError(errorMap);
841     }
842     return Response.ok(responseList).build();
843   }
844
845   /**
846    * Get Actions by Model ID
847    */
848   private Response getActionsByModel(String modelId, HttpServletRequest servletRequest) {
849     ListResponseWrapper responseList = null;
850     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
851     Map<String, String> queryParamErrors = validateQueryParam(modelId);
852     errorMap.putAll(queryParamErrors);
853     if (errorMap.isEmpty()) {
854       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_MODEL, modelId);
855       responseList = createResponse(actions);
856     } else {
857       checkAndThrowError(errorMap);
858     }
859     return Response.ok(responseList).build();
860   }
861
862   /**
863    * Get all actions with given action name
864    */
865   private Response getActionsByName(String name, HttpServletRequest servletRequest) {
866     ListResponseWrapper responseList = null;
867     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
868     Map<String, String> queryParamErrors = validateQueryParam(name);
869     errorMap.putAll(queryParamErrors);
870     if (errorMap.isEmpty()) {
871       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_NAME, name);
872       responseList = createResponse(actions);
873     } else {
874       checkAndThrowError(errorMap);
875     }
876     return Response.ok(responseList).build();
877   }
878
879   /**
880    * Get an action with given ActionUUID
881    */
882   private Response getActionsByUniqueID(String actionUUID, HttpServletRequest servletRequest,
883                                         String actionInvariantUUID) {
884     LOGGER.debug(
885         " entering getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " +
886             actionUUID);
887     Map<String, Object> responseDTO = new LinkedHashMap<>();
888     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
889     Map<String, String> queryParamErrors = validateQueryParam(actionUUID);
890     errorMap.putAll(queryParamErrors);
891     if (errorMap.isEmpty()) {
892       Action action = actionManager.getActionsByActionUuId(actionUUID);
893       if (action.getActionInvariantUuId() != null &&
894           action.getActionInvariantUuId().equalsIgnoreCase(actionInvariantUUID)) {
895         responseDTO = JsonUtil.json2Object(action.getData(), LinkedHashMap.class);
896         responseDTO.put(STATUS, action.getStatus().name());
897         responseDTO.put(TIMESTAMP, getUtcDateStringFromTimestamp(action.getTimestamp()));
898         responseDTO.put(UPDATED_BY, action.getUser());
899       } else {
900         throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST);
901       }
902     } else {
903       checkAndThrowError(errorMap);
904     }
905     LOGGER.debug(
906         " exit getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " +
907             actionUUID);
908     return Response.ok(responseDTO).build();
909   }
910
911   /**
912    * Get all actions with given Vendor Name
913    */
914   private Response getActionsByVendor(String vendor, HttpServletRequest servletRequest) {
915     //Validate request syntax before passing to the manager
916     ListResponseWrapper responseList = null;
917     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
918     Map<String, String> queryParamErrors = validateQueryParam(vendor);
919     errorMap.putAll(queryParamErrors);
920     if (errorMap.isEmpty()) {
921       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_VENDOR, vendor);
922       responseList = createResponse(actions);
923     } else {
924       checkAndThrowError(errorMap);
925     }
926     return Response.ok(responseList).build();
927   }
928
929   /**
930    * Get all actions with given Category Name
931    */
932   private Response getActionsByCategory(String category, HttpServletRequest servletRequest) {
933     //Validate request syntax before passing to the manager
934     ListResponseWrapper responseList = null;
935     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
936     Map<String, String> queryParamErrors = validateQueryParam(category);
937     errorMap.putAll(queryParamErrors);
938     if (errorMap.isEmpty()) {
939       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_CATEGORY, category);
940       responseList = createResponse(actions);
941     } else {
942       checkAndThrowError(errorMap);
943     }
944     return Response.ok(responseList).build();
945   }
946
947   /**
948    * Validates mandatory headers in the request
949    *
950    * @param servletRequest Servlet Request object
951    * @return Map of error codes and description found in the request headers
952    */
953   private Map<String, String> validateRequestHeaders(HttpServletRequest servletRequest) {
954     Map<String, String> errorMap = new LinkedHashMap<>();
955     //Syntactic generic request parameter validations
956     String openEcompRequestId = servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM);
957     if (StringUtils.isEmpty(openEcompRequestId)) {
958       errorMap.put(ACTION_INVALID_REQUEST_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_REQUEST_ID_INVALID);
959     }
960
961     String opemnEcompInstanceId = servletRequest.getHeader(X_OPEN_ECOMP_INSTANCE_ID_HEADER_PARAM);
962     if (StringUtils.isEmpty(opemnEcompInstanceId)) {
963       errorMap.put(ACTION_INVALID_INSTANCE_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_INSTANCE_ID_INVALID);
964     }
965     return errorMap;
966   }
967
968   /**
969    * Validates query parameter in the request
970    *
971    * @param queryParam Query Parameter to be validated
972    * @return Map of error codes and description found in the query parameter
973    */
974   private Map<String, String> validateQueryParam(String queryParam) {
975     Map<String, String> queryParamErrors = new LinkedHashMap<>();
976     if (StringUtils.isEmpty(queryParam)) {
977       queryParamErrors
978           .put(ACTION_INVALID_PARAM_CODE, ACTION_REQUEST_MISSING_MANDATORY_PARAM + queryParam);
979     }
980     return queryParamErrors;
981   }
982
983   /**
984    * Validate request body based on request type
985    *
986    * @param requestJSON Raw request json body as string
987    * @return Map of error codes and description found in the request body
988    */
989   private Map<String, String> validateRequestBody(String requestType, String requestJSON) {
990     Map<String, String> requestBodyErrorMap = new LinkedHashMap<>();
991     if (StringUtils.isEmpty(requestJSON) || requestJSON.equals(REQUEST_EMPTY_BODY)) {
992       requestBodyErrorMap.put(ACTION_INVALID_REQUEST_BODY_CODE, ACTION_REQUEST_BODY_EMPTY);
993     } else {
994       if(requestType == ActionConstants.REQUEST_TYPE_CREATE_ACTION){
995         //placeholder for future implementation
996       }
997       if(requestType == ActionConstants.REQUEST_TYPE_UPDATE_ACTION){
998         //Semantic request specific validations
999         Action action = JsonUtil.json2Object(requestJSON, Action.class);
1000         if(StringUtils.isEmpty(action.getName())){
1001           setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_PARAM_NAME,
1002               requestBodyErrorMap);
1003         } else {
1004           //Added check for action names not allowing whitespaces
1005           if (action.getName().matches(whitespaceRegex)){
1006             requestBodyErrorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_REQUEST_INVALID_NAME);
1007           }
1008         }
1009
1010         if(action.getSupportedModels() != null && !isIDPresentInMap(action.getSupportedModels(),
1011             SUPPORTED_MODELS_VERSION_ID)){
1012           setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE,
1013               ACTION_REQUEST_PARAM_SUPPORTED_MODELS, requestBodyErrorMap);
1014         }
1015         if(action.getSupportedComponents() != null && !isIDPresentInMap(action
1016             .getSupportedComponents(), SUPPORTED_COMPONENTS_ID)){
1017           setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE,
1018               ACTION_REQUEST_PARAM_SUPPORTED_MODELS, requestBodyErrorMap);
1019         }
1020         if(action.getArtifacts() != null){
1021           setErrorValue(ACTION_UPDATE_NOT_ALLOWED_CODE,
1022               ACTION_REQUEST_ARTIFACT_OPERATION_ALLOWED, requestBodyErrorMap);
1023         }
1024       }
1025
1026     }
1027     return requestBodyErrorMap;
1028   }
1029
1030   /**
1031    * Populates Given Error Map with Given Error Code and Error MEssage
1032    */
1033   private void setErrorValue(String key, String message, Map<String, String> errorMap) {
1034     String errorMessage = errorMap.get(key);
1035     if (errorMessage != null) {
1036       message = errorMessage + ", " + message;
1037     } else {
1038       if(key == ACTION_REQUEST_INVALID_GENERIC_CODE)
1039         message = ACTION_REQUEST_MISSING_MANDATORY_PARAM + message;
1040     }
1041     errorMap.put(key, message);
1042   }
1043
1044   /**
1045    * Returns true if given key exists in List of HashMap
1046    */
1047   private boolean isIDPresentInMap(List<HashMap<String, String>> map, String idName) {
1048     if (map != null && !map.isEmpty()) {
1049       for (HashMap<String, String> entry : map) {
1050         if (StringUtils.isEmpty(entry.get(idName))) {
1051           return false;
1052         }
1053       }
1054     }
1055     return true;
1056   }
1057
1058   /**
1059    * @throws ActionException if given ErrorMap is not empty. All error messages at given time are
1060    *                         thrown in one single exception
1061    */
1062   private void checkAndThrowError(Map<String, String> errorMap) {
1063     if (errorMap.size() > 1) {
1064       //Multiple errors detected .. Send the response with a common error code for multiple errors
1065       throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE,
1066           StringUtils.join(errorMap.values(), ", "));
1067     } else if (errorMap.size() == 1) {
1068       String svcPolicyExceptionCode = errorMap.entrySet().iterator().next().getKey();
1069       throw new ActionException(svcPolicyExceptionCode,
1070           errorMap.get(svcPolicyExceptionCode));
1071     }
1072   }
1073
1074   /**
1075    * Populates ActionResponseDto based on given Action
1076    */
1077   private ActionResponseDto createResponseDTO(Action action) {
1078     String data = action.getData();
1079     ActionResponseDto responseDTO = JsonUtil.json2Object(data, ActionResponseDto.class);
1080     responseDTO.setStatus(action.getStatus().name());
1081     responseDTO.setTimestamp(getUtcDateStringFromTimestamp(action.getTimestamp()));
1082     //if(!action.getUser().equals(DELETE_ACTION_USER))
1083     responseDTO.setUpdatedBy(action.getUser());
1084     return responseDTO;
1085   }
1086
1087   /**
1088    * Creates response based on given list of actions
1089    */
1090   private ListResponseWrapper createResponse(List<Action> actions) {
1091     ListResponseWrapper responseList = new ListResponseWrapper();
1092     for (Action action : actions) {
1093       ActionResponseDto responseDTO = createResponseDTO(action);
1094       responseList.add(responseDTO);
1095     }
1096     return responseList;
1097   }
1098
1099
1100   private Response createArtifactDownloadResponse(ActionArtifact actionartifact) {
1101     if (actionartifact != null && actionartifact.getArtifact() != null) {
1102       byte[] artifactsBytes = actionartifact.getArtifact();
1103       File artifactFile = new File(actionartifact.getArtifactName());
1104       try (FileOutputStream fos = new FileOutputStream(artifactFile)) {
1105         fos.write(artifactsBytes);
1106         fos.close();
1107       } catch (IOException exception) {
1108         LOGGER.error(ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG, exception);
1109         throw new ActionException(ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE,
1110             ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
1111       }
1112       Response.ResponseBuilder responseBuilder = Response.ok(artifactFile);
1113       responseBuilder.header("Content-Disposition",
1114           "attachment; filename=" + actionartifact.getArtifactName());
1115       responseBuilder.header("Content-MD5", CalcMD5CheckSum(artifactsBytes));
1116       responseBuilder.header("Content-Length", artifactFile.length());
1117       return responseBuilder.build();
1118     } else {
1119       throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE,
1120           ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST);
1121     }
1122   }
1123
1124   /**
1125    * Initialize MDC for logging the current request
1126    *
1127    * @param actionInvariantId Action Invariant Id if available (null otherwise)
1128    * @param servletRequest    Request Contecxt object
1129    * @param requestType       Current action request (CRUD of Action, Artifact, Version operations)
1130    */
1131   private void initializeRequestMDC(HttpServletRequest servletRequest, String actionInvariantId,
1132                                     ActionRequest requestType) {
1133     MDC.put(REQUEST_ID, servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM));
1134     MDC.put(PARTNER_NAME, servletRequest.getRemoteUser());
1135     MDC.put(INSTANCE_UUID, MDC_ASDC_INSTANCE_UUID);
1136     MDC.put(SERVICE_METRIC_BEGIN_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
1137     MDC.put(STATUS_CODE, StatusCode.COMPLETE.name());
1138     MDC.put(SERVICE_NAME, requestType.name());
1139     MDC.put(CLIENT_IP, MDC.get(REMOTE_HOST));
1140     MDC.put(SERVICE_INSTANCE_ID, actionInvariantId);
1141     MDC.put(LOCAL_ADDR, MDC.get("ServerIPAddress"));
1142     MDC.put(BE_FQDN, MDC.get("ServerFQDN"));
1143
1144     if (LOGGER.isDebugEnabled()) {
1145       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.DEBUG.name());
1146     } else if (LOGGER.isInfoEnabled()) {
1147       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.INFO.name());
1148     } else if (LOGGER.isWarnEnabled()) {
1149       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.WARN.name());
1150     } else if (LOGGER.isErrorEnabled()) {
1151       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.ERROR.name());
1152     }
1153   }
1154
1155   private String CalcMD5CheckSum(byte[] input) {
1156     String checksum = null;
1157     if (input != null) {
1158       checksum = DigestUtils.md5Hex(input).toUpperCase();
1159       System.out.println("checksum : " + checksum);
1160     }
1161     return checksum;
1162   }
1163 }