dc101ae9551c6b02a3491f67591048b751e89249
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdc.action.impl;
18
19 import org.apache.commons.collections4.CollectionUtils;
20 import org.apache.commons.lang.StringUtils;
21 import org.openecomp.core.dao.UniqueValueDao;
22 import org.openecomp.core.dao.UniqueValueDao;
23 import org.openecomp.core.dao.UniqueValueDaoFactory;
24 import org.openecomp.core.util.UniqueValueUtil;
25 import org.openecomp.core.utilities.CommonMethods;
26 import org.openecomp.core.utilities.json.JsonUtil;
27 import org.openecomp.sdc.action.ActionConstants;
28 import org.openecomp.sdc.action.ActionManager;
29 import org.openecomp.sdc.action.dao.ActionArtifactDao;
30 import org.openecomp.sdc.action.dao.ActionArtifactDaoFactory;
31 import org.openecomp.sdc.action.dao.ActionDao;
32 import org.openecomp.sdc.action.dao.ActionDaoFactory;
33 import org.openecomp.sdc.action.dao.types.ActionArtifactEntity;
34 import org.openecomp.sdc.action.dao.types.ActionEntity;
35 import org.openecomp.sdc.action.errors.ActionErrorConstants;
36 import org.openecomp.sdc.action.errors.ActionException;
37 import org.openecomp.sdc.action.logging.StatusCode;
38 import org.openecomp.sdc.action.types.*;
39 import org.openecomp.sdc.common.errors.CoreException;
40 import org.openecomp.sdc.logging.api.Logger;
41 import org.openecomp.sdc.logging.api.LoggerFactory;
42 import org.openecomp.sdc.versioning.ActionVersioningManager;
43 import org.openecomp.sdc.versioning.ActionVersioningManagerFactory;
44 import org.openecomp.sdc.versioning.dao.VersionInfoDao;
45 import org.openecomp.sdc.versioning.dao.VersionInfoDaoFactory;
46 import org.openecomp.sdc.versioning.dao.types.UserCandidateVersion;
47 import org.openecomp.sdc.versioning.dao.types.Version;
48 import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity;
49 import org.openecomp.sdc.versioning.errors.EntityNotExistErrorBuilder;
50 import org.openecomp.sdc.versioning.errors.VersioningErrorCodes;
51 import org.openecomp.sdc.versioning.types.VersionInfo;
52 import org.openecomp.sdc.versioning.types.VersionableEntityAction;
53 import org.slf4j.MDC;
54
55 import java.util.*;
56
57 import static org.openecomp.sdc.action.ActionConstants.*;
58 import static org.openecomp.sdc.action.errors.ActionErrorConstants.*;
59 import static org.openecomp.sdc.action.util.ActionUtil.*;
60 import static org.openecomp.sdc.versioning.dao.types.Version.VERSION_STRING_VIOLATION_MSG;
61
62 /**
63  * Manager Implementation for {@link ActionManager Action Library Operations}
64  * <br>
65  * Handles Business layer validations and acts as an interface between the REST
66  * and DAO layers.
67  */
68 public class ActionManagerImpl implements ActionManager {
69
70     private static final String ARTIFACT_UUID = "artifactUUID= ";
71     private static final String BY_USER = " by user = ";
72     private static final String WITH_VALUE = " With value = ";
73     private static final String AND_VERSION = " and version";
74     private final ActionDao actionDao;
75     private final ActionVersioningManager versioningManager;
76     private final ActionArtifactDao actionArtifactDao;
77     private final VersionInfoDao versionInfoDao;
78     private final UniqueValueDao uniqueValueDao;
79
80     private final Logger log = LoggerFactory.getLogger(this.getClass()
81             .getName());
82
83   public ActionManagerImpl() {
84     actionDao = ActionDaoFactory.getInstance().createInterface();
85     versioningManager = ActionVersioningManagerFactory.getInstance().createInterface();
86     actionArtifactDao = ActionArtifactDaoFactory.getInstance().createInterface();
87     versionInfoDao = VersionInfoDaoFactory.getInstance().createInterface();
88     actionDao.registerVersioning(ACTION_VERSIONABLE_TYPE);
89     uniqueValueDao = UniqueValueDaoFactory.getInstance().createInterface();
90   }
91
92   public ActionManagerImpl(ActionDao actionDao, ActionVersioningManager versioningManager,
93                            ActionArtifactDao actionArtifactDao, VersionInfoDao versionInfoDao,
94                            UniqueValueDao uniqueValueDao) {
95     this.actionDao = actionDao;
96     this.versioningManager = versioningManager;
97     this.actionArtifactDao = actionArtifactDao;
98     this.versionInfoDao = versionInfoDao;
99     this.uniqueValueDao = uniqueValueDao;
100   }
101   /**
102    * List All Major, Last Minor and Candidate version (if any) for Given Action Invariant UUID
103    *
104    * @param invariantId Invariant UUID of the action for which the information is required
105    * @return List of All Major, Last Minor and Candidate version if any Of {@link Action} with given
106    * actionInvariantUuId.
107    * @throws ActionException Exception with an action library specific code, short description and
108    *                         detailed message for the error occurred during the operation
109    */
110
111     @Override
112     public List<Action> getActionsByActionInvariantUuId(String invariantId) {
113         List<Action> actions;
114
115         log.debug(" entering getActionsByActionInvariantUuId with  invariantID = " + invariantId);
116         actions = actionDao.getActionsByActionInvariantUuId(invariantId != null ? invariantId.toUpperCase() : null);
117
118         if (actions != null && actions.isEmpty()) {
119             throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST);
120         }
121
122         log.debug(" exit getActionsByActionInvariantUuId with  invariantID = " + invariantId);
123         return actions;
124     }
125
126     /**
127      * Get list of actions based on a filter criteria. If no filter is sent all
128      * actions will be returned
129      *
130      * @param filterType
131      *            Filter by Vendor/Category/Model/Component/None
132      * @param filterValue
133      *            Filter Parameter Value (Vendor ID/Category ID/Model
134      *            ID/Component ID)
135      * @return List of {@link Action} objects based on a filter criteria <br>
136      *         Empty List if no records match the provided filter criteria
137      */
138     @Override
139     public List<Action> getFilteredActions(String filterType, String filterValue) {
140         List<Action> actions;
141         log.debug(" entering getFilteredActions By filterType = " + filterType + WITH_VALUE + filterValue);
142         switch (filterType) {
143         case FILTER_TYPE_NONE:
144             // Business validation for OPENECOMP Component type fetch (if any)
145             break;
146         case FILTER_TYPE_VENDOR:
147             // Business validation for vendor type fetch (if any)
148             break;
149         case FILTER_TYPE_CATEGORY:
150             // Business validation for Category type fetch (if any)
151             break;
152         case FILTER_TYPE_MODEL:
153             // Business validation for model type fetch (if any)
154             break;
155         case FILTER_TYPE_OPEN_ECOMP_COMPONENT:
156             // Business validation for OPENECOMP Component type fetch (if any)
157             break;
158         case FILTER_TYPE_NAME:
159             actions = actionDao.getFilteredActions(filterType, filterValue != null ? filterValue.toLowerCase() : null);
160             if (actions != null && actions.isEmpty()) {
161                 throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST);
162             }
163             log.debug(" exit getFilteredActions By filterType = " + filterType + WITH_VALUE + filterValue);
164             return actions;
165         default:
166             break;
167         }
168         actions = actionDao.getFilteredActions(filterType, filterValue != null ? filterValue.toLowerCase() : null);
169         List<Action> majorMinorVersionList = getMajorMinorVersionActions(actions);
170         Collections.sort(majorMinorVersionList);
171         log.debug(" exit getFilteredActions By filterType = " + filterType + WITH_VALUE + filterValue);
172         return majorMinorVersionList;
173     }
174
175     /**
176      * Get the properties of an action version by its UUID.
177      *
178      * @param actionUuId
179      *            UUID of the specific action version
180      * @return {@link Action} object corresponding the version represented by
181      *         the UUID
182      */
183     @Override
184     public Action getActionsByActionUuId(String actionUuId) {
185         log.debug(" entering getActionsByActionUuId with  actionUUID = " + actionUuId);
186         Action action = actionDao.getActionsByActionUuId(actionUuId != null ? actionUuId.toUpperCase() : null);
187
188         if (action == null) {
189             throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST);
190         }
191
192         log.debug(" exit getActionsByActionUuId with  actionUUID = " + actionUuId);
193         return action;
194     }
195
196     /**
197      * List OPENECOMP Components supported by Action Library.
198      *
199      * @return List of {@link OpenEcompComponent} objects supported by Action
200      *         Library <br>
201      *         Empty List if no components are found
202      */
203     @Override
204     public List<OpenEcompComponent> getOpenEcompComponents() {
205         return actionDao.getOpenEcompComponents();
206     }
207
208     /**
209      * Delete an action.
210      *
211      * @param actionInvariantUuId
212      *            Invariant UUID of the action to be deleted
213      * @param user
214      *            User id of the user performing the operation
215      */
216     @Override
217     public void deleteAction(String actionInvariantUuId, String user) {
218         try {
219             log.debug(
220                     "entering deleteAction with actionInvariantUuId = " + actionInvariantUuId + " and user = " + user);
221             actionLogPreProcessor(ActionSubOperation.DELETE_ACTION, TARGET_ENTITY_API);
222             versioningManager.delete(ACTION_VERSIONABLE_TYPE, actionInvariantUuId, user);
223             actionLogPostProcessor(StatusCode.COMPLETE);
224             log.metrics("");
225             actionDao.deleteAction(actionInvariantUuId);
226         } catch (CoreException ce) {
227             formAndThrowException(ce);
228         }
229     }
230
231     /**
232      * Create a new Action.
233      *
234      * @param action
235      *            Action object model of the user request for creating an action
236      * @param user
237      *            AT&T id of the user sending the create request
238      * @return {@link Action} model object for the created action
239      */
240     @Override
241     public Action createAction(Action action, String user) {
242         UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(uniqueValueDao);
243         try {
244             actionLogPreProcessor(ActionSubOperation.VALIDATE_ACTION_UNIQUE_NAME, TARGET_ENTITY_API);
245             uniqueValueUtil.validateUniqueValue(ActionConstants.UniqueValues.ACTION_NAME, action.getName());
246             actionLogPostProcessor(StatusCode.COMPLETE);
247         } catch (CoreException exception) {
248             String errorDesc = String.format(ACTION_ENTITY_UNIQUE_VALUE_MSG, ActionConstants.UniqueValues.ACTION_NAME,
249                     action.getName());
250             log.error(errorDesc, exception);
251             actionLogPostProcessor(StatusCode.ERROR, ACTION_ENTITY_UNIQUE_VALUE_ERROR, errorDesc, false);
252             throw new ActionException(ACTION_ENTITY_UNIQUE_VALUE_ERROR, errorDesc);
253         } finally {
254             log.metrics("");
255         }
256         action.setUser(user);
257         action.setTimestamp(getCurrentTimeStampUtc());
258         action.setActionInvariantUuId(CommonMethods.nextUuId());
259         action.setActionUuId(CommonMethods.nextUuId());
260
261         actionLogPreProcessor(ActionSubOperation.CREATE_ACTION_VERSION, TARGET_ENTITY_API);
262         Version version = versioningManager.create(ACTION_VERSIONABLE_TYPE, action.getActionInvariantUuId(), user);
263         actionLogPostProcessor(StatusCode.COMPLETE);
264         log.metrics("");
265
266         action.setVersion(version.toString());
267         action.setStatus(ActionStatus.Locked);
268         action = updateData(action);
269         action = actionDao.createAction(action);
270
271         actionLogPreProcessor(ActionSubOperation.CREATE_ACTION_UNIQUE_VALUE, TARGET_ENTITY_API);
272         uniqueValueUtil.createUniqueValue(ActionConstants.UniqueValues.ACTION_NAME, action.getName());
273         actionLogPostProcessor(StatusCode.COMPLETE);
274         log.metrics("");
275
276         return action;
277     }
278
279     /**
280      * Update an existing action.
281      *
282      * @param action
283      *            Action object model of the user request for creating an action
284      * @param user
285      *            AT&T id of the user sending the update request
286      * @return {@link Action} model object for the update action
287      */
288     @Override
289     public Action updateAction(Action action, String user) {
290         try {
291             log.debug("entering updateAction to update action with invariantUuId = " + action.getActionInvariantUuId()
292                     + BY_USER + user);
293             String invariantUuId = action.getActionInvariantUuId();
294             actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_API);
295             VersionInfo versionInfo = versioningManager.getEntityVersionInfo(ACTION_VERSIONABLE_TYPE, invariantUuId,
296                     user, VersionableEntityAction.Write);
297             actionLogPostProcessor(StatusCode.COMPLETE);
298             log.metrics("");
299
300             Version activeVersion = versionInfo.getActiveVersion();
301             validateActions(action, activeVersion);
302             action.setStatus(ActionStatus.Locked); // Status will be Checkout
303                                                    // for update
304             updateData(action);
305             action.setUser(user);
306             action.setTimestamp(getCurrentTimeStampUtc());
307             actionDao.updateAction(action);
308
309         } catch (CoreException ce) {
310             formAndThrowException(ce);
311         }
312         log.debug("exit updateAction");
313         return action;
314     }
315
316     /**
317      * Checkout an existing action.
318      *
319      * @param invariantUuId
320      *            actionInvariantUuId of the action to be checked out
321      * @param user
322      *            AT&T id of the user sending the checkout request
323      * @return {@link Action} model object for the checkout action
324      */
325     @Override
326     public Action checkout(String invariantUuId, String user) {
327         Version version = null;
328         ActionEntity actionEntity = null;
329         try {
330             log.debug("entering checkout for Action with invariantUUID= " + invariantUuId + BY_USER + user);
331             actionLogPreProcessor(ActionSubOperation.CHECKOUT_ACTION, TARGET_ENTITY_API);
332             version = versioningManager.checkout(ACTION_VERSIONABLE_TYPE, invariantUuId, user);
333             actionLogPostProcessor(StatusCode.COMPLETE);
334             log.metrics("");
335
336             actionEntity = updateUniqueIdForVersion(invariantUuId, version, ActionStatus.Locked.name(), user);
337         } catch (CoreException exception) {
338             if (exception.code() != null && exception.code()
339                     .id()
340                     .equals(VersioningErrorCodes.CHECKOT_ON_LOCKED_ENTITY)) {
341                 actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB);
342                 VersionInfoEntity versionInfoEntity = versionInfoDao
343                         .get(new VersionInfoEntity(ACTION_VERSIONABLE_TYPE, invariantUuId));
344                 actionLogPostProcessor(StatusCode.COMPLETE);
345                 log.metrics("");
346                 String checkoutUser = versionInfoEntity.getCandidate()
347                         .getUser();
348                 log.debug("Actual checkout user for Action with invariantUUID= " + invariantUuId + " is = "
349                         + checkoutUser);
350                 if (!checkoutUser.equals(user)) {
351                     throw new ActionException(ACTION_CHECKOUT_ON_LOCKED_ENTITY_OTHER_USER, exception.getMessage());
352                 }
353             }
354             formAndThrowException(exception);
355         }
356         log.debug("exit checkout for Action with invariantUUID= " + invariantUuId + BY_USER + user);
357         return actionEntity != null ? actionEntity.toDto() : new Action();
358     }
359
360     /**
361      * Undo an already checked out action.
362      *
363      * @param invariantUuId
364      *            actionInvariantUuId of the checked out action
365      * @param user
366      *            AT&T id of the user sending the request
367      */
368     @Override
369     public void undoCheckout(String invariantUuId, String user) {
370         Version version;
371         try {
372             log.debug("entering undoCheckout for Action with invariantUUID= " + invariantUuId + BY_USER + user);
373
374             actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB);
375             // Get list of uploaded artifacts in this checked out version
376             VersionInfoEntity versionInfoEntity = versionInfoDao
377                     .get(new VersionInfoEntity(ACTION_VERSIONABLE_TYPE, invariantUuId));
378             actionLogPostProcessor(StatusCode.COMPLETE);
379             log.metrics("");
380             if (versionInfoEntity == null) {
381                 throw new CoreException(new EntityNotExistErrorBuilder(ACTION_VERSIONABLE_TYPE, invariantUuId).build());
382             }
383             UserCandidateVersion candidate = versionInfoEntity.getCandidate();
384             Version activeVersion;
385             if (candidate != null) {
386                 activeVersion = candidate.getVersion();
387             } else {
388                 activeVersion = versionInfoEntity.getActiveVersion();
389             }
390
391             actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_VERSION, TARGET_ENTITY_DB);
392             Action action = actionDao.get(new ActionEntity(invariantUuId, activeVersion))
393                     .toDto();
394             actionLogPostProcessor(StatusCode.COMPLETE);
395             log.metrics("");
396
397             // Perform undo checkout on the action
398             actionLogPreProcessor(ActionSubOperation.UNDO_CHECKOUT_ACTION, TARGET_ENTITY_API);
399             version = versioningManager.undoCheckout(ACTION_VERSIONABLE_TYPE, invariantUuId, user);
400             actionLogPostProcessor(StatusCode.COMPLETE);
401             log.metrics("");
402
403             if (version.equals(new Version(0, 0))) {
404                 actionLogPreProcessor(ActionSubOperation.DELETE_UNIQUEVALUE, TARGET_ENTITY_API);
405                 UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(uniqueValueDao);
406                 uniqueValueUtil.deleteUniqueValue(ActionConstants.UniqueValues.ACTION_NAME, action.getName());
407                 actionLogPostProcessor(StatusCode.COMPLETE);
408                 log.metrics("");
409
410                 actionLogPreProcessor(ActionSubOperation.DELETE_ACTIONVERSION, TARGET_ENTITY_DB);
411                 // Added for the case where Create->Undo_Checkout->Checkout
412                 // should not get the action
413                 versionInfoDao.delete(new VersionInfoEntity(ACTION_VERSIONABLE_TYPE, invariantUuId));
414                 actionLogPostProcessor(StatusCode.COMPLETE);
415                 log.metrics("");
416             }
417
418             List<ActionArtifact> currentVersionArtifacts = action.getArtifacts();
419
420             // Delete the artifacts from action_artifact table (if any)
421             if (CollectionUtils.isNotEmpty(currentVersionArtifacts) && currentVersionArtifacts.size() > 0) {
422                 for (ActionArtifact artifact : currentVersionArtifacts) {
423                     ActionArtifactEntity artifactDeleteEntity = new ActionArtifactEntity(artifact.getArtifactUuId(),
424                             getEffectiveVersion(activeVersion.toString()));
425                     actionLogPreProcessor(ActionSubOperation.DELETE_ARTIFACT, TARGET_ENTITY_DB);
426                     actionArtifactDao.delete(artifactDeleteEntity);
427                     actionLogPostProcessor(StatusCode.COMPLETE);
428                     log.metrics("");
429                 }
430             }
431         } catch (CoreException exception) {
432             formAndThrowException(exception);
433         }
434         log.debug("exit undoCheckout for Action with invariantUUID= " + invariantUuId + BY_USER + user);
435     }
436
437     /**
438      * Checkin a checked out action.
439      *
440      * @param invariantUuId
441      *            actionInvariantUuId of the checked out action
442      * @param user
443      *            AT&T id of the user sending the request
444      * @return {@link Action} model object for the updated action
445      */
446     @Override
447     public Action checkin(String invariantUuId, String user) {
448         Version version = null;
449         ActionEntity actionEntity = null;
450         try {
451             log.debug("entering checkin for Action with invariantUUID= " + invariantUuId + BY_USER + user);
452             actionLogPreProcessor(ActionSubOperation.CHECKIN_ACTION, TARGET_ENTITY_API);
453             version = versioningManager.checkin(ACTION_VERSIONABLE_TYPE, invariantUuId, user, null);
454             actionLogPostProcessor(StatusCode.COMPLETE);
455             log.metrics("");
456             actionEntity = updateStatusForVersion(invariantUuId, version, ActionStatus.Available.name(), user);
457         } catch (CoreException exception) {
458             formAndThrowException(exception);
459         }
460         log.debug("exit checkin for Action with invariantUUID= " + invariantUuId + BY_USER + user);
461         return actionEntity != null ? actionEntity.toDto() : new Action();
462     }
463
464     /**
465      * Submit a checked in action.
466      *
467      * @param invariantUuId
468      *            actionInvariantUuId of the checked in action
469      * @param user
470      *            AT&T id of the user sending the request
471      * @return {@link Action} model object for the updated action
472      */
473     @Override
474     public Action submit(String invariantUuId, String user) {
475         Version version = null;
476         ActionEntity actionEntity = null;
477         try {
478             log.debug("entering submit for Action with invariantUUID= " + invariantUuId + BY_USER + user);
479             actionLogPreProcessor(ActionSubOperation.SUBMIT_ACTION, TARGET_ENTITY_API);
480             version = versioningManager.submit(ACTION_VERSIONABLE_TYPE, invariantUuId, user, null);
481             actionLogPostProcessor(StatusCode.COMPLETE);
482             log.metrics("");
483             actionEntity = updateUniqueIdForVersion(invariantUuId, version, ActionStatus.Final.name(), user);
484         } catch (CoreException exception) {
485             formAndThrowException(exception);
486         }
487         log.debug("exit submit for Action with invariantUUID= " + invariantUuId + BY_USER + user);
488         return actionEntity != null ? actionEntity.toDto() : new Action();
489     }
490
491     /**
492      * Download an artifact of an action.
493      *
494      * @param artifactUuId
495      *            {@link ActionArtifact} object representing the artifact and
496      *            its metadata
497      * @param actionUuId
498      *            UUID of the action for which the artifact has to be downloaded
499      * @return downloaded action artifact object
500      */
501     @Override
502     public ActionArtifact downloadArtifact(String actionUuId, String artifactUuId) {
503         log.debug(" entering downloadArtifact with actionUUID= " + actionUuId + " and artifactUUID= " + artifactUuId);
504         Action action = actionDao.getActionsByActionUuId(actionUuId);
505         ActionArtifact actionArtifact;
506         if (action != null) {
507             MDC.put(SERVICE_INSTANCE_ID, action.getActionInvariantUuId());
508             List<ActionArtifact> artifacts = action.getArtifacts();
509             String actionVersion = action.getVersion();
510             int effectiveVersion = getEffectiveVersion(actionVersion);
511             ActionArtifact artifactMetadata = getArtifactMetadataFromAction(artifacts, ARTIFACT_METADATA_ATTR_UUID,
512                     artifactUuId);
513             if (artifactMetadata != null) {
514                 String artifactName = artifactMetadata.getArtifactName();
515                 actionArtifact = actionArtifactDao.downloadArtifact(effectiveVersion, artifactUuId);
516                 actionArtifact.setArtifactName(artifactName);
517
518             } else {
519                 throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE,
520                         ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST);
521             }
522         } else {
523             throw new ActionException(ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE,
524                     ActionErrorConstants.ACTION_ENTITY_NOT_EXIST);
525         }
526         log.debug(" exit downloadArtifact with actionUUID= " + actionUuId + " and artifactUUID= " + artifactUuId);
527         return actionArtifact;
528     }
529
530     /**
531      * Upload an artifact to an action.
532      *
533      * @param artifact
534      *            {@link ActionArtifact} object representing the artifact and
535      *            its metadata
536      * @param actionInvariantUuId
537      *            Invariant UUID of the action to which the artifact has to be
538      *            uploaded
539      * @param user
540      *            User ID of the user sending the request
541      * @return Uploaded action artifact object
542      */
543     @Override
544     public ActionArtifact uploadArtifact(ActionArtifact artifact, String actionInvariantUuId, String user) {
545         ActionArtifact uploadArtifactResponse = new ActionArtifact();
546         try {
547             log.debug("entering uploadArtifact with actionInvariantUuId= " + actionInvariantUuId + "artifactName= "
548                     + artifact.getArtifactName());
549             actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB);
550             VersionInfo versionInfo = versioningManager.getEntityVersionInfo(ACTION_VERSIONABLE_TYPE,
551                     actionInvariantUuId, user, VersionableEntityAction.Write);
552             actionLogPostProcessor(StatusCode.COMPLETE);
553             log.metrics("");
554             Version activeVersion = versionInfo.getActiveVersion();
555             actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_ACTIONINVID, TARGET_ENTITY_DB);
556             Action action = actionDao.get(new ActionEntity(actionInvariantUuId, activeVersion))
557                     .toDto();
558             actionLogPostProcessor(StatusCode.COMPLETE);
559             log.metrics("");
560             String artifactUuId = generateActionArtifactUuId(action, artifact.getArtifactName());
561             // Check for Unique document name
562             List<ActionArtifact> actionArtifacts = action.getArtifacts();
563             ActionArtifact artifactMetadata = getArtifactMetadataFromAction(actionArtifacts,
564                     ARTIFACT_METADATA_ATTR_NAME, artifact.getArtifactName());
565             if (artifactMetadata != null) {
566                 throw new ActionException(ACTION_ARTIFACT_ALREADY_EXISTS_CODE,
567                         String.format(ACTION_ARTIFACT_ALREADY_EXISTS, actionInvariantUuId));
568             }
569
570             // Create the artifact
571             artifact.setArtifactUuId(artifactUuId);
572             artifact.setTimestamp(getCurrentTimeStampUtc());
573             artifact.setEffectiveVersion(getEffectiveVersion(activeVersion.toString()));
574             actionArtifactDao.uploadArtifact(artifact);
575
576             // Update the action data field and timestamp
577             addArtifactMetadataInActionData(action, artifact);
578
579             // Set the response object
580             uploadArtifactResponse.setArtifactUuId(artifact.getArtifactUuId());
581         } catch (CoreException ce) {
582             formAndThrowException(ce);
583         }
584         log.debug("exit uploadArtifact with actionInvariantUuId= " + actionInvariantUuId + "artifactName= "
585                 + artifact.getArtifactName());
586         return uploadArtifactResponse;
587     }
588
589     @Override
590     public void deleteArtifact(String actionInvariantUuId, String artifactUuId, String user) {
591         log.debug("enter deleteArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID + artifactUuId
592                 + " and user = " + user);
593         Action action = actionDao.getLockedAction(actionInvariantUuId, user);
594         List<ActionArtifact> actionArtifacts = action.getArtifacts();
595         ActionArtifact artifactMetadata = getArtifactMetadataFromAction(actionArtifacts, ARTIFACT_METADATA_ATTR_UUID,
596                 artifactUuId);
597         if (artifactMetadata == null) {
598             throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE,
599                     ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST);
600         }
601         if (artifactMetadata.getArtifactProtection()
602                 .equals(ActionArtifactProtection.readOnly.name())) {
603             throw new ActionException(ACTION_ARTIFACT_DELETE_READ_ONLY, ACTION_ARTIFACT_DELETE_READ_ONLY_MSG);
604         } else {
605
606             // Update action by removing artifact metadata
607             String jsonData = action.getData();
608             List<ActionArtifact> artifacts = action.getArtifacts();// action.getArtifacts();
609             ActionArtifact artifact = null;
610             Iterator<ActionArtifact> it = artifacts.iterator();
611             while (it.hasNext()) {
612                 artifact = it.next();
613                 String artifactId = artifact.getArtifactUuId();
614                 if (artifactId.equals(artifactUuId)) {
615                     it.remove();
616                 }
617             }
618
619             Map dataMap = JsonUtil.json2Object(jsonData, LinkedHashMap.class);
620             dataMap.put("artifacts", artifacts);
621             String data = JsonUtil.object2Json(dataMap);
622             ActionEntity actionEntity = action.toEntity();
623             actionEntity.setData(data);
624             actionLogPreProcessor(ActionSubOperation.UPDATE_ACTION, TARGET_ENTITY_DB);
625             actionDao.update(actionEntity);
626             actionLogPostProcessor(StatusCode.COMPLETE, null, "", false);
627             log.metrics("");
628             // delete Artifact if it's upload and delete action on same checkout
629             // version
630             String artifactName = artifactMetadata.getArtifactName();
631             String generatedArtifactUuId = generateActionArtifactUuId(action, artifactName);
632             if (generatedArtifactUuId.equals(artifactUuId)) {
633                 if (artifact != null) {
634                     ActionArtifactEntity artifactDeleteEntity = new ActionArtifactEntity(artifact.getArtifactUuId(),
635                             getEffectiveVersion(action.getVersion()));
636                     actionLogPreProcessor(ActionSubOperation.DELETE_ACTION_ARTIFACT, TARGET_ENTITY_DB);
637                     actionArtifactDao.delete(artifactDeleteEntity);
638                 }
639                 actionLogPostProcessor(StatusCode.COMPLETE, null, "", false);
640                 log.metrics("");
641             }
642
643         }
644         log.debug("exit deleteArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID + artifactUuId
645                 + " and user = " + user);
646     }
647
648     /**
649      * Update an existing artifact.
650      *
651      * @param artifact
652      *            {@link ActionArtifact} object representing the artifact and
653      *            its metadata
654      * @param actionInvariantUuId
655      *            Invariant UUID of the action to which the artifact has to be
656      *            uploaded
657      * @param user
658      *            User ID of the user sending the request
659      */
660     public void updateArtifact(ActionArtifact artifact, String actionInvariantUuId, String user) {
661         try {
662             log.debug("Enter updateArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID
663                     + artifact.getArtifactUuId() + " and user = " + user);
664             actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_API);
665             VersionInfo versionInfo = versioningManager.getEntityVersionInfo(ACTION_VERSIONABLE_TYPE,
666                     actionInvariantUuId, user, VersionableEntityAction.Write);
667             actionLogPostProcessor(StatusCode.COMPLETE, null, "", false);
668             log.metrics("");
669             Version activeVersion = versionInfo.getActiveVersion();
670             actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_ACTIONINVID, TARGET_ENTITY_DB);
671             Action action = actionDao.get(new ActionEntity(actionInvariantUuId, activeVersion))
672                     .toDto();
673             actionLogPostProcessor(StatusCode.COMPLETE, null, "", false);
674             log.metrics("");
675             List<ActionArtifact> actionArtifacts = action.getArtifacts();
676             ActionArtifact artifactMetadataByUuId = getArtifactMetadataFromAction(actionArtifacts,
677                     ARTIFACT_METADATA_ATTR_UUID, artifact.getArtifactUuId());
678             // Check if artifact is already in action or not
679             if (artifactMetadataByUuId == null) {
680                 throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE,
681                         ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST);
682             }
683             // If user tries to change artifact name
684             if (artifact.getArtifactName() != null && !artifactMetadataByUuId.getArtifactName()
685                     .equalsIgnoreCase(artifact.getArtifactName())) {
686                 throw new ActionException(ACTION_UPDATE_NOT_ALLOWED_CODE, ACTION_ARTIFACT_UPDATE_NAME_INVALID);
687             }
688
689             byte[] payload = artifact.getArtifact();
690             String artifactLabel = artifact.getArtifactLabel();
691             String artifactCategory = artifact.getArtifactCategory();
692             String artifactDescription = artifact.getArtifactDescription();
693             String artifactProtection = artifact.getArtifactProtection();
694             String artifactName = artifact.getArtifactName();
695             // If artifact read only
696             if (artifactMetadataByUuId.getArtifactProtection()
697                     .equals(ActionArtifactProtection.readOnly.name())) {
698                 if (artifactName != null || artifactLabel != null || artifactCategory != null
699                         || artifactDescription != null || payload != null) {
700                     throw new ActionException(ACTION_ARTIFACT_UPDATE_READ_ONLY, ACTION_ARTIFACT_UPDATE_READ_ONLY_MSG);
701                 }
702                 // Changing value from readOnly to readWrite
703                 if (artifactProtection != null
704                         && artifactProtection.equals(ActionArtifactProtection.readWrite.name())) {
705                     artifactMetadataByUuId.setArtifactProtection(ActionArtifactProtection.readWrite.name());
706                     artifactMetadataByUuId.setTimestamp(getCurrentTimeStampUtc());
707                     updateArtifactMetadataInActionData(action, artifactMetadataByUuId);
708                 }
709             } else {
710                 int effectiveVersion = getEffectiveVersion(activeVersion.toString());
711                 if (artifactLabel != null) {
712                     artifactMetadataByUuId.setArtifactLabel(artifactLabel);
713                 }
714                 if (artifactCategory != null) {
715                     artifactMetadataByUuId.setArtifactCategory(artifactCategory);
716                 }
717                 if (artifactDescription != null) {
718                     artifactMetadataByUuId.setArtifactDescription(artifactDescription);
719                 }
720                 if (artifactProtection != null) {
721                     artifactMetadataByUuId.setArtifactProtection(artifactProtection);
722                 }
723                 if (payload != null) {
724                     // get artifact data from action_artifact table for updating
725                     // the content
726                     ActionArtifact artifactContent = new ActionArtifact();
727                     artifactContent.setArtifactUuId(artifact.getArtifactUuId());
728                     artifactContent.setArtifact(payload);
729                     artifactContent.setEffectiveVersion(effectiveVersion);
730                     actionArtifactDao.updateArtifact(artifactContent);
731                 }
732                 // Update the action data field and timestamp
733                 artifactMetadataByUuId.setTimestamp(getCurrentTimeStampUtc());
734                 updateArtifactMetadataInActionData(action, artifactMetadataByUuId);
735             }
736             log.debug("exit updateArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID
737                     + artifact.getArtifactUuId() + " and user = " + user);
738         } catch (CoreException coreException) {
739             formAndThrowException(coreException);
740         }
741     }
742
743     /**
744      * Generate artifact UUID at runtime using action name and effective
745      * version.
746      *
747      * @param action
748      *            {@link Action} for which the artifact is being
749      *            uploaded/updated/downloaded
750      * @param artifactName
751      *            Artifact name
752      * @return Generated UUID string
753      */
754     private String generateActionArtifactUuId(Action action, String artifactName) {
755         int effectiveVersion = getEffectiveVersion(action.getVersion());
756         // Upper case for maintaining case-insensitive behavior for the artifact
757         // names
758         String artifactUuIdString = action.getName()
759                 .toUpperCase() + effectiveVersion + artifactName.toUpperCase();
760         String generateArtifactUuId = UUID.nameUUIDFromBytes((artifactUuIdString).getBytes())
761                 .toString();
762         String artifactUuId = generateArtifactUuId.replace("-", "");
763         return artifactUuId.toUpperCase();
764     }
765
766     /**
767      * Generate the effective action version for artifact operations.
768      *
769      * @param actionVersion
770      *            Version of the action as a string
771      * @return Effective version to be used for artifact operations
772      */
773     private int getEffectiveVersion(String actionVersion) {
774         Version version = Version.valueOf(actionVersion);
775         return version.getMajor() * 10000 + version.getMinor();
776     }
777
778     /**
779      * Update the data field of the Action object with the modified/generated
780      * fields after an operation.
781      *
782      * @param action
783      *            Action object whose data field has to be updated
784      * @return Updated {@link Action} object
785      */
786     private Action updateData(Action action) {
787         log.debug("entering updateData to update data json for action with actionuuid=  " + action.getActionUuId());
788         Map<String, String> dataMap = new LinkedHashMap<>();
789         dataMap.put(ActionConstants.UNIQUE_ID, action.getActionUuId());
790         dataMap.put(ActionConstants.VERSION, action.getVersion());
791         dataMap.put(ActionConstants.INVARIANTUUID, action.getActionInvariantUuId());
792         dataMap.put(ActionConstants.STATUS, action.getStatus()
793                 .name());
794
795         String data = action.getData();
796         Map<String, String> currentDataMap = JsonUtil.json2Object(data, LinkedHashMap.class);
797         dataMap.putAll(currentDataMap);
798         data = JsonUtil.object2Json(dataMap);
799         action.setData(data);
800         log.debug("exit updateData");
801         return action;
802     }
803
804     /**
805      * Method to add the artifact metadata in the data attribute of action
806      * table.
807      *
808      * @param action
809      *            Action to which artifact is uploaded
810      * @param artifact
811      *            Uploaded artifact object
812      */
813     private void addArtifactMetadataInActionData(Action action, ActionArtifact artifact) {
814
815         ActionArtifact artifactMetadata = new ActionArtifact();
816         artifactMetadata.setArtifactUuId(artifact.getArtifactUuId());
817         artifactMetadata.setArtifactName(artifact.getArtifactName());
818         artifactMetadata.setArtifactProtection(artifact.getArtifactProtection());
819         artifactMetadata.setArtifactLabel(artifact.getArtifactLabel());
820         artifactMetadata.setArtifactDescription(artifact.getArtifactDescription());
821         artifactMetadata.setArtifactCategory(artifact.getArtifactCategory());
822         artifactMetadata.setTimestamp(artifact.getTimestamp());
823
824         List<ActionArtifact> actionArtifacts = action.getArtifacts();
825         if (actionArtifacts == null) {
826             actionArtifacts = new ArrayList<>();
827         }
828         actionArtifacts.add(artifactMetadata);
829         action.setArtifacts(actionArtifacts);
830         String currentData = action.getData();
831         Map<String, Object> currentDataMap = JsonUtil.json2Object(currentData, LinkedHashMap.class);
832         currentDataMap.put(ActionConstants.ARTIFACTS, actionArtifacts);
833         String updatedActionData = JsonUtil.object2Json(currentDataMap);
834         action.setData(updatedActionData);
835         action.setTimestamp(artifact.getTimestamp());
836         actionDao.updateAction(action);
837     }
838
839     /**
840      * Get a list of last major and last minor version (no candidate) of action
841      * from a list of actions.
842      *
843      * @param actions
844      *            Exhaustive list of the action versions
845      * @return List {@link Action} of last major and last minor version (no
846      *         candidate) of action from a list of actions
847      */
848     private List<Action> getMajorMinorVersionActions(List<Action> actions) {
849         log.debug(" entering getMajorMinorVersionActions for actions ");
850         List<Action> list = new LinkedList<>();
851         actionLogPreProcessor(ActionSubOperation.GET_VERSIONINFO_FOR_ALL_ACTIONS, TARGET_ENTITY_API);
852         Map<String, VersionInfo> actionVersionMap = versioningManager.listEntitiesVersionInfo(ACTION_VERSIONABLE_TYPE,
853                 "", VersionableEntityAction.Read);
854         actionLogPostProcessor(StatusCode.COMPLETE);
855         log.metrics("");
856         for (Action action : actions) {
857             if (action.getStatus() == ActionStatus.Deleted) {
858                 continue;
859             }
860             VersionInfo actionVersionInfo = actionVersionMap.get(action.getActionInvariantUuId());
861             if (actionVersionInfo.getActiveVersion() != null && actionVersionInfo.getActiveVersion()
862                     .equals(Version.valueOf(action.getVersion()))) {
863                 list.add(action);
864             } else if (actionVersionInfo.getLatestFinalVersion() != null && actionVersionInfo.getLatestFinalVersion()
865                     .equals(Version.valueOf(action.getVersion()))
866                     && !actionVersionInfo.getLatestFinalVersion()
867                             .equals(actionVersionInfo.getActiveVersion())) {
868                 list.add(action);
869             }
870         }
871         log.debug(" exit getMajorMinorVersionActions for actions ");
872         return list;
873     }
874
875     /**
876      * CoreException object wrapper from Version library to Action Library
877      * Exception.
878      *
879      * @param exception
880      *            CoreException object from version library
881      */
882     private void formAndThrowException(CoreException exception) {
883         log.debug("entering formAndThrowException with input CoreException =" + exception.code()
884                 .id() + " " + exception.getMessage());
885         String errorDescription = exception.getMessage();
886         String errorCode = exception.code()
887                 .id();
888         ActionException actionException = new ActionException();
889         switch (errorCode) {
890         case VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST:
891             actionException.setErrorCode(ACTION_ENTITY_NOT_EXIST_CODE);
892             actionException.setDescription(ACTION_ENTITY_NOT_EXIST);
893             break;
894         case VersioningErrorCodes.CHECKOT_ON_LOCKED_ENTITY:
895             actionException.setErrorCode(ACTION_CHECKOUT_ON_LOCKED_ENTITY);
896             actionException.setDescription(errorDescription);
897             break;
898         case VersioningErrorCodes.CHECKIN_ON_UNLOCKED_ENTITY:
899             actionException.setErrorCode(ACTION_CHECKIN_ON_UNLOCKED_ENTITY);
900             actionException.setDescription(errorDescription);
901             break;
902         case VersioningErrorCodes.SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED:
903             actionException.setErrorCode(ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED);
904             actionException.setDescription(errorDescription);
905             break;
906         case VersioningErrorCodes.SUBMIT_LOCKED_ENTITY_NOT_ALLOWED:
907             actionException.setErrorCode(ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED);
908             actionException.setDescription(errorDescription);
909             break;
910         case VersioningErrorCodes.UNDO_CHECKOUT_ON_UNLOCKED_ENTITY:
911             actionException.setErrorCode(ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY);
912             actionException.setDescription(errorDescription);
913             break;
914         case VersioningErrorCodes.EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER:
915             actionException.setErrorCode(ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER);
916             actionException.setDescription(errorDescription.replace("edit", "updat"));
917             break;
918         case VersioningErrorCodes.CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER:
919             actionException.setErrorCode(ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER);
920             actionException.setDescription(errorDescription);
921             break;
922         case VersioningErrorCodes.UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER:
923             actionException.setErrorCode(ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER);
924             actionException.setDescription(errorDescription);
925             break;
926         case VersioningErrorCodes.EDIT_ON_UNLOCKED_ENTITY:
927             actionException.setErrorCode(ACTION_UPDATE_ON_UNLOCKED_ENTITY);
928             actionException.setDescription(errorDescription.replace("edit", "update"));
929             break;
930         case VersioningErrorCodes.DELETE_ON_LOCKED_ENTITY:
931             actionException.setErrorCode(ACTION_DELETE_ON_LOCKED_ENTITY_CODE);
932             actionException.setDescription(errorDescription);
933             break;
934         default:
935             actionException.setErrorCode(ACTION_INTERNAL_SERVER_ERR_CODE);
936             actionException.setDescription(exception.getMessage());
937
938         }
939         // Todo - Uncomment only if class to be added in ERROR Log
940         /*
941          * actionErrorLogProcessor(CategoryLogLevel.ERROR,
942          * actionException.getErrorCode(), actionException.getDescription());
943          * log.error("");
944          */
945         log.debug("exit formAndThrowException with ActionException =" + actionException.getErrorCode() + " "
946                 + actionException.getDescription());
947         throw actionException;
948     }
949
950     /**
951      * Validates an action object for business layer validations before an
952      * update operation.
953      *
954      * @param action
955      *            Action object to be validated
956      * @param activeVersion
957      *            Active version of the actoin object
958      */
959     private void validateActions(Action action, Version activeVersion) {
960         try {
961             // Set version if not already available in input request
962             // If version set in input compare it with version from DB
963             if (StringUtils.isEmpty(action.getVersion())) {
964                 action.setVersion(activeVersion.toString());
965             } else {
966                 if (!activeVersion.equals(Version.valueOf(action.getVersion()))) {
967                     throw new ActionException(ACTION_UPDATE_INVALID_VERSION,
968                             String.format(ACTION_REQUESTED_VERSION_INVALID, action.getVersion()));
969                 }
970             }
971             String invariantUuId = action.getActionInvariantUuId();
972             Version version = Version.valueOf(action.getVersion());
973             Action existingAction = getActions(invariantUuId, version);
974             if (existingAction == null || existingAction.getActionInvariantUuId() == null) {
975                 throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST);
976             }
977             List<String> invalidParameters = new LinkedList<>();
978             // Prevent update of name, version and id fields
979             if (!existingAction.getName()
980                     .equals(action.getName())) {
981                 throw new ActionException(ACTION_UPDATE_NOT_ALLOWED_CODE_NAME, ACTION_UPDATE_NOT_ALLOWED_FOR_NAME);
982             }
983             if (!StringUtils.isEmpty(action.getActionUuId()) && !existingAction.getActionUuId()
984                     .equals(action.getActionUuId())) {
985                 invalidParameters.add(UNIQUE_ID);
986             }
987             if (action.getStatus() != null && (existingAction.getStatus() != action.getStatus())) {
988                 invalidParameters.add(STATUS);
989             }
990
991             if (!invalidParameters.isEmpty()) {
992                 throw new ActionException(ACTION_UPDATE_NOT_ALLOWED_CODE,
993                         String.format(ACTION_UPDATE_PARAM_INVALID, StringUtils.join(invalidParameters, ", ")));
994             }
995             action.setActionUuId(existingAction.getActionUuId());
996         } catch (IllegalArgumentException iae) {
997             String message = iae.getMessage();
998             if (message == VERSION_STRING_VIOLATION_MSG) {
999                 throw new ActionException(ACTION_UPDATE_NOT_ALLOWED_CODE, message);
1000             } else {
1001                 throw iae;
1002             }
1003         }
1004     }
1005
1006     /**
1007      * Get an action version entity object.
1008      *
1009      * @param invariantUuId
1010      *            Invariant UUID of the action
1011      * @param version
1012      *            Version of the action
1013      * @return {@link ActionEntity} object of the action version
1014      */
1015     private ActionEntity getActionsEntityByVersion(String invariantUuId, Version version) {
1016         log.debug("entering getActionsEntityByVersion with invariantUUID= " + invariantUuId + AND_VERSION + version);
1017         ActionEntity entity = null;
1018         if (version != null) {
1019             actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_VERSION, TARGET_ENTITY_DB);
1020             entity = actionDao
1021                     .get(new ActionEntity(invariantUuId != null ? invariantUuId.toUpperCase() : null, version));
1022             actionLogPostProcessor(StatusCode.COMPLETE);
1023             log.metrics("");
1024         }
1025         log.debug("exit getActionsEntityByVersion with invariantUuId= " + invariantUuId + AND_VERSION + version);
1026         return entity;
1027     }
1028
1029     /**
1030      * Get an action version object.
1031      *
1032      * @param invariantUuId
1033      *            Invariant UUID of the action
1034      * @param version
1035      *            Version of the action
1036      * @return {@link Action} object of the action version
1037      */
1038     private Action getActions(String invariantUuId, Version version) {
1039         ActionEntity actionEntity = getActionsEntityByVersion(
1040                 invariantUuId != null ? invariantUuId.toUpperCase() : null, version);
1041         return actionEntity != null ? actionEntity.toDto() : new Action();
1042     }
1043
1044     /**
1045      * Create and set the Unique ID in for an action version row.
1046      *
1047      * @param invariantUuId
1048      *            Invariant UUID of the action
1049      * @param version
1050      *            Version of the action
1051      * @param status
1052      *            Status of the action
1053      * @param user
1054      *            AT&T id of the user sending the request
1055      * @return {@link ActionEntity} object of the action version
1056      */
1057     private ActionEntity updateUniqueIdForVersion(String invariantUuId, Version version, String status, String user) {
1058         log.debug("entering updateUniqueIdForVersion to update action with invariantUuId= " + invariantUuId
1059                 + " with version,status and user as ::" + version + " " + status + " " + user);
1060         // generate UUID AND update for newly created entity row
1061         ActionEntity actionEntity = getActionsEntityByVersion(invariantUuId, version);
1062         if (actionEntity != null) {
1063             log.debug("Found action to be updated");
1064             String data = actionEntity.getData();
1065             String uniqueId = CommonMethods.nextUuId();
1066             Map<String, String> dataMap = JsonUtil.json2Object(data, LinkedHashMap.class);
1067             dataMap.put(ActionConstants.UNIQUE_ID, uniqueId);
1068             dataMap.put(ActionConstants.VERSION, version.toString());
1069             dataMap.put(ActionConstants.STATUS, status);
1070             data = JsonUtil.object2Json(dataMap);
1071
1072             actionEntity.setData(data);
1073             actionEntity.setActionUuId(uniqueId);
1074             actionEntity.setStatus(status);
1075             actionEntity.setUser(user);
1076             actionEntity.setTimestamp(getCurrentTimeStampUtc());
1077             actionLogPreProcessor(ActionSubOperation.UPDATE_ACTION, TARGET_ENTITY_DB);
1078             actionDao.update(actionEntity);
1079             actionLogPostProcessor(StatusCode.COMPLETE);
1080             log.metrics("");
1081         }
1082
1083         log.debug("exit updateUniqueIdForVersion to update action with invariantUUID= " + invariantUuId);
1084         return actionEntity;
1085     }
1086
1087     /**
1088      * Set the status for an action version row.
1089      *
1090      * @param invariantUuId
1091      *            Invariant UUID of the action
1092      * @param version
1093      *            Version of the action
1094      * @param status
1095      *            Status of the action
1096      * @param user
1097      *            AT&T id of the user sending the request
1098      * @return {@link ActionEntity} object of the action version
1099      */
1100     private ActionEntity updateStatusForVersion(String invariantUuId, Version version, String status, String user) {
1101         log.debug("entering updateStatusForVersion with invariantUuId= " + invariantUuId + AND_VERSION + version
1102                 + " for updating status " + status + " by user " + user);
1103         ActionEntity actionEntity = getActionsEntityByVersion(invariantUuId, version);
1104         if (actionEntity != null) {
1105             String data = actionEntity.getData();
1106             Map<String, String> dataMap = JsonUtil.json2Object(data, LinkedHashMap.class);
1107             dataMap.put(ActionConstants.STATUS, status);
1108             data = JsonUtil.object2Json(dataMap);
1109             actionEntity.setData(data);
1110             actionEntity.setStatus(status);
1111             actionEntity.setUser(user);
1112             actionEntity.setTimestamp(getCurrentTimeStampUtc());
1113             actionLogPreProcessor(ActionSubOperation.UPDATE_ACTION, TARGET_ENTITY_DB);
1114             actionDao.update(actionEntity);
1115             actionLogPostProcessor(StatusCode.COMPLETE);
1116             log.metrics("");
1117         }
1118         log.debug("exit updateStatusForVersion with invariantUuId= " + invariantUuId + AND_VERSION + version
1119                 + " for updating status " + status + " by user " + user);
1120         return actionEntity;
1121
1122     }
1123
1124     /**
1125      * Gets an artifact from the action artifact metadata by artifact name.
1126      *
1127      * @param actionArtifactList
1128      *            Action's existing artifact list
1129      * @param artifactFilterType
1130      *            Search criteria for artifact in action artifact metadata
1131      * @param artifactFilterValue
1132      *            Value of Search parameter
1133      * @return Artifact metadata object if artifact is present in action and
1134      *         null otherwise
1135      */
1136     private ActionArtifact getArtifactMetadataFromAction(List<ActionArtifact> actionArtifactList,
1137             String artifactFilterType, String artifactFilterValue) {
1138         ActionArtifact artifact = null;
1139         if (actionArtifactList != null && !actionArtifactList.isEmpty()) {
1140             for (ActionArtifact entry : actionArtifactList) {
1141                 switch (artifactFilterType) {
1142                 case ARTIFACT_METADATA_ATTR_UUID:
1143                     String artifactUuId = entry.getArtifactUuId();
1144                     if (artifactUuId != null && artifactUuId.equals(artifactFilterValue)) {
1145                         artifact = entry;
1146                         break;
1147                     }
1148                     break;
1149                 case ARTIFACT_METADATA_ATTR_NAME:
1150                     String existingArtifactName = entry.getArtifactName()
1151                             .toLowerCase();
1152                     if (existingArtifactName.equals(artifactFilterValue.toLowerCase())) {
1153                         artifact = entry;
1154                         break;
1155                     }
1156                     break;
1157                 default:
1158                 }
1159             }
1160         }
1161         return artifact;
1162     }
1163
1164     /**
1165      * Method to update the artifact metadata in the data attribute of action
1166      * table.
1167      *
1168      * @param action
1169      *            Action to which artifact is uploaded
1170      * @param updatedArtifact
1171      *            updated artifact object
1172      */
1173     private void updateArtifactMetadataInActionData(Action action, ActionArtifact updatedArtifact) {
1174         for (ActionArtifact entry : action.getArtifacts()) {
1175             if (entry.getArtifactUuId()
1176                     .equals(updatedArtifact.getArtifactUuId())) {
1177                 entry.setArtifactLabel(updatedArtifact.getArtifactLabel());
1178                 entry.setArtifactCategory(updatedArtifact.getArtifactCategory());
1179                 entry.setArtifactDescription(updatedArtifact.getArtifactDescription());
1180                 entry.setArtifactProtection(updatedArtifact.getArtifactProtection());
1181                 entry.setTimestamp(updatedArtifact.getTimestamp());
1182                 break;
1183             }
1184         }
1185         String data = action.getData();
1186         Map<String, Object> map = JsonUtil.json2Object(data, LinkedHashMap.class);
1187         map.put(ActionConstants.ARTIFACTS, action.getArtifacts());
1188         String updatedActionData = JsonUtil.object2Json(map);
1189         action.setData(updatedActionData);
1190         action.setTimestamp(updatedArtifact.getTimestamp());
1191         actionDao.updateAction(action);
1192     }
1193 }