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