re base code
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / action-library-rest / action-library-rest-services / src / main / java / org / openecomp / sdcrests / action / rest / services / ActionsImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.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 = 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     }
150
151     LOGGER.debug(" exit getActionsByActionInvariantUuId ");
152     actionLogPostProcessor(StatusCode.COMPLETE, true);
153     return Response.ok(responseList).build();
154   }
155
156   private ListResponseWrapper getActionsByInvId(HttpServletRequest servletRequest,
157                                                 String invariantID) {
158     LOGGER.debug(" entering getActionsByInvId with invariantID= " + invariantID);
159     ListResponseWrapper responseList = new ListResponseWrapper();
160     if (StringUtils.isEmpty(servletRequest.getQueryString())) {
161       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
162       Map<String, String> queryParamErrors = validateQueryParam(invariantID);
163       errorMap.putAll(queryParamErrors);
164       if (errorMap.isEmpty()) {
165         List<Action> actions = actionManager.getActionsByActionInvariantUuId(invariantID);
166         List<ActionResponseDto> versionList = new ArrayList<>();
167         for (Action action : actions) {
168           ActionResponseDto responseDTO = createResponseDTO(action);
169           versionList.add(responseDTO);
170         }
171         responseList.setVersions(versionList);
172         responseList.setActionList(null);
173
174       } else {
175         checkAndThrowError(errorMap);
176       }
177     }
178     LOGGER.debug(" exit getActionsByInvId with invariantID= " + invariantID);
179     return responseList;
180   }
181
182   private Response getActionByUUID(HttpServletRequest servletRequest, String invariantID,
183                                    String actionUUID) throws ActionException {
184     int noOfFilterParams = 0;
185     Response response = null;
186     LOGGER.debug(" entering getActionByUUID with invariantID= " + invariantID + " and actionUUID= " +
187         actionUUID);
188     if (!StringUtils.isEmpty(actionUUID)) {
189       noOfFilterParams++;
190       response = getActionsByUniqueID(actionUUID, servletRequest, invariantID);
191     }
192     if (noOfFilterParams == 0) {
193       throw new ActionException(ACTION_INVALID_SEARCH_CRITERIA,
194           ACTION_REQUEST_FILTER_PARAM_INVALID);
195     }
196
197     LOGGER.debug(" exit getActionByUUID with invariantID= " + invariantID + " and actionUUID= " +
198         actionUUID);
199     return response;
200   }
201
202   @Override
203   public Response getOpenEcompComponents(HttpServletRequest servletRequest) {
204     try {
205       LOGGER.debug(" entering getEcompComponents ");
206       initializeRequestMDC(servletRequest, "", ActionRequest.GET_OPEN_ECOMP_COMPONENTS);
207       //Validate request syntax before passing to the manager
208       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
209       checkAndThrowError(errorMap);
210       ListResponseWrapper response = new ListResponseWrapper();
211       List<OpenEcompComponent> openEcompComponents = actionManager.getOpenEcompComponents();
212       response.setActionList(null);
213       response.setComponentList(openEcompComponents);
214       LOGGER.debug(" exit getEcompComponents ");
215       actionLogPostProcessor(StatusCode.COMPLETE, true);
216       return Response.ok(response).build();
217     } catch (ActionException exception) {
218       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
219       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
220       LOGGER.error("");
221       throw exception;
222     } catch (Exception exception) {
223       actionLogPostProcessor(StatusCode.ERROR, true);
224       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
225           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
226       LOGGER.error("");
227       throw exception;
228     }
229   }
230
231   @Override
232   public Response getFilteredActions(String vendor, String category, String name, String modelID,
233                                      String componentID, HttpServletRequest servletRequest) {
234     try {
235       LOGGER.debug(" entering getFilteredActions ");
236       Response response;
237       initializeRequestMDC(servletRequest, "", ActionRequest.GET_FILTERED_ACTIONS);
238       int noOfFilterParams = getNoOfFilterParams(vendor, category, name, modelID, componentID);
239       if (StringUtils.isEmpty(servletRequest.getQueryString())) {
240         response = getAllActions(servletRequest);
241         LOGGER.debug(" exit getFilteredActions ");
242         actionLogPostProcessor(StatusCode.COMPLETE, true);
243         return response;
244       }
245       validateNoOfFilterParamsExactly1(noOfFilterParams);
246       if (!StringUtils.isEmpty(vendor)) {
247         response = getActionsByVendor(vendor, servletRequest);
248       } else if (!StringUtils.isEmpty(category)) {
249         response = getActionsByCategory(category, servletRequest);
250       } else if (!StringUtils.isEmpty(name)) {
251         response = getActionsByName(name, servletRequest);
252       } else if (!StringUtils.isEmpty(modelID)) {
253         response = getActionsByModel(modelID, servletRequest);
254       } else if (!StringUtils.isEmpty(componentID)) {
255         response = getActionsByOpenEcompComponents(componentID, servletRequest);
256       } else {
257         throw new ActionException(ACTION_INVALID_PARAM_CODE, ACTION_REQUEST_FILTER_PARAM_INVALID);
258       }
259
260       LOGGER.debug(" exit getFilteredActions ");
261       actionLogPostProcessor(StatusCode.COMPLETE, true);
262       return response;
263     } catch (ActionException exception) {
264       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
265       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
266       LOGGER.error("");
267       throw exception;
268     } catch (Exception exception) {
269       actionLogPostProcessor(StatusCode.ERROR, true);
270       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
271           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
272       LOGGER.error("");
273       throw exception;
274     }
275   }
276
277   private void validateNoOfFilterParamsExactly1(int noOfFilterParams) {
278     if (noOfFilterParams > 1) {
279       throw new ActionException(ACTION_MULT_SEARCH_CRITERIA,
280           ACTION_FILTER_MULTIPLE_QUERY_PARAM_NOT_SUPPORTED);
281     }
282     if (noOfFilterParams == 0) {
283       throw new ActionException(ACTION_INVALID_SEARCH_CRITERIA,
284           ACTION_REQUEST_FILTER_PARAM_INVALID);
285     }
286   }
287
288   private int getNoOfFilterParams(String vendor, String category, String name, String modelID, String componentID) {
289     int noOfFilterParams = 0;
290     if (!StringUtils.isEmpty(vendor)) {
291       noOfFilterParams++;
292     }
293     if (!StringUtils.isEmpty(category)) {
294       noOfFilterParams++;
295     }
296     if (!StringUtils.isEmpty(name)) {
297       noOfFilterParams++;
298     }
299     if (!StringUtils.isEmpty(modelID)) {
300       noOfFilterParams++;
301     }
302     if (!StringUtils.isEmpty(componentID)) {
303       noOfFilterParams++;
304     }
305     return noOfFilterParams;
306   }
307
308   @Override
309   public Response createAction(String requestJSON, HttpServletRequest servletRequest) {
310     try {
311       initializeRequestMDC(servletRequest, null, ActionRequest.CREATE_ACTION);
312       LOGGER.debug(" entering API createAction ");
313       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
314       Map<String, String> requestBodyErrors =
315           validateRequestBody(REQUEST_TYPE_CREATE_ACTION, requestJSON);
316       errorMap.putAll(requestBodyErrors);
317       ActionResponseDto actionResponseDTO = new ActionResponseDto();
318       if (errorMap.isEmpty()) {
319         String user = servletRequest.getRemoteUser();
320         Action action = JsonUtil.json2Object(requestJSON, Action.class);
321         action.setData(requestJSON);
322         Action responseAction = actionManager.createAction(action, user);
323         MDC.put(SERVICE_INSTANCE_ID, responseAction.getActionInvariantUuId());
324         new MapActionToActionResponseDto().doMapping(responseAction, actionResponseDTO);
325       } else {
326         checkAndThrowError(errorMap);
327       }
328       actionLogPostProcessor(StatusCode.COMPLETE, true);
329       LOGGER.debug(" exit API createAction with ActionInvariantUUID= " + MDC.get(SERVICE_INSTANCE_ID));
330       return Response.ok(actionResponseDTO).build();
331     } catch (ActionException exception) {
332       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
333       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
334       LOGGER.error("");
335       throw exception;
336     } catch (Exception exception) {
337       actionLogPostProcessor(StatusCode.ERROR, true);
338       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
339           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
340       LOGGER.error(exception.getMessage());
341       throw exception;
342     }
343
344   }
345
346   @Override
347   public Response updateAction(String invariantUUID, String requestJSON,
348                                HttpServletRequest servletRequest) {
349     ActionResponseDto actionResponseDTO = null;
350     try {
351       initializeRequestMDC(servletRequest, invariantUUID, ActionRequest.UPDATE_ACTION);
352       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
353       Map<String, String> requestBodyErrors =
354           validateRequestBody(REQUEST_TYPE_UPDATE_ACTION, requestJSON);
355       errorMap.putAll(requestBodyErrors);
356       actionResponseDTO = new ActionResponseDto();
357       if (errorMap.isEmpty()) {
358         String user = servletRequest.getRemoteUser();
359         Action action = JsonUtil.json2Object(requestJSON, Action.class);
360         action.setActionInvariantUuId(invariantUUID);
361         action.setData(requestJSON);
362         Action updatedAction = actionManager.updateAction(action, user);
363         new MapActionToActionResponseDto().doMapping(updatedAction, actionResponseDTO);
364       } else {
365         checkAndThrowError(errorMap);
366       }
367       actionLogPostProcessor(StatusCode.COMPLETE, true);
368     } catch (ActionException exception) {
369       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
370       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
371       LOGGER.error("");
372       throw exception;
373     } catch (Exception exception) {
374       actionLogPostProcessor(StatusCode.ERROR, true);
375       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
376           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
377       LOGGER.error(exception.getMessage());
378       throw exception;
379     }
380
381     return Response.ok(actionResponseDTO).build();
382   }
383
384   @Override
385   public Response deleteAction(String actionInvariantUUID, HttpServletRequest servletRequest) {
386     try {
387       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.DELETE_ACTION);
388       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
389       if (errorMap.isEmpty()) {
390         String user = servletRequest.getRemoteUser();
391         actionManager.deleteAction(actionInvariantUUID, user);
392       } else {
393         checkAndThrowError(errorMap);
394       }
395
396       actionLogPostProcessor(StatusCode.COMPLETE, true);
397       return Response.ok(new ActionResponseDto()).build();
398     } catch (ActionException exception) {
399       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
400       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
401       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
402       throw exception;
403     } catch (Exception exception) {
404       actionLogPostProcessor(StatusCode.ERROR, true);
405       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
406           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
407       LOGGER.error(exception.getMessage());
408       throw exception;
409     }
410   }
411
412   @Override
413   public Response actOnAction(String invariantUUID, String requestJSON,
414                               HttpServletRequest servletRequest) {
415     Response response = null;
416     try {
417       initializeRequestMDC(servletRequest, invariantUUID, ActionRequest.ACTION_VERSIONING);
418       LOGGER.debug("entering actOnAction with invariantUUID= " + invariantUUID + " and requestJSON= " +
419           requestJSON);
420       Map<String, String> errorMap = validateRequestHeaders(servletRequest);
421       Map<String, String> requestBodyErrors =
422           validateRequestBody(REQUEST_TYPE_VERSION_ACTION, requestJSON);
423       errorMap.putAll(requestBodyErrors);
424
425       ActionVersionDto versionDTO = JsonUtil.json2Object(requestJSON, ActionVersionDto.class);
426       checkAndThrowError(errorMap);
427
428       String status = versionDTO.getStatus();
429       Action action = new Action();
430       String user = servletRequest.getRemoteUser();
431       switch (status) {
432         case "Checkout":
433           action = actionManager.checkout(invariantUUID, user);
434           break;
435         case "Undo_Checkout":
436           actionManager.undoCheckout(invariantUUID, user);
437           StringWrapperResponse responseText = new StringWrapperResponse();
438           responseText.setValue(ActionConstants.UNDO_CHECKOUT_RESPONSE_TEXT);
439           response = Response
440               .status(Response.Status.OK)
441               .entity(responseText)
442               .build();
443           return response;
444         case "Checkin":
445           action = actionManager.checkin(invariantUUID, user);
446           break;
447         case "Submit":
448           action = actionManager.submit(invariantUUID, user);
449           break;
450         default:
451           throw new ActionException(ACTION_INVALID_PARAM_CODE,
452               String.format(ACTION_UNSUPPORTED_OPERATION, status));
453       }
454
455       ActionResponseDto actionResponseDTO = new ActionResponseDto();
456       new MapActionToActionResponseDto().doMapping(action, actionResponseDTO);
457       response = Response.ok(actionResponseDTO).build();
458       actionLogPostProcessor(StatusCode.COMPLETE, true);
459     } catch (ActionException exception) {
460       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
461       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
462       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
463       throw exception;
464     } catch (Exception exception) {
465       actionLogPostProcessor(StatusCode.ERROR, true);
466       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
467           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
468       LOGGER.error(exception.getMessage());
469       throw exception;
470     } finally {
471       LOGGER.debug("exit actOnAction with invariantUUID= " + invariantUUID + " and requestJSON= " +
472           requestJSON);
473     }
474     return response;
475   }
476
477   @Override
478   public Response uploadArtifact(String actionInvariantUUID,
479                                  String artifactName,
480                                  String artifactLabel,
481                                  String artifactCategory,
482                                  String artifactDescription,
483                                  String artifactProtection,
484                                  String checksum,
485                                  Attachment artifactToUpload,
486                                  HttpServletRequest servletRequest) {
487     Response response = null;
488     try {
489       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.UPLOAD_ARTIFACT);
490       LOGGER.debug("entering uploadArtifact with actionInvariantUuId= " + actionInvariantUUID +
491           "artifactName= " + artifactName);
492       response =
493           uploadArtifactInternal(actionInvariantUUID, artifactName, artifactLabel, artifactCategory,
494               artifactDescription, artifactProtection, checksum, artifactToUpload, servletRequest);
495       actionLogPostProcessor(StatusCode.COMPLETE, true);
496       LOGGER.debug("exiting uploadArtifact with actionInvariantUuId= " + actionInvariantUUID +
497           "artifactName= " + artifactName);
498     } catch (ActionException exception) {
499       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
500       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
501       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
502       throw exception;
503     } catch (Exception exception) {
504       actionLogPostProcessor(StatusCode.ERROR, true);
505       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
506           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
507       LOGGER.error(exception.getMessage());
508       throw exception;
509     }
510
511     LOGGER.debug("exiting uploadArtifact with actionInvariantUuId= " + actionInvariantUUID +
512         "artifactName= " + artifactName);
513     return response;
514   }
515
516   private Response uploadArtifactInternal(String actionInvariantUUID, String artifactName,
517                                           String artifactLabel, String artifactCategory,
518                                           String artifactDescription, String artifactProtection,
519                                           String checksum, Attachment artifactToUpload,
520                                           HttpServletRequest servletRequest) {
521     byte[] payload = null;
522     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
523     //Artifact name empty validation
524     if (StringUtils.isEmpty(artifactName)) {
525       errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE,
526           ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_NAME);
527     } else {
528       //Artifact name syntax check for whitespaces and invalid characters
529       if (artifactName.matches(invalidFilenameRegex)) {
530         errorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_ARTIFACT_INVALID_NAME);
531       }
532     }
533
534     //Content-Type Header Validation
535     String contentType = servletRequest.getContentType();
536     if (StringUtils.isEmpty(contentType)) {
537       errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID);
538     }
539
540     if (artifactToUpload == null) {
541       throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE,
542           ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_FILE);
543     }
544
545     try (InputStream artifactInputStream = artifactToUpload.getDataHandler().getInputStream()) {
546       payload = FileUtils.toByteArray(artifactInputStream);
547     } catch (IOException exception) {
548       LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception);
549       throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR);
550     }
551
552     //Validate Artifact size
553     if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) {
554       throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR);
555     }
556
557     //Validate Checksum
558     if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) {
559       errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR);
560     }
561
562     //Validate artifact protection values
563     if (StringUtils.isEmpty(artifactProtection)) {
564       artifactProtection = ActionArtifactProtection.readWrite.name();
565     }
566
567     if (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) &&
568         !artifactProtection.equals(ActionArtifactProtection.readWrite.name())) {
569       errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE,
570           ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE);
571     }
572
573     ActionArtifact uploadedArtifact = new ActionArtifact();
574     if (errorMap.isEmpty()) {
575       String user = servletRequest.getRemoteUser();
576       ActionArtifact upload = new ActionArtifact();
577       upload.setArtifactName(artifactName);
578       upload.setArtifactLabel(artifactLabel);
579       upload.setArtifactDescription(artifactDescription);
580       upload.setArtifact(payload);
581       upload.setArtifactCategory(artifactCategory);
582       upload.setArtifactProtection(artifactProtection);
583       uploadedArtifact = actionManager.uploadArtifact(upload, actionInvariantUUID, user);
584     } else {
585       checkAndThrowError(errorMap);
586     }
587     return Response.ok(uploadedArtifact).build();
588   }
589
590   @Override
591   public Response downloadArtifact(String actionUUID, String artifactUUID,
592                                    HttpServletRequest servletRequest) {
593     Response response = null;
594     try {
595       initializeRequestMDC(servletRequest, "", ActionRequest.DOWNLOAD_ARTIFACT);
596       LOGGER.debug(
597           " entering downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " +
598               artifactUUID);
599       response = downloadArtifactInternal(actionUUID, artifactUUID, servletRequest);
600       actionLogPostProcessor(StatusCode.COMPLETE, true);
601     } catch (ActionException exception) {
602       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
603       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
604       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
605       throw exception;
606     } catch (Exception exception) {
607       actionLogPostProcessor(StatusCode.ERROR, true);
608       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
609           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
610       LOGGER.error(exception.getMessage());
611       throw exception;
612     }
613
614     LOGGER.debug(" exit downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " +
615         artifactUUID);
616     return response;
617   }
618
619   private Response downloadArtifactInternal(String actionUUID, String artifactUUID,
620                                             HttpServletRequest servletRequest) {
621     Response response;
622     ActionArtifact actionartifact = null;
623     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
624     Map<String, String> queryParamErrors = validateQueryParam(actionUUID);
625     errorMap.putAll(queryParamErrors);
626     queryParamErrors = validateQueryParam(artifactUUID);
627     errorMap.putAll(queryParamErrors);
628     if (errorMap.isEmpty()) {
629       actionartifact = actionManager.downloadArtifact(actionUUID, artifactUUID);
630     } else {
631       checkAndThrowError(errorMap);
632     }
633     response = createArtifactDownloadResponse(actionartifact);
634     return response;
635   }
636
637   @Override
638   public Response deleteArtifact(String actionInvariantUUID, String artifactUUID,
639                                  HttpServletRequest servletRequest) {
640     Response response = null;
641     try {
642       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.DELETE_ARTIFACT);
643       LOGGER.debug(" entering deleteArtifact with actionInvariantUuId= " + actionInvariantUUID +
644           " and artifactUUID= " + artifactUUID);
645       response = deleteArtifactInternal(actionInvariantUUID, artifactUUID, servletRequest);
646       LOGGER.debug(" exit deleteArtifact with actionInvariantUuId= " + actionInvariantUUID +
647           " and artifactUUID= " + artifactUUID);
648       actionLogPostProcessor(StatusCode.COMPLETE, true);
649     } catch (ActionException exception) {
650       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
651       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
652       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
653       throw exception;
654     } catch (Exception exception) {
655       actionLogPostProcessor(StatusCode.ERROR, true);
656       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
657           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
658       LOGGER.error(exception.getMessage());
659       throw exception;
660     }
661
662     return response;
663   }
664
665   private Response deleteArtifactInternal(String actionInvariantUUID, String artifactUUID,
666                                           HttpServletRequest servletRequest) {
667     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
668     Map<String, String> queryParamErrors = validateQueryParam(actionInvariantUUID);
669     errorMap.putAll(queryParamErrors);
670     queryParamErrors = validateQueryParam(artifactUUID);
671     errorMap.putAll(queryParamErrors);
672     if (errorMap.isEmpty()) {
673       actionManager
674           .deleteArtifact(actionInvariantUUID, artifactUUID, servletRequest.getRemoteUser());
675     } else {
676       checkAndThrowError(errorMap);
677     }
678     return Response.ok().build();
679   }
680
681   @Override
682   public Response updateArtifact(String actionInvariantUUID, String artifactUUID,
683                                  String artifactName, String artifactLabel, String artifactCategory,
684                                  String artifactDescription, String artifactProtection,
685                                  String checksum, Attachment artifactToUpdate,
686                                  HttpServletRequest servletRequest) {
687     Response response = null;
688     LOGGER.debug(" entering updateArtifact with actionInvariantUuId= " + actionInvariantUUID +
689         " and artifactUUID= " + artifactUUID + " and artifactName= " + artifactName +
690         " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory +
691         " and artifactDescription= " + artifactDescription + " and artifactProtection= " +
692         artifactProtection + " and checksum= " + checksum);
693     try {
694       initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.UPDATE_ARTIFACT);
695       response =
696           updateArtifactInternal(actionInvariantUUID, artifactUUID, artifactName, artifactLabel,
697               artifactCategory, artifactDescription, artifactProtection, checksum, artifactToUpdate,
698               servletRequest);
699       actionLogPostProcessor(StatusCode.COMPLETE, true);
700     } catch (ActionException exception) {
701       actionLogPostProcessor(StatusCode.ERROR, exception.getErrorCode(), exception.getDescription(), true);
702       actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription());
703       LOGGER.error(MDC.get(ERROR_DESCRIPTION));
704       throw exception;
705     } catch (Exception exception) {
706       actionLogPostProcessor(StatusCode.ERROR, true);
707       actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE,
708           ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
709       LOGGER.error(exception.getMessage());
710       throw exception;
711     }
712
713     LOGGER.debug(" exit updateArtifact with actionInvariantUuId= " + actionInvariantUUID +
714         " and artifactUUID= " + artifactUUID + " and artifactName= " + artifactName +
715         " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory +
716         " and artifactDescription= " + artifactDescription + " and artifactProtection= " +
717         artifactProtection + " and checksum= " + checksum);
718     return response;
719   }
720
721   private Response updateArtifactInternal(String actionInvariantUUID, String artifactUUID,
722                                           String artifactName, String artifactLabel,
723                                           String artifactCategory, String artifactDescription,
724                                           String artifactProtection, String checksum,
725                                           Attachment artifactToUpdate,
726                                           HttpServletRequest servletRequest) {
727     byte[] payload = null;
728     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
729
730     //Content-Type Header Validation
731     String contentType = servletRequest.getContentType();
732     if (StringUtils.isEmpty(contentType)) {
733       errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID);
734     }
735
736     if (artifactToUpdate != null) {
737
738       try (InputStream artifactInputStream = artifactToUpdate.getDataHandler().getInputStream()) {
739         payload = FileUtils.toByteArray(artifactInputStream);
740       } catch (IOException exception) {
741         LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception);
742         throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR);
743       }
744
745       //Validate Artifact size
746       if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) {
747         throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE,
748             ACTION_ARTIFACT_TOO_BIG_ERROR);
749       }
750
751       //Validate Checksum
752       if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) {
753         errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR);
754       }
755     }
756
757     if (artifactProtection != null && (artifactProtection.isEmpty() ||
758         (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) &&
759             !artifactProtection.equals(ActionArtifactProtection.readWrite.name())))) {
760       errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE,
761           ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE);
762     }
763
764     ActionArtifact updateArtifact = new ActionArtifact();
765     if (errorMap.isEmpty()) {
766       String user = servletRequest.getRemoteUser();
767       ActionArtifact update = new ActionArtifact();
768       update.setArtifactUuId(artifactUUID);
769       update.setArtifactName(artifactName);
770       update.setArtifactLabel(artifactLabel);
771       update.setArtifactDescription(artifactDescription);
772       update.setArtifact(payload);
773       update.setArtifactCategory(artifactCategory);
774       update.setArtifactProtection(artifactProtection);
775       actionManager.updateArtifact(update, actionInvariantUUID, user);
776     } else {
777       checkAndThrowError(errorMap);
778     }
779     return Response.ok().build();
780   }
781
782   /**
783    * Get List of all actions
784    */
785   private Response getAllActions(HttpServletRequest servletRequest) {
786     ListResponseWrapper responseList = null;
787     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
788     if (errorMap.isEmpty()) {
789       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_NONE, null);
790       responseList = createResponse(actions);
791     } else {
792       checkAndThrowError(errorMap);
793     }
794
795     return Response.ok(responseList).build();
796   }
797
798   /**
799    * Get Actions by OPENECOMP component ID
800    */
801   private Response getActionsByOpenEcompComponents(String componentID,
802                                                    HttpServletRequest servletRequest) {
803     ListResponseWrapper responseList = null;
804     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
805     Map<String, String> queryParamErrors = validateQueryParam(componentID);
806     errorMap.putAll(queryParamErrors);
807     if (errorMap.isEmpty()) {
808       List<Action> actions =
809           actionManager.getFilteredActions(FILTER_TYPE_OPEN_ECOMP_COMPONENT, componentID);
810       responseList = createResponse(actions);
811     } else {
812       checkAndThrowError(errorMap);
813     }
814     return Response.ok(responseList).build();
815   }
816
817   /**
818    * Get Actions by Model ID
819    */
820   private Response getActionsByModel(String modelId, HttpServletRequest servletRequest) {
821     ListResponseWrapper responseList = null;
822     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
823     Map<String, String> queryParamErrors = validateQueryParam(modelId);
824     errorMap.putAll(queryParamErrors);
825     if (errorMap.isEmpty()) {
826       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_MODEL, modelId);
827       responseList = createResponse(actions);
828     } else {
829       checkAndThrowError(errorMap);
830     }
831     return Response.ok(responseList).build();
832   }
833
834   /**
835    * Get all actions with given action name
836    */
837   private Response getActionsByName(String name, HttpServletRequest servletRequest) {
838     ListResponseWrapper responseList = null;
839     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
840     Map<String, String> queryParamErrors = validateQueryParam(name);
841     errorMap.putAll(queryParamErrors);
842     if (errorMap.isEmpty()) {
843       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_NAME, name);
844       responseList = createResponse(actions);
845     } else {
846       checkAndThrowError(errorMap);
847     }
848     return Response.ok(responseList).build();
849   }
850
851   /**
852    * Get an action with given ActionUUID
853    */
854   private Response getActionsByUniqueID(String actionUUID, HttpServletRequest servletRequest,
855                                         String actionInvariantUUID) {
856     LOGGER.debug(
857         " entering getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " +
858             actionUUID);
859     Map<String, Object> responseDTO = new LinkedHashMap<>();
860     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
861     Map<String, String> queryParamErrors = validateQueryParam(actionUUID);
862     errorMap.putAll(queryParamErrors);
863     if (errorMap.isEmpty()) {
864       Action action = actionManager.getActionsByActionUuId(actionUUID);
865       if (action.getActionInvariantUuId() != null &&
866           action.getActionInvariantUuId().equalsIgnoreCase(actionInvariantUUID)) {
867         responseDTO = JsonUtil.json2Object(action.getData(), LinkedHashMap.class);
868         responseDTO.put(STATUS, action.getStatus().name());
869         responseDTO.put(TIMESTAMP, getUtcDateStringFromTimestamp(action.getTimestamp()));
870         responseDTO.put(UPDATED_BY, action.getUser());
871       } else {
872         throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST);
873       }
874     } else {
875       checkAndThrowError(errorMap);
876     }
877     LOGGER.debug(
878         " exit getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " +
879             actionUUID);
880     return Response.ok(responseDTO).build();
881   }
882
883   /**
884    * Get all actions with given Vendor Name
885    */
886   private Response getActionsByVendor(String vendor, HttpServletRequest servletRequest) {
887     //Validate request syntax before passing to the manager
888     ListResponseWrapper responseList = null;
889     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
890     Map<String, String> queryParamErrors = validateQueryParam(vendor);
891     errorMap.putAll(queryParamErrors);
892     if (errorMap.isEmpty()) {
893       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_VENDOR, vendor);
894       responseList = createResponse(actions);
895     } else {
896       checkAndThrowError(errorMap);
897     }
898     return Response.ok(responseList).build();
899   }
900
901   /**
902    * Get all actions with given Category Name
903    */
904   private Response getActionsByCategory(String category, HttpServletRequest servletRequest) {
905     //Validate request syntax before passing to the manager
906     ListResponseWrapper responseList = null;
907     Map<String, String> errorMap = validateRequestHeaders(servletRequest);
908     Map<String, String> queryParamErrors = validateQueryParam(category);
909     errorMap.putAll(queryParamErrors);
910     if (errorMap.isEmpty()) {
911       List<Action> actions = actionManager.getFilteredActions(FILTER_TYPE_CATEGORY, category);
912       responseList = createResponse(actions);
913     } else {
914       checkAndThrowError(errorMap);
915     }
916     return Response.ok(responseList).build();
917   }
918
919   /**
920    * Validates mandatory headers in the request
921    *
922    * @param servletRequest Servlet Request object
923    * @return Map of error codes and description found in the request headers
924    */
925   private Map<String, String> validateRequestHeaders(HttpServletRequest servletRequest) {
926     Map<String, String> errorMap = new LinkedHashMap<>();
927     //Syntactic generic request parameter validations
928     String openEcompRequestId = servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM);
929     if (StringUtils.isEmpty(openEcompRequestId)) {
930       errorMap.put(ACTION_INVALID_REQUEST_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_REQUEST_ID_INVALID);
931     }
932
933     String opemnEcompInstanceId = servletRequest.getHeader(X_OPEN_ECOMP_INSTANCE_ID_HEADER_PARAM);
934     if (StringUtils.isEmpty(opemnEcompInstanceId)) {
935       errorMap.put(ACTION_INVALID_INSTANCE_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_INSTANCE_ID_INVALID);
936     }
937     return errorMap;
938   }
939
940   /**
941    * Validates query parameter in the request
942    *
943    * @param queryParam Query Parameter to be validated
944    * @return Map of error codes and description found in the query parameter
945    */
946   private Map<String, String> validateQueryParam(String queryParam) {
947     Map<String, String> queryParamErrors = new LinkedHashMap<>();
948     if (StringUtils.isEmpty(queryParam)) {
949       queryParamErrors
950           .put(ACTION_INVALID_PARAM_CODE, ACTION_REQUEST_MISSING_MANDATORY_PARAM + queryParam);
951     }
952     return queryParamErrors;
953   }
954
955   /**
956    * Validate request body based on request type
957    *
958    * @param requestJSON Raw request json body as string
959    * @return Map of error codes and description found in the request body
960    */
961   private Map<String, String> validateRequestBody(String requestType, String requestJSON) {
962     Map<String, String> requestBodyErrorMap = new LinkedHashMap<>();
963     if (StringUtils.isEmpty(requestJSON) || requestJSON.equals(REQUEST_EMPTY_BODY)) {
964       requestBodyErrorMap.put(ACTION_INVALID_REQUEST_BODY_CODE, ACTION_REQUEST_BODY_EMPTY);
965     } else {
966       if(requestType == ActionConstants.REQUEST_TYPE_CREATE_ACTION){
967         //placeholder for future implementation
968       }
969       if(requestType == ActionConstants.REQUEST_TYPE_UPDATE_ACTION){
970         //Semantic request specific validations
971         Action action = JsonUtil.json2Object(requestJSON, Action.class);
972         if(StringUtils.isEmpty(action.getName())){
973           setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_PARAM_NAME,
974               requestBodyErrorMap);
975         } else {
976           //Added check for action names not allowing whitespaces
977           if (action.getName().matches(whitespaceRegex)){
978             requestBodyErrorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_REQUEST_INVALID_NAME);
979           }
980         }
981
982         if(action.getSupportedModels() != null && !isIDPresentInMap(action.getSupportedModels(),
983             SUPPORTED_MODELS_VERSION_ID)){
984           setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE,
985               ACTION_REQUEST_PARAM_SUPPORTED_MODELS, requestBodyErrorMap);
986         }
987         if(action.getSupportedComponents() != null && !isIDPresentInMap(action
988             .getSupportedComponents(), SUPPORTED_COMPONENTS_ID)){
989           setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE,
990               ACTION_REQUEST_PARAM_SUPPORTED_MODELS, requestBodyErrorMap);
991         }
992         if(action.getArtifacts() != null){
993           setErrorValue(ACTION_UPDATE_NOT_ALLOWED_CODE,
994               ACTION_REQUEST_ARTIFACT_OPERATION_ALLOWED, requestBodyErrorMap);
995         }
996       }
997
998     }
999     return requestBodyErrorMap;
1000   }
1001
1002   /**
1003    * Populates Given Error Map with Given Error Code and Error MEssage
1004    */
1005   private void setErrorValue(String key, String message, Map<String, String> errorMap) {
1006     String errorMessage = errorMap.get(key);
1007     if (errorMessage != null) {
1008       message = errorMessage + ", " + message;
1009     } else {
1010       if(key == ACTION_REQUEST_INVALID_GENERIC_CODE)
1011         message = ACTION_REQUEST_MISSING_MANDATORY_PARAM + message;
1012     }
1013     errorMap.put(key, message);
1014   }
1015
1016   /**
1017    * Returns true if given key exists in List of HashMap
1018    */
1019   private boolean isIDPresentInMap(List<HashMap<String, String>> map, String idName) {
1020     if (map != null && !map.isEmpty()) {
1021       for (HashMap<String, String> entry : map) {
1022         if (StringUtils.isEmpty(entry.get(idName))) {
1023           return false;
1024         }
1025       }
1026     }
1027     return true;
1028   }
1029
1030   /**
1031    * @throws ActionException if given ErrorMap is not empty. All error messages at given time are
1032    *                         thrown in one single exception
1033    */
1034   private void checkAndThrowError(Map<String, String> errorMap) {
1035     if (errorMap.size() > 1) {
1036       //Multiple errors detected .. Send the response with a common error code for multiple errors
1037       throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE,
1038           StringUtils.join(errorMap.values(), ", "));
1039     } else if (errorMap.size() == 1) {
1040       String svcPolicyExceptionCode = errorMap.entrySet().iterator().next().getKey();
1041       throw new ActionException(svcPolicyExceptionCode,
1042           errorMap.get(svcPolicyExceptionCode));
1043     }
1044   }
1045
1046   /**
1047    * Populates ActionResponseDto based on given Action
1048    */
1049   private ActionResponseDto createResponseDTO(Action action) {
1050     String data = action.getData();
1051     ActionResponseDto responseDTO = JsonUtil.json2Object(data, ActionResponseDto.class);
1052     responseDTO.setStatus(action.getStatus().name());
1053     responseDTO.setTimestamp(getUtcDateStringFromTimestamp(action.getTimestamp()));
1054     //if(!action.getUser().equals(DELETE_ACTION_USER))
1055     responseDTO.setUpdatedBy(action.getUser());
1056     return responseDTO;
1057   }
1058
1059   /**
1060    * Creates response based on given list of actions
1061    */
1062   private ListResponseWrapper createResponse(List<Action> actions) {
1063     ListResponseWrapper responseList = new ListResponseWrapper();
1064     for (Action action : actions) {
1065       ActionResponseDto responseDTO = createResponseDTO(action);
1066       responseList.add(responseDTO);
1067     }
1068     return responseList;
1069   }
1070
1071
1072   private Response createArtifactDownloadResponse(ActionArtifact actionartifact) {
1073     if (actionartifact != null && actionartifact.getArtifact() != null) {
1074       byte[] artifactsBytes = actionartifact.getArtifact();
1075       File artifactFile = new File(actionartifact.getArtifactName());
1076       try (FileOutputStream fos = new FileOutputStream(artifactFile)) {
1077         fos.write(artifactsBytes);
1078       } catch (IOException exception) {
1079         LOGGER.error(ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG, exception);
1080         throw new ActionException(ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE,
1081             ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
1082       }
1083       Response.ResponseBuilder responseBuilder = Response.ok(artifactFile);
1084       responseBuilder.header("Content-Disposition",
1085           "attachment; filename=" + actionartifact.getArtifactName());
1086       responseBuilder.header("Content-MD5", CalcMD5CheckSum(artifactsBytes));
1087       responseBuilder.header("Content-Length", artifactFile.length());
1088       return responseBuilder.build();
1089     } else {
1090       throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE,
1091           ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST);
1092     }
1093   }
1094
1095   /**
1096    * Initialize MDC for logging the current request
1097    *
1098    * @param actionInvariantId Action Invariant Id if available (null otherwise)
1099    * @param servletRequest    Request Contecxt object
1100    * @param requestType       Current action request (CRUD of Action, Artifact, Version operations)
1101    */
1102   private void initializeRequestMDC(HttpServletRequest servletRequest, String actionInvariantId,
1103                                     ActionRequest requestType) {
1104     MDC.put(REQUEST_ID, servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM));
1105     MDC.put(PARTNER_NAME, servletRequest.getRemoteUser());
1106     MDC.put(INSTANCE_UUID, MDC_ASDC_INSTANCE_UUID);
1107     MDC.put(SERVICE_METRIC_BEGIN_TIMESTAMP, String.valueOf(System.currentTimeMillis()));
1108     MDC.put(STATUS_CODE, StatusCode.COMPLETE.name());
1109     MDC.put(SERVICE_NAME, requestType.name());
1110     MDC.put(CLIENT_IP, MDC.get(REMOTE_HOST));
1111     MDC.put(SERVICE_INSTANCE_ID, actionInvariantId);
1112     MDC.put(LOCAL_ADDR, MDC.get("ServerIPAddress"));
1113     MDC.put(BE_FQDN, MDC.get("ServerFQDN"));
1114
1115     if (LOGGER.isDebugEnabled()) {
1116       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.DEBUG.name());
1117     } else if (LOGGER.isInfoEnabled()) {
1118       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.INFO.name());
1119     } else if (LOGGER.isWarnEnabled()) {
1120       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.WARN.name());
1121     } else if (LOGGER.isErrorEnabled()) {
1122       MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.ERROR.name());
1123     }
1124   }
1125
1126   private String CalcMD5CheckSum(byte[] input) {
1127     String checksum = null;
1128     if (input != null) {
1129       checksum = DigestUtils.md5Hex(input).toUpperCase();
1130       System.out.println("checksum : " + checksum);
1131     }
1132     return checksum;
1133   }
1134 }