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