aboutsummaryrefslogtreecommitdiffstats
path: root/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
blob: 56d882fb4660bdfbd67bcef107f12aba521ecd0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/*-
 * ============LICENSE_START=======================================================
 * ONAP Policy Engine
 * ================================================================================
 * Copyright (C) 2017, 2019 AT&T Intellectual Property. 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.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.controller;

import com.att.research.xacml.api.pap.PAPException;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.Getter;
import lombok.Setter;
import org.json.JSONObject;
import org.onap.policy.admin.RESTfulPAPEngine;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.model.PDPGroupContainer;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
import org.onap.policy.xacml.std.pap.StdPDP;
import org.onap.policy.xacml.std.pap.StdPDPGroup;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.JsonMessage;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping({"/"})
public class PDPController extends RestrictedBaseController {
    private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class);

    protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
    private PDPGroupContainer container;

    private static String SUPERADMIN = "super-admin";
    private static String SUPEREDITOR = "super-editor";
    private static String SUPERGUEST = "super-guest";

    private Set<OnapPDPGroup> groupsData;

    private boolean junit = false;

    private PolicyController policyController;

    public PolicyController getPolicyController() {
        return policyController;
    }

    public void setPolicyController(PolicyController policyController) {
        this.policyController = policyController;
    }

    public synchronized void refreshGroups(HttpServletRequest request) {
        synchronized (this.groups) {
            this.groups.clear();
            try {
                PolicyController controller = getPolicyControllerInstance();
                Set<PDPPolicy> filteredPolicies = new HashSet<>();
                Set<String> scopes;
                List<String> roles;
                String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId();
                List<Object> userRoles = controller.getRoles(userId);
                Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
                roles = pair.u;
                scopes = pair.t;

                if (!junit && controller.getPapEngine() == null) {
                    setPAPEngine(request);
                }
                if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
                    if (!junit) {
                        this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
                    } else {
                        this.groups.addAll(this.getGroupsData());
                    }
                } else {
                    if (!userRoles.isEmpty() && !scopes.isEmpty()) {
                        this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
                        List<OnapPDPGroup> tempGroups = new ArrayList<>();
                        if (!groups.isEmpty()) {
                            Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
                            while (pdpGroup.hasNext()) {
                                OnapPDPGroup group = pdpGroup.next();
                                Set<PDPPolicy> policies = group.getPolicies();
                                for (PDPPolicy policy : policies) {
                                    for (String scope : scopes) {
                                        scope = scope.replace(File.separator, ".");
                                        String policyName = policy.getId();
                                        if (policyName.contains(".Config_")) {
                                            policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
                                        } else if (policyName.contains(".Action_")) {
                                            policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
                                        } else if (policyName.contains(".Decision_")) {
                                            policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
                                        }
                                        if (policyName.startsWith(scope)) {
                                            filteredPolicies.add(policy);
                                        }
                                    }
                                }
                                pdpGroup.remove();
                                StdPDPGroup newGroup = (StdPDPGroup) group;
                                newGroup.setPolicies(filteredPolicies);
                                tempGroups.add(newGroup);
                            }
                            groups.clear();
                            groups = tempGroups;
                        }
                    }
                }
            } catch (PAPException e) {
                String message = "Unable to retrieve Groups from server: " + e;
                policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Pap Engine is Null" + message);
            }
        }
    }

    private void setPAPEngine(HttpServletRequest request) {
        String myRequestURL = request.getRequestURL().toString();
        try {
            //
            // Set the URL for the RESTful PAP Engine
            //
            PolicyController.setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
        } catch (Exception e) {
            policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP", e);
        }
    }

    @RequestMapping(
            value = {"/get_PDPGroupData"},
            method = {org.springframework.web.bind.annotation.RequestMethod.GET},
            produces = MediaType.APPLICATION_JSON_VALUE)
    public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            refreshGroups(request);
            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
            JSONObject j = new JSONObject(msg);
            response.getWriter().write(j.toString());
        } catch (Exception e) {
            policyLogger.error(
                    XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while retrieving the PDP Group data" + e);
        }
    }

    @RequestMapping(
            value = {"/pdp_Group/save_pdp_group"},
            method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    public void savePDPGroup(HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            PolicyController controller = getPolicyControllerInstance();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonNode root = mapper.readTree(request.getReader());
            this.container = new PDPGroupContainer(controller.getPapEngine());

            String userId = UserUtils.getUserSession(request).getOrgUserId();
            policyLogger.info(
                    "****************************************Logging UserID for Save PDP Group Function*****************************************");
            policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpGroupData").toString());
            policyLogger.info(
                    "***************************************************************************************************************************");

            StdPDPGroup pdpGroupData = mapper
                    .readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
            try {
                if (pdpGroupData.getId() == null) {
                    this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription());
                } else {
                    this.container.updateGroup(pdpGroupData);
                }

            } catch (Exception e) {
                String message = "Unable to create Group.  Reason:\n" + e.getMessage();
                policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while creating the PDP Group"
                        + message + e);
            }

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application / json");
            request.setCharacterEncoding("UTF-8");

            PrintWriter out = response.getWriter();
            refreshGroups(request);
            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
            JSONObject j = new JSONObject(msg);
            out.write(j.toString());
        } catch (Exception e) {
            policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e);
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = null;
            try {
                request.setCharacterEncoding("UTF-8");
                out = response.getWriter();
                out.write(e.getMessage());
            } catch (Exception e1) {
                policyLogger
                        .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e1);
            }
        }
    }

    @RequestMapping(
            value = {"/pdp_Group/remove_pdp_group"},
            method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    public void removePDPGroup(HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonNode root = mapper.readTree(request.getReader());
            PolicyController controller = getPolicyControllerInstance();
            this.container = new PDPGroupContainer(controller.getPapEngine());

            String userId = UserUtils.getUserSession(request).getOrgUserId();
            policyLogger.info(
                    "****************************************Logging UserID for Remove PDP Group Function*****************************************");
            policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpGroupData").toString());
            policyLogger.info(
                    "*****************************************************************************************************************************");

            StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
            if ("Default".equals(pdpGroupData.getName())) {
                throw new UnsupportedOperationException("You can't remove the Default Group.");
            } else {
                this.container.removeGroup(pdpGroupData, null);
            }

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application / json");
            request.setCharacterEncoding("UTF-8");

            PrintWriter out = response.getWriter();

            refreshGroups(request);
            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
            JSONObject j = new JSONObject(msg);
            out.write(j.toString());
        } catch (Exception e) {
            policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e);
            PrintWriter out;
            try {
                response.setCharacterEncoding("UTF-8");
                request.setCharacterEncoding("UTF-8");
                out = response.getWriter();
                out.write(e.getMessage());
            } catch (Exception e1) {
                policyLogger.error("Exception Occured" + e1);
            }
        }
    }

    @RequestMapping(
            value = {"/pdp_Group/save_pdpTogroup"},
            method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonNode root = mapper.readTree(request.getReader());
            PolicyController controller = getPolicyControllerInstance();
            this.container = new PDPGroupContainer(controller.getPapEngine());
            String update = root.get("update").toString();
            PdpData pdpGroupData = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
            StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);

            String userId = UserUtils.getUserSession(request).getOrgUserId();
            policyLogger.info(
                    "****************************************Logging UserID while Saving  pdp in  PDP Group*****************************************");
            policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpInGroup").toString()
                    + "Active Group Data: " + root.get("activePDP").toString());
            policyLogger.info(
                    "*******************************************************************************************************************************");

            try {

                if (update.contains("false")) {
                    this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(),
                            pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
                } else {
                    this.container.updateGroup(activeGroupData);
                }
            } catch (Exception e) {
                String message = "Unable to create Group.  Reason:\n" + e.getMessage();
                policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Error Occured while Creating Pdp in PDP Group" + message + e);
            }

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application / json");
            request.setCharacterEncoding("UTF-8");

            PrintWriter out = response.getWriter();
            refreshGroups(request);
            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
            JSONObject j = new JSONObject(msg);
            out.write(j.toString());
        } catch (Exception e) {
            policyLogger
                    .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e);
            PrintWriter out;
            try {
                response.setCharacterEncoding("UTF-8");
                request.setCharacterEncoding("UTF-8");
                out = response.getWriter();
                out.write(e.getMessage());
            } catch (Exception e1) {
                policyLogger.error("Exception Occured" + e1);
            }
        }
    }

    @RequestMapping(
            value = {"/pdp_Group/remove_pdpFromGroup"},
            method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonNode root = mapper.readTree(request.getReader());
            PolicyController controller = getPolicyControllerInstance();
            this.container = new PDPGroupContainer(controller.getPapEngine());
            StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
            StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);

            String userId = UserUtils.getUserSession(request).getOrgUserId();
            policyLogger.info(
                    "****************************************Logging UserID while Removing  pdp from  PDP Group*****************************************");
            policyLogger.info("UserId:  " + userId + "Delete PDP Group Data:  " + root.get("data").toString()
                    + "Active Group Data: " + root.get("activePDP").toString());
            policyLogger.info(
                    "***********************************************************************************************************************************");

            this.container.removePDP(deletePdp, activeGroupData);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application / json");
            request.setCharacterEncoding("UTF-8");

            PrintWriter out = response.getWriter();
            refreshGroups(request);
            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
            JSONObject j = new JSONObject(msg);
            out.write(j.toString());
        } catch (Exception e) {
            policyLogger.error(
                    XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing Pdp from PDP Group" + e);
            PrintWriter out;
            try {
                response.setCharacterEncoding("UTF-8");
                request.setCharacterEncoding("UTF-8");
                out = response.getWriter();
                out.write(e.getMessage());
            } catch (Exception e1) {
                policyLogger.error("Exception Occured" + e1);
            }
        }
    }

    private PolicyController getPolicyControllerInstance() {
        return policyController != null ? getPolicyController() : new PolicyController();
    }

    public boolean isJunit() {
        return junit;
    }

    public void setJunit(boolean junit) {
        this.junit = junit;
    }

    public Set<OnapPDPGroup> getGroupsData() {
        return groupsData;
    }

    public void setGroupsData(Set<OnapPDPGroup> groupsData) {
        this.groupsData = groupsData;
    }
}

@Getter
@Setter
class PdpData {
    String id;
    int jmxPort;
    String name;
    String description;
}