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