Use lombok in xacml-pdp
[policy/xacml-pdp.git] / main / src / main / java / org / onap / policy / pdpx / main / comm / XacmlPdpUpdatePublisher.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdpx.main.comm;
22
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import java.util.stream.Collectors;
29 import lombok.AllArgsConstructor;
30 import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient;
31 import org.onap.policy.models.pdp.concepts.PdpStatus;
32 import org.onap.policy.models.pdp.concepts.PdpUpdate;
33 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
34 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
35 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
36 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
37 import org.onap.policy.pdpx.main.XacmlState;
38 import org.onap.policy.pdpx.main.rest.XacmlPdpApplicationManager;
39 import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 @AllArgsConstructor
44 public class XacmlPdpUpdatePublisher {
45
46     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpUpdatePublisher.class);
47
48     private final TopicSinkClient client;
49     private final XacmlState state;
50     private final XacmlPdpApplicationManager appManager;
51
52     /**
53      * Handle the PDP Update message.
54      *
55      * @param message Incoming message
56      */
57     public void handlePdpUpdate(PdpUpdate message) {
58
59         // current data
60         Map<ToscaConceptIdentifier, ToscaPolicy> deployedPolicies = policyToMap(appManager.getToscaPolicies().keySet());
61
62         // incoming data
63         Map<ToscaConceptIdentifier, ToscaPolicy> toBeDeployedPolicies = policyToMap(message.getPoliciesToBeDeployed());
64         List<ToscaConceptIdentifier> toBeUndeployedIds =
65                         Optional.ofNullable(message.getPoliciesToBeUndeployed()).orElse(Collections.emptyList());
66
67         // Undeploy policies
68         for (ToscaConceptIdentifier policyId: toBeUndeployedIds) {
69             ToscaPolicy policy = deployedPolicies.get(policyId);
70             if (policy == null) {
71                 LOGGER.warn("attempt to undeploy policy that has not been previously deployed: {}", policyId);
72             } else if (toBeDeployedPolicies.containsKey(policyId)) {
73                 LOGGER.warn("not undeploying policy, as it also appears in the deployment list: {}", policyId);
74             } else {
75                 appManager.removeUndeployedPolicy(policy);
76             }
77         }
78
79         var errorMessage = new StringBuilder();
80         // Deploy a policy
81         // if deployed policies do not contain the incoming policy load it
82         for (ToscaPolicy policy : toBeDeployedPolicies.values()) {
83             if (!deployedPolicies.containsKey(policy.getIdentifier())) {
84                 try {
85                     appManager.loadDeployedPolicy(policy);
86                 } catch (XacmlApplicationException e) {
87                     // Failed to load policy, return error(s) to PAP
88                     LOGGER.error("Failed to load policy: {}", policy, e);
89                     errorMessage.append("Failed to load policy: " + policy + ": "
90                             + e.getMessage() + XacmlPolicyUtils.LINE_SEPARATOR);
91                 }
92             }
93         }
94
95         // update the policy count statistic
96         var stats = XacmlPdpStatisticsManager.getCurrent();
97         if (stats != null) {
98             stats.setTotalPolicyCount(appManager.getPolicyCount());
99         }
100
101         PdpStatus status = state.updateInternalState(message, errorMessage.toString());
102         LOGGER.debug("Returning current deployed policies: {} ", status.getPolicies());
103
104         sendPdpUpdate(status);
105     }
106
107     private Map<ToscaConceptIdentifier, ToscaPolicy> policyToMap(Collection<ToscaPolicy> policies) {
108         if (policies == null) {
109             return Collections.emptyMap();
110         }
111
112         return policies.stream().collect(Collectors.toMap(ToscaPolicy::getIdentifier, policy -> policy));
113     }
114
115     private void sendPdpUpdate(PdpStatus status) {
116         // Send PdpStatus Change to PAP
117         if (!client.send(status)) {
118             LOGGER.error("failed to send to topic sink {}", client.getTopic());
119         }
120     }
121 }