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