Consolidate PolicyRestAdapter setup
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / UpdateOthersPAPS.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2018-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.pap.xacml.rest;
22
23 import com.att.research.xacml.util.XACMLProperties;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25
26 import java.io.BufferedWriter;
27 import java.io.File;
28 import java.io.FileWriter;
29 import java.io.IOException;
30 import java.nio.charset.StandardCharsets;
31 import java.nio.file.Files;
32 import java.nio.file.Paths;
33 import java.util.Base64;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40
41 import org.json.JSONObject;
42 import org.onap.policy.common.logging.flexlogger.FlexLogger;
43 import org.onap.policy.common.logging.flexlogger.Logger;
44 import org.onap.policy.pap.xacml.rest.adapters.UpdateObjectData;
45 import org.onap.policy.pap.xacml.rest.components.Policy;
46 import org.onap.policy.pap.xacml.rest.util.JsonMessage;
47 import org.onap.policy.rest.XACMLRestProperties;
48 import org.onap.policy.rest.dao.CommonClassDao;
49 import org.onap.policy.rest.jpa.ActionBodyEntity;
50 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
51 import org.onap.policy.rest.jpa.PolicyDBDaoEntity;
52 import org.onap.policy.utils.PeCryptoUtils;
53 import org.onap.policy.xacml.api.XACMLErrorConstants;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.http.HttpEntity;
56 import org.springframework.http.HttpHeaders;
57 import org.springframework.http.HttpMethod;
58 import org.springframework.http.HttpStatus;
59 import org.springframework.stereotype.Controller;
60 import org.springframework.web.bind.annotation.RequestBody;
61 import org.springframework.web.bind.annotation.RequestMapping;
62 import org.springframework.web.bind.annotation.RequestMethod;
63 import org.springframework.web.bind.annotation.ResponseBody;
64 import org.springframework.web.client.HttpClientErrorException;
65 import org.springframework.web.client.RestTemplate;
66
67 @Controller
68 public class UpdateOthersPAPS {
69
70     private static final Logger policyLogger = FlexLogger.getLogger(UpdateOthersPAPS.class);
71
72     private static CommonClassDao commonClassDao;
73
74     private static final String contentType = "application/json";
75     private static String configType = ".Config_";
76     private static String actionType = ".Action_";
77     private static String error = "error";
78
79     public static CommonClassDao getCommonClassDao() {
80         return commonClassDao;
81     }
82
83     public static void setCommonClassDao(CommonClassDao commonClassDao) {
84         UpdateOthersPAPS.commonClassDao = commonClassDao;
85     }
86
87     @Autowired
88     private UpdateOthersPAPS(CommonClassDao commonClassDao) {
89         UpdateOthersPAPS.commonClassDao = commonClassDao;
90     }
91
92     public UpdateOthersPAPS() {
93         // Empty Constructor
94     }
95
96     @RequestMapping(value = "/notifyOtherPAPs", method = RequestMethod.POST)
97     public void notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response) {
98         Map<String, Object> model = new HashMap<>();
99         ObjectMapper mapper = new ObjectMapper();
100         UpdateObjectData body = new UpdateObjectData();
101         body.setAction(request.getParameter("action"));
102         body.setNewPolicyName(request.getParameter("newPolicyName"));
103         body.setOldPolicyName(request.getParameter("oldPolicyName"));
104
105         String currentPap = XACMLRestProperties.getProperty("xacml.rest.pap.url");
106         List<Object> getPAPUrls = commonClassDao.getData(PolicyDBDaoEntity.class);
107         if (getPAPUrls != null && !getPAPUrls.isEmpty()) {
108             for (int i = 0; i < getPAPUrls.size(); i++) {
109                 PolicyDBDaoEntity papId = (PolicyDBDaoEntity) getPAPUrls.get(i);
110                 String papUrl = papId.getPolicyDBDaoUrl();
111                 if (!papUrl.equals(currentPap)) {
112                     String userName = papId.getUsername();
113                     String password = papId.getPassword();
114                     Base64.Encoder encoder = Base64.getEncoder();
115                     String txt;
116                     try {
117                         PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
118                         txt = PeCryptoUtils.decrypt(password);
119                     } catch (Exception e) {
120                         policyLogger.debug(e);
121                         // if we can't decrypt, might as well try it anyway
122                         txt = password;
123                     }
124                     String encoding = encoder.encodeToString((userName + ":" + txt).getBytes(StandardCharsets.UTF_8));
125                     HttpHeaders headers = new HttpHeaders();
126                     headers.set("Authorization", "Basic " + encoding);
127                     headers.set("Content-Type", contentType);
128
129                     RestTemplate restTemplate = new RestTemplate();
130                     HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
131                     HttpClientErrorException exception = null;
132
133                     try {
134                         restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, requestEntity,
135                                 String.class);
136                     } catch (Exception e) {
137                         policyLogger.error(
138                                 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
139                         exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
140                         if ("409 Conflict".equals(e.getMessage())) {
141                             policyLogger.error(e.getMessage());
142                             response.addHeader(error, e.getMessage());
143                         }
144                     }
145                     if (exception != null && exception.getStatusCode() != null) {
146                         String message;
147                         if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
148                             message = XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":"
149                                     + "ERROR_AUTH_GET_PERM";
150                             policyLogger.error(message);
151                         } else if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
152                             message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":"
153                                     + exception.getResponseBodyAsString();
154                             policyLogger.error(message);
155                         } else if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
156                             message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl
157                                     + exception;
158                             policyLogger.error(message);
159                         } else {
160                             message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":"
161                                     + exception.getResponseBodyAsString();
162                             policyLogger.error(message);
163                         }
164                         model.put(papUrl, message);
165                     } else {
166                         model.put(papUrl, "Success");
167                     }
168                 }
169             }
170             JsonMessage msg;
171             try {
172                 msg = new JsonMessage(mapper.writeValueAsString(model));
173                 JSONObject j = new JSONObject(msg);
174                 response.getWriter().write(j.toString());
175             } catch (Exception e) {
176                 policyLogger.error("Exception Occured" + e);
177             }
178         }
179     }
180
181     @RequestMapping(value = "/updateConfiguration", method = RequestMethod.POST)
182     @ResponseBody
183     public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response) {
184         String action = data.getAction();
185         String newPolicyName = data.getNewPolicyName();
186         String oldPolicyName = data.getOldPolicyName();
187         try {
188             if ("rename".equals(action)) {
189                 if (oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)) {
190                     File file;
191                     if (oldPolicyName.contains(configType)) {
192                         file = new File(Policy.getConfigHome() + File.separator + oldPolicyName);
193                     } else {
194                         file = new File(Policy.getActionHome() + File.separator + oldPolicyName);
195                     }
196                     if (file.exists()) {
197                         File renamefile;
198                         if (oldPolicyName.contains(configType)) {
199                             renamefile = new File(Policy.getConfigHome() + File.separator + newPolicyName);
200                         } else {
201                             renamefile = new File(Policy.getActionHome() + File.separator + newPolicyName);
202                         }
203                         if (file.renameTo(renamefile)) {
204                             policyLogger.info("Policy has been renamed Successfully" + newPolicyName);
205                             response.addHeader("rename", "Success");
206                         } else {
207                             response.addHeader("rename", "Failure");
208                         }
209                     }
210                 }
211             } else if ("delete".equals(action)) {
212                 if (oldPolicyName.contains(configType)) {
213                     Files.deleteIfExists(Paths.get(Policy.getConfigHome() + File.separator + oldPolicyName));
214                 } else if (oldPolicyName.contains("Action_")) {
215                     Files.deleteIfExists(Paths.get(Policy.getActionHome() + File.separator + oldPolicyName));
216                 }
217             } else if ("clonePolicy".equals(action) || "exportPolicy".equals(action)) {
218                 if (newPolicyName.contains(configType)) {
219                     ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao
220                             .getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName);
221                     saveConfigurationData(configEntiy, newPolicyName);
222                 } else if (newPolicyName.contains(actionType)) {
223                     ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao
224                             .getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName);
225                     saveActionBodyData(actionEntiy, newPolicyName);
226                 }
227             }
228         } catch (IOException e) {
229             policyLogger.error("Exception Occured While updating Configuration" + e);
230         }
231     }
232
233     private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName) {
234         try (FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)) {
235             BufferedWriter bw = new BufferedWriter(fw);
236             bw.write(configEntiy.getConfigBody());
237             bw.close();
238         } catch (IOException e) {
239             policyLogger.error("Exception Occured While closing the File input stream" + e);
240         }
241     }
242
243     private void saveActionBodyData(ActionBodyEntity actionEntiy, String newPolicyName) {
244         try (FileWriter fw = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)) {
245             BufferedWriter bw = new BufferedWriter(fw);
246             bw.write(actionEntiy.getActionBody());
247             bw.close();
248         } catch (IOException e) {
249             policyLogger.error("Exception Occured While closing the File input stream" + e);
250         }
251     }
252 }