2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.openecomp.policy.admin;
22 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.io.PrintWriter;
28 import java.net.HttpURLConnection;
30 import java.nio.charset.StandardCharsets;
31 import java.util.Base64;
32 import java.util.List;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
37 import org.apache.commons.fileupload.FileItem;
38 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
39 import org.apache.commons.fileupload.servlet.ServletFileUpload;
40 import org.apache.commons.io.IOUtils;
41 import org.json.JSONObject;
42 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
43 import org.openecomp.policy.common.logging.flexlogger.Logger;
44 import org.openecomp.policy.controller.CreateClosedLoopFaultController;
45 import org.openecomp.policy.controller.CreateDcaeMicroServiceController;
46 import org.openecomp.policy.controller.CreateFirewallController;
47 import org.openecomp.policy.controller.PolicyController;
48 import org.openecomp.policy.rest.XACMLRestProperties;
49 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
50 import org.openecomp.policy.rest.dao.CommonClassDao;
51 import org.openecomp.policy.rest.jpa.PolicyVersion;
52 import org.openecomp.policy.utils.PolicyUtils;
53 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
54 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
55 import org.openecomp.portalsdk.core.web.support.UserUtils;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.http.HttpEntity;
58 import org.springframework.http.HttpHeaders;
59 import org.springframework.http.HttpMethod;
60 import org.springframework.http.HttpStatus;
61 import org.springframework.http.ResponseEntity;
62 import org.springframework.web.bind.annotation.RequestMapping;
63 import org.springframework.web.bind.annotation.RequestMethod;
64 import org.springframework.web.bind.annotation.RestController;
65 import org.springframework.web.client.HttpClientErrorException;
66 import org.springframework.web.client.RestTemplate;
67 import org.springframework.web.servlet.ModelAndView;
69 import com.att.research.xacml.util.XACMLProperties;
70 import com.fasterxml.jackson.databind.DeserializationFeature;
71 import com.fasterxml.jackson.databind.JsonNode;
72 import com.fasterxml.jackson.databind.ObjectMapper;
73 import com.fasterxml.jackson.databind.SerializationFeature;
77 public class PolicyRestController extends RestrictedBaseController{
79 private static final Logger LOGGER = FlexLogger.getLogger(PolicyRestController.class);
81 private String boundary = null;
84 CommonClassDao commonClassDao;
86 @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
87 public ModelAndView policyCreationController(HttpServletRequest request, HttpServletResponse response) throws Exception{
89 String userId = UserUtils.getUserSession(request).getOrgUserId();
90 ObjectMapper mapper = new ObjectMapper();
91 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
92 JsonNode root = mapper.readTree(request.getReader());
94 PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
95 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
96 if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
97 policyData.isEditPolicy = true;
99 if(policyData.getConfigPolicyType() != null){
100 if(policyData.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")){
101 CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
102 policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
103 }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Firewall Config")){
104 CreateFirewallController fwController = new CreateFirewallController();
105 policyData = fwController.setDataToPolicyRestAdapter(policyData);
106 }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Micro Service")){
107 CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
108 policyData = msController.setDataToPolicyRestAdapter(policyData, root);
112 policyData.setUserId(userId);
114 if(root.get("policyData").get("model").get("path").size() != 0){
116 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
117 dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
119 if(policyData.isEditPolicy){
120 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
122 policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", ""));
125 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
128 String body = PolicyUtils.objectToJsonString(policyData);
129 String uri = request.getRequestURI();
130 ResponseEntity<?> responseEntity = sendToPAP(body, uri, request, HttpMethod.POST);
131 if(responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
132 result = "PolicyExists";
134 result = responseEntity.getBody().toString();
135 String policyName = responseEntity.getHeaders().get("policyName").get(0).toString();
136 if(policyData.isEditPolicy){
137 if(result.equalsIgnoreCase("success")){
138 PolicyNotificationMail email = new PolicyNotificationMail();
139 String mode = "EditPolicy";
140 String watchPolicyName = policyName.replace(".xml", "");
141 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf(".")+1);
142 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf(".")).replace(".", File.separator);
143 String policyVersionName = watchPolicyName.replace(".", File.separator);
144 watchPolicyName = watchPolicyName + "." + version + ".xml";
145 PolicyVersion entityItem = new PolicyVersion();
146 entityItem.setPolicyName(policyVersionName);
147 entityItem.setActiveVersion(Integer.parseInt(version));
148 entityItem.setModifiedBy(userId);
149 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
155 response.setCharacterEncoding("UTF-8");
156 response.setContentType("application / json");
157 request.setCharacterEncoding("UTF-8");
159 PrintWriter out = response.getWriter();
160 String responseString = mapper.writeValueAsString(result);
161 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
162 out.write(j.toString());
168 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpServletRequest request, HttpMethod method) throws Exception{
169 String papUrl = PolicyController.papUrl;
170 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
171 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
172 LOGGER.info("User Id is " + papID + "Pass is: " + papPass);
174 Base64.Encoder encoder = Base64.getEncoder();
175 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
176 HttpHeaders headers = new HttpHeaders();
177 headers.set("Authorization", "Basic " + encoding);
178 headers.set("Content-Type", "application/json");
180 RestTemplate restTemplate = new RestTemplate();
181 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
182 ResponseEntity<?> result = null;
183 HttpClientErrorException exception = null;
186 result = ((ResponseEntity<?>) restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class));
188 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
189 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
190 if(e.getMessage().equals("409 Conflict")){
191 return (ResponseEntity<?>) ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
194 if(exception != null && exception.getStatusCode()!=null){
195 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
196 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
197 LOGGER.error(message);
198 throw new Exception(message, exception);
200 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
201 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
202 LOGGER.error(message);
203 throw new Exception(message, exception);
205 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
206 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
207 LOGGER.error(message);
208 throw new Exception(message, exception);
210 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
211 LOGGER.error(message);
212 throw new Exception(message, exception);
217 private String callPAP(HttpServletRequest request, HttpServletResponse response, String method, String uri){
218 String papUrl = PolicyController.papUrl;
219 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
220 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
221 LOGGER.info("User Id is " + papID + "Pass is: " + papPass);
223 Base64.Encoder encoder = Base64.getEncoder();
224 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
225 HttpHeaders headers = new HttpHeaders();
226 headers.set("Authorization", "Basic " + encoding);
227 headers.set("Content-Type", "application/json");
230 HttpURLConnection connection = null;
231 List<FileItem> items;
232 FileItem item = null;
234 if(uri.contains("import_dictionary")){
236 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
238 file = new File(item.getName());
239 String newFile = file.toString();
240 uri = uri +"&dictionaryName="+newFile;
241 } catch (Exception e2) {
242 e2.printStackTrace();
247 URL url = new URL(papUrl + uri);
248 connection = (HttpURLConnection)url.openConnection();
249 connection.setRequestMethod(method);
250 connection.setUseCaches(false);
251 connection.setInstanceFollowRedirects(false);
252 connection.setRequestProperty("Authorization", "Basic " + encoding);
253 connection.setDoOutput(true);
254 connection.setDoInput(true);
256 if(!uri.contains("searchPolicy")){
257 if(!(uri.endsWith("set_BRMSParamData") || uri.contains("import_dictionary"))){
258 connection.setRequestProperty("Content-Type","application/json");
259 ObjectMapper mapper = new ObjectMapper();
260 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
261 JsonNode root = null;
263 root = mapper.readTree(request.getReader());
264 }catch (Exception e1) {
265 e1.printStackTrace();
268 ObjectMapper mapper1 = new ObjectMapper();
269 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
271 Object obj = mapper1.treeToValue(root, Object.class);
272 String json = mapper1.writeValueAsString(obj);
274 Object content = new ByteArrayInputStream(json.getBytes());
276 if (content != null && (content instanceof InputStream)) {
277 // send current configuration
278 try (OutputStream os = connection.getOutputStream()) {
279 int count = IOUtils.copy((InputStream) content, os);
280 if (LOGGER.isDebugEnabled()) {
281 LOGGER.debug("copied to output, bytes=" + count);
286 if(uri.endsWith("set_BRMSParamData")){
287 connection.setRequestProperty("Content-Type","application/json");
288 try (OutputStream os = connection.getOutputStream()) {
289 IOUtils.copy((InputStream) request.getInputStream(), os);
292 boundary = "===" + System.currentTimeMillis() + "===";
293 connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
294 try (OutputStream os = connection.getOutputStream()) {
295 IOUtils.copy((InputStream) item.getInputStream(), os);
301 connection.connect();
303 int responseCode = connection.getResponseCode();
304 if(responseCode == 200){
305 // get the response content into a String
306 String responseJson = null;
307 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
308 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
309 scanner.useDelimiter("\\A");
310 responseJson = scanner.hasNext() ? scanner.next() : "";
312 LOGGER.info("JSON response from PAP: " + responseJson);
316 } catch (Exception e) {
324 if (connection != null) {
326 // For some reason trying to get the inputStream from the connection
327 // throws an exception rather than returning null when the InputStream does not exist.
328 InputStream is = null;
330 is = connection.getInputStream();
331 } catch (Exception e1) {
338 } catch (IOException ex) {
339 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
341 connection.disconnect();
347 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
348 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
349 String uri = request.getRequestURI().replace("/getDictionary", "");
350 String body = sendToPAP(null, uri, request, HttpMethod.GET).getBody().toString();
351 response.getWriter().write(body);
354 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
355 public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
356 String uri = request.getRequestURI().replace("/saveDictionary", "");
357 if(uri.contains("import_dictionary")){
358 String userId = UserUtils.getUserSession(request).getOrgUserId();
359 uri = uri+ "?userId=" +userId;
361 String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
362 response.getWriter().write(body);
366 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
367 public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
368 String uri = request.getRequestURI().replace("/deleteDictionary", "");
369 String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
370 response.getWriter().write(body);
374 public void deleteElasticData(String fileName){
375 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
376 callPAP(null, null, "POST", uri.trim());