Consolidate PolicyRestAdapter setup
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PolicyNotificationController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controller;
22
23 /*
24  *
25  * */
26 import com.fasterxml.jackson.databind.DeserializationFeature;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import com.fasterxml.jackson.databind.node.ArrayNode;
30
31 import java.io.File;
32 import java.io.IOException;
33 import java.util.List;
34
35 import javax.script.SimpleBindings;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38
39 import org.json.JSONObject;
40 import org.onap.policy.common.logging.flexlogger.FlexLogger;
41 import org.onap.policy.common.logging.flexlogger.Logger;
42 import org.onap.policy.rest.dao.CommonClassDao;
43 import org.onap.policy.rest.jpa.WatchPolicyNotificationTable;
44 import org.onap.policy.utils.PolicyUtils;
45 import org.onap.portalsdk.core.controller.RestrictedBaseController;
46 import org.onap.portalsdk.core.web.support.UserUtils;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.stereotype.Controller;
49 import org.springframework.web.bind.annotation.RequestMapping;
50 import org.springframework.web.servlet.ModelAndView;
51
52 @Controller
53 @RequestMapping({"/"})
54 public class PolicyNotificationController extends RestrictedBaseController {
55     private static Logger logger = FlexLogger.getLogger(PolicyNotificationController.class);
56
57     @Autowired
58     CommonClassDao commonClassDao;
59
60     /**
61      * watchPolicy.
62      *
63      * @param request HttpServletRequest
64      * @param response HttpServletResponse
65      * @return ModelAndView
66      * @throws IOException IOException
67      */
68     @RequestMapping(value = {"/watchPolicy"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
69     public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
70         StringBuilder path = new StringBuilder();
71         String responseValue = "";
72         try {
73             response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
74             request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
75             //
76             //
77             //
78             String userId = UserUtils.getUserSession(request).getOrgUserId();
79             logger.info("userid info: " + userId);
80             ObjectMapper mapper = new ObjectMapper();
81             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
82             JsonNode root = mapper.readTree(request.getReader());
83             String name = root.get("watchData").get("name").toString();
84             JsonNode pathList = root.get("watchData").get("path");
85             String finalName;
86             if (pathList.isArray()) {
87                 ArrayNode arrayNode = (ArrayNode) pathList;
88                 for (int i = 0; i < arrayNode.size(); i++) {
89                     JsonNode individualElement = arrayNode.get(i);
90                     if (i == 0) {
91                         path.append(individualElement.toString().replace("\"", "").trim());
92                     } else {
93                         path.append(File.separator + individualElement.toString().replace("\"", "").trim());
94                     }
95                 }
96             }
97
98             if (pathList.size() > 0) {
99                 finalName = path + File.separator + name.replace("\"", "").trim();
100             } else {
101                 finalName = name.replace("\"", "").trim();
102             }
103             if (finalName.contains("\\")) {
104                 finalName = finalName.replace("\\", "\\\\");
105             }
106             String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
107             SimpleBindings params = new SimpleBindings();
108             params.put("finalName", finalName);
109             params.put("userId", userId);
110             List<Object> watchList = commonClassDao.getDataByQuery(query, params);
111             if (watchList.isEmpty()) {
112                 if (finalName.contains("\\\\")) {
113                     finalName = finalName.replace("\\\\", File.separator);
114                 }
115                 WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
116                 watch.setPolicyName(finalName);
117                 watch.setLoginIds(userId);
118                 commonClassDao.save(watch);
119                 responseValue = "You have Subscribed Successfully";
120             } else {
121                 commonClassDao.delete(watchList.get(0));
122                 responseValue = "You have UnSubscribed Successfully";
123             }
124
125             response.setContentType(PolicyUtils.APPLICATION_JSON);
126
127             response.getWriter().write(new JSONObject("{watchData: "
128                     + mapper.writeValueAsString(responseValue) + "}").toString());
129         } catch (Exception e) {
130             logger.error("Error druing watchPolicy function " + e);
131             response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
132         }
133         return null;
134     }
135 }