Server Stubs PAP
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / rest / SessionData.java
index 923871e..4cea257 100644 (file)
@@ -3,7 +3,8 @@
  * ONAP PAP
  * ================================================================================
  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2021 Nordix Foundation.
+ * Modifications Copyright (C) 2021-2022 Nordix Foundation.
+ * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -31,6 +32,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.stream.Collectors;
+import lombok.Getter;
 import org.apache.commons.lang3.tuple.Pair;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.pap.concepts.PolicyNotification;
@@ -39,7 +41,6 @@ import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
 import org.onap.policy.models.pdp.concepts.PdpStateChange;
 import org.onap.policy.models.pdp.concepts.PdpUpdate;
 import org.onap.policy.models.pdp.enums.PdpState;
-import org.onap.policy.models.provider.PolicyModelsProvider;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
@@ -47,6 +48,10 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter.ToscaTypedEntityFilterBuilder;
 import org.onap.policy.pap.main.notification.DeploymentStatus;
+import org.onap.policy.pap.main.service.PdpGroupService;
+import org.onap.policy.pap.main.service.PolicyAuditService;
+import org.onap.policy.pap.main.service.PolicyStatusService;
+import org.onap.policy.pap.main.service.ToscaServiceTemplateService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -61,11 +66,6 @@ public class SessionData {
      */
     private static final Pattern VERSION_PREFIX_PAT = Pattern.compile("[^.]+(?:[.][^.]+)?");
 
-    /**
-     * DB provider.
-     */
-    private final PolicyModelsProvider dao;
-
     /**
      * Maps a group name to its group data. This accumulates the set of groups to be created and updated when the REST
      * call completes.
@@ -96,27 +96,46 @@ public class SessionData {
     /**
      * Map's a policy's identifier to the policies for deployment.
      */
-    private Map<ToscaConceptIdentifier, ToscaPolicy> policiesToBeDeployed = new HashMap<>();
+    private final Map<ToscaConceptIdentifier, ToscaPolicy> policiesToBeDeployed = new HashMap<>();
 
     /**
      * Set of policies to be undeployed.
      */
-    private Set<ToscaConceptIdentifier> policiesToBeUndeployed = new HashSet<>();
+    private final Set<ToscaConceptIdentifier> policiesToBeUndeployed = new HashSet<>();
+
+    /**
+     * User starting requests.
+     */
+    @Getter
+    private final String user;
 
     /**
      * Tracks policy deployment status so notifications can be generated.
      */
     private final DeploymentStatus deployStatus;
 
+    private final PolicyAuditManager auditManager;
+
+    private final ToscaServiceTemplateService toscaService;
+
+    private final PdpGroupService pdpGroupService;
 
     /**
      * Constructs the object.
      *
-     * @param dao DAO provider
-     */
-    public SessionData(PolicyModelsProvider dao) {
-        this.dao = dao;
-        this.deployStatus = makeDeploymentStatus(dao);
+     * @param user user triggering the request
+     * @param policyAuditService the policyAuditService
+     * @param policyStatusService the policyStatusService
+     * @param pdpGroupService the pdpGroupService
+     * @param toscaService the toscaService
+     */
+    public SessionData(String user, ToscaServiceTemplateService toscaService, PdpGroupService pdpGroupService,
+        PolicyStatusService policyStatusService, PolicyAuditService policyAuditService) {
+        this.toscaService = toscaService;
+        this.pdpGroupService = pdpGroupService;
+        this.deployStatus = makeDeploymentStatus(policyStatusService);
+        this.auditManager = makePolicyAuditManager(policyAuditService);
+        this.user = user;
     }
 
     /**
@@ -132,7 +151,7 @@ public class SessionData {
         ToscaPolicyType type = typeCache.get(desiredType);
         if (type == null) {
 
-            List<ToscaPolicyType> lst = dao.getPolicyTypeList(desiredType.getName(), desiredType.getVersion());
+            List<ToscaPolicyType> lst = toscaService.getPolicyTypeList(desiredType.getName(), desiredType.getVersion());
             if (lst.isEmpty()) {
                 return null;
             }
@@ -157,10 +176,10 @@ public class SessionData {
         ToscaPolicy policy = policyCache.get(desiredPolicy);
         if (policy == null) {
             ToscaTypedEntityFilterBuilder<ToscaPolicy> filterBuilder =
-                    ToscaTypedEntityFilter.<ToscaPolicy>builder().name(desiredPolicy.getName());
+                ToscaTypedEntityFilter.<ToscaPolicy>builder().name(desiredPolicy.getName());
             setPolicyFilterVersion(filterBuilder, desiredPolicy.getVersion());
 
-            List<ToscaPolicy> lst = dao.getFilteredPolicyList(filterBuilder.build());
+            List<ToscaPolicy> lst = toscaService.getFilteredPolicyList(filterBuilder.build());
             if (lst.isEmpty()) {
                 return null;
             }
@@ -220,7 +239,7 @@ public class SessionData {
         }
 
         logger.info("add update and state-change {} {} {} policies={}", update.getName(), update.getPdpGroup(),
-                update.getPdpSubgroup(), update.getPolicies().size());
+                update.getPdpSubgroup(), update.getPoliciesToBeDeployed().size());
         pdpRequests.put(update.getName(), Pair.of(update, change));
     }
 
@@ -231,7 +250,7 @@ public class SessionData {
      */
     public void addUpdate(PdpUpdate update) {
         logger.info("add update {} {} {} policies={}", update.getName(), update.getPdpGroup(), update.getPdpSubgroup(),
-                update.getPolicies().size());
+                update.getPoliciesToBeDeployed().size());
         pdpRequests.compute(update.getName(), (name, data) -> Pair.of(update, (data == null ? null : data.getRight())));
     }
 
@@ -325,7 +344,7 @@ public class SessionData {
 
         GroupData data = groupCache.get(name);
         if (data == null) {
-            List<PdpGroup> lst = dao.getPdpGroups(name);
+            List<PdpGroup> lst = pdpGroupService.getPdpGroups(name);
             if (lst.isEmpty()) {
                 logger.info("unknown group {}", name);
                 return null;
@@ -349,9 +368,8 @@ public class SessionData {
      *
      * @param type desired policy type
      * @return the active groups supporting the given policy
-     * @throws PfModelException if an error occurred
      */
-    public List<PdpGroup> getActivePdpGroupsByPolicyType(ToscaConceptIdentifier type) throws PfModelException {
+    public List<PdpGroup> getActivePdpGroupsByPolicyType(ToscaConceptIdentifier type) {
         /*
          * Cannot use computeIfAbsent() because the enclosed code throws an unchecked exception and handling that would
          * obfuscate the code too much, thus disabling the sonar.
@@ -361,7 +379,7 @@ public class SessionData {
             PdpGroupFilter filter = PdpGroupFilter.builder().policyTypeList(Collections.singletonList(type))
                     .groupState(PdpState.ACTIVE).build();
 
-            List<PdpGroup> groups = dao.getFilteredPdpGroups(filter);
+            List<PdpGroup> groups = pdpGroupService.getFilteredPdpGroups(filter);
 
             data = groups.stream().map(this::addGroup).collect(Collectors.toList());
             type2groups.put(type, data);
@@ -373,7 +391,7 @@ public class SessionData {
     /**
      * Gets the list of policies to be deployed to the PDPs.
      *
-     * @returns a list of policies to be deployed
+     * @return a list of policies to be deployed
      */
     public List<ToscaPolicy> getPoliciesToBeDeployed() {
         return new LinkedList<>(this.policiesToBeDeployed.values());
@@ -382,7 +400,7 @@ public class SessionData {
     /**
      * Gets the list of policies to be undeployed from the PDPs.
      *
-     * @returns a list of policies to be undeployed
+     * @return a list of policies to be undeployed
      */
     public List<ToscaConceptIdentifier> getPoliciesToBeUndeployed() {
         return new LinkedList<>(this.policiesToBeUndeployed);
@@ -412,17 +430,15 @@ public class SessionData {
      * Update the DB with the changes.
      *
      * @param notification notification to which to add policy status
-     *
-     * @throws PfModelException if an error occurred
      */
-    public void updateDb(PolicyNotification notification) throws PfModelException {
+    public void updateDb(PolicyNotification notification) {
         // create new groups
         List<GroupData> created = groupCache.values().stream().filter(GroupData::isNew).collect(Collectors.toList());
         if (!created.isEmpty()) {
             if (logger.isInfoEnabled()) {
                 created.forEach(group -> logger.info("creating DB group {}", group.getGroup().getName()));
             }
-            dao.createPdpGroups(created.stream().map(GroupData::getGroup).collect(Collectors.toList()));
+            pdpGroupService.createPdpGroups(created.stream().map(GroupData::getGroup).collect(Collectors.toList()));
         }
 
         // update existing groups
@@ -432,9 +448,12 @@ public class SessionData {
             if (logger.isInfoEnabled()) {
                 updated.forEach(group -> logger.info("updating DB group {}", group.getGroup().getName()));
             }
-            dao.updatePdpGroups(updated.stream().map(GroupData::getGroup).collect(Collectors.toList()));
+            pdpGroupService.updatePdpGroups(updated.stream().map(GroupData::getGroup).collect(Collectors.toList()));
         }
 
+        // send audits records to DB
+        auditManager.saveRecordsToDb();
+
         // flush deployment status records to the DB
         deployStatus.flush(notification);
     }
@@ -443,11 +462,10 @@ public class SessionData {
      * Deletes a group from the DB, immediately (i.e., without caching the request to be executed later).
      *
      * @param group the group to be deleted
-     * @throws PfModelException if an error occurred
      */
-    public void deleteGroupFromDb(PdpGroup group) throws PfModelException {
+    public void deleteGroupFromDb(PdpGroup group) {
         logger.info("deleting DB group {}", group.getName());
-        dao.deletePdpGroup(group.getName());
+        pdpGroupService.deletePdpGroup(group.getName());
     }
 
     /**
@@ -459,12 +477,13 @@ public class SessionData {
      * @param pdpType PDP type (i.e., PdpSubGroup) containing the PDP of interest
      * @throws PfModelException if an error occurred
      */
-    protected void trackDeploy(ToscaPolicy policy, Collection<String> pdps, String pdpGroup,
-            String pdpType) throws PfModelException {
+    protected void trackDeploy(ToscaPolicy policy, Collection<String> pdps, String pdpGroup, String pdpType)
+            throws PfModelException {
         ToscaConceptIdentifier policyId = policy.getIdentifier();
         policiesToBeDeployed.put(policyId, policy);
 
         addData(policyId, pdps, pdpGroup, pdpType, true);
+        auditManager.addDeploymentAudit(policyId, pdpGroup, pdpType, user);
     }
 
     /**
@@ -479,7 +498,9 @@ public class SessionData {
     protected void trackUndeploy(ToscaConceptIdentifier policyId, Collection<String> pdps, String pdpGroup,
             String pdpType) throws PfModelException {
         policiesToBeUndeployed.add(policyId);
+
         addData(policyId, pdps, pdpGroup, pdpType, false);
+        auditManager.addUndeploymentAudit(policyId, pdpGroup, pdpType, user);
     }
 
     /**
@@ -508,7 +529,11 @@ public class SessionData {
 
     // these may be overridden by junit tests
 
-    protected DeploymentStatus makeDeploymentStatus(PolicyModelsProvider dao) {
-        return new DeploymentStatus(dao);
+    protected DeploymentStatus makeDeploymentStatus(PolicyStatusService policyStatusService) {
+        return new DeploymentStatus(policyStatusService);
+    }
+
+    protected PolicyAuditManager makePolicyAuditManager(PolicyAuditService policyAuditService) {
+        return new PolicyAuditManager(policyAuditService);
     }
 }