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.ArrayList;
32 import java.util.Base64;
33 import java.util.List;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
38 import org.apache.commons.fileupload.FileItem;
39 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
40 import org.apache.commons.fileupload.servlet.ServletFileUpload;
41 import org.apache.commons.io.IOUtils;
42 import org.json.JSONObject;
43 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
44 import org.openecomp.policy.common.logging.flexlogger.Logger;
45 import org.openecomp.policy.controller.CreateClosedLoopFaultController;
46 import org.openecomp.policy.controller.CreateDcaeMicroServiceController;
47 import org.openecomp.policy.controller.CreateFirewallController;
48 import org.openecomp.policy.controller.PolicyController;
49 import org.openecomp.policy.rest.XACMLRestProperties;
50 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
51 import org.openecomp.policy.rest.dao.CommonClassDao;
52 import org.openecomp.policy.rest.jpa.PolicyVersion;
53 import org.openecomp.policy.utils.PolicyUtils;
54 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
55 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
56 import org.openecomp.portalsdk.core.web.support.UserUtils;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.http.HttpEntity;
59 import org.springframework.http.HttpHeaders;
60 import org.springframework.http.HttpMethod;
61 import org.springframework.http.HttpStatus;
62 import org.springframework.http.ResponseEntity;
63 import org.springframework.web.bind.annotation.RequestMapping;
64 import org.springframework.web.bind.annotation.RequestMethod;
65 import org.springframework.web.bind.annotation.RestController;
66 import org.springframework.web.client.HttpClientErrorException;
67 import org.springframework.web.client.RestTemplate;
68 import org.springframework.web.servlet.ModelAndView;
70 import com.att.research.xacml.util.XACMLProperties;
71 import com.fasterxml.jackson.databind.DeserializationFeature;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectMapper;
74 import com.fasterxml.jackson.databind.SerializationFeature;
78 public class PolicyRestController extends RestrictedBaseController{
80 private static final Logger LOGGER = FlexLogger.getLogger(PolicyRestController.class);
82 private String boundary = null;
85 CommonClassDao commonClassDao;
87 @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
88 public ModelAndView policyCreationController(HttpServletRequest request, HttpServletResponse response) throws Exception{
90 String userId = UserUtils.getUserSession(request).getOrgUserId();
91 ObjectMapper mapper = new ObjectMapper();
92 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
93 JsonNode root = mapper.readTree(request.getReader());
95 PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
97 if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
98 policyData.isEditPolicy = true;
100 if(root.get("policyData").get("model").get("path").size() != 0){
102 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
103 dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
105 if(policyData.isEditPolicy){
106 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
108 policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", ""));
111 String domain = root.get("policyData").get("model").get("name").toString();
112 if(domain.contains("/")){
113 domain = domain.substring(0, domain.lastIndexOf("/")).replace("/", File.separator);
115 domain = domain.replace("\"", "");
116 policyData.setDomainDir(domain);
119 if(policyData.getConfigPolicyType() != null){
120 if(policyData.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")){
121 CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
122 policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
123 }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Firewall Config")){
124 CreateFirewallController fwController = new CreateFirewallController();
125 policyData = fwController.setDataToPolicyRestAdapter(policyData);
126 }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Micro Service")){
127 CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
128 policyData = msController.setDataToPolicyRestAdapter(policyData, root);
132 policyData.setUserId(userId);
135 String body = PolicyUtils.objectToJsonString(policyData);
136 String uri = request.getRequestURI();
137 ResponseEntity<?> responseEntity = sendToPAP(body, uri, request, HttpMethod.POST);
138 if(responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
139 result = "PolicyExists";
141 result = responseEntity.getBody().toString();
142 String policyName = responseEntity.getHeaders().get("policyName").get(0).toString();
143 if(policyData.isEditPolicy){
144 if(result.equalsIgnoreCase("success")){
145 PolicyNotificationMail email = new PolicyNotificationMail();
146 String mode = "EditPolicy";
147 String watchPolicyName = policyName.replace(".xml", "");
148 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf(".")+1);
149 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf(".")).replace(".", File.separator);
150 String policyVersionName = watchPolicyName.replace(".", File.separator);
151 watchPolicyName = watchPolicyName + "." + version + ".xml";
152 PolicyVersion entityItem = new PolicyVersion();
153 entityItem.setPolicyName(policyVersionName);
154 entityItem.setActiveVersion(Integer.parseInt(version));
155 entityItem.setModifiedBy(userId);
156 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
162 response.setCharacterEncoding("UTF-8");
163 response.setContentType("application / json");
164 request.setCharacterEncoding("UTF-8");
166 PrintWriter out = response.getWriter();
167 String responseString = mapper.writeValueAsString(result);
168 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
169 out.write(j.toString());
175 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpServletRequest request, HttpMethod method) throws Exception{
176 String papUrl = PolicyController.papUrl;
177 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
178 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
179 LOGGER.info("User Id is " + papID + "Pass is: " + papPass);
181 Base64.Encoder encoder = Base64.getEncoder();
182 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
183 HttpHeaders headers = new HttpHeaders();
184 headers.set("Authorization", "Basic " + encoding);
185 headers.set("Content-Type", "application/json");
187 RestTemplate restTemplate = new RestTemplate();
188 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
189 ResponseEntity<?> result = null;
190 HttpClientErrorException exception = null;
193 result = ((ResponseEntity<?>) restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class));
195 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
196 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
197 if(e.getMessage().equals("409 Conflict")){
198 return (ResponseEntity<?>) ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
201 if(exception != null && exception.getStatusCode()!=null){
202 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
203 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
204 LOGGER.error(message);
205 throw new Exception(message, exception);
207 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
208 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
209 LOGGER.error(message);
210 throw new Exception(message, exception);
212 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
213 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
214 LOGGER.error(message);
215 throw new Exception(message, exception);
217 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
218 LOGGER.error(message);
219 throw new Exception(message, exception);
224 private String callPAP(HttpServletRequest request, HttpServletResponse response, String method, String uri){
225 String papUrl = PolicyController.papUrl;
226 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
227 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
228 LOGGER.info("User Id is " + papID + "Pass is: " + papPass);
230 Base64.Encoder encoder = Base64.getEncoder();
231 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
232 HttpHeaders headers = new HttpHeaders();
233 headers.set("Authorization", "Basic " + encoding);
234 headers.set("Content-Type", "application/json");
237 HttpURLConnection connection = null;
238 List<FileItem> items;
239 FileItem item = null;
241 if(uri.contains("import_dictionary")){
243 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
245 file = new File(item.getName());
246 String newFile = file.toString();
247 uri = uri +"&dictionaryName="+newFile;
248 } catch (Exception e2) {
249 LOGGER.error("Exception Occured while calling PAP with import dictionary request"+e2);
254 URL url = new URL(papUrl + uri);
255 connection = (HttpURLConnection)url.openConnection();
256 connection.setRequestMethod(method);
257 connection.setUseCaches(false);
258 connection.setInstanceFollowRedirects(false);
259 connection.setRequestProperty("Authorization", "Basic " + encoding);
260 connection.setDoOutput(true);
261 connection.setDoInput(true);
263 if(!uri.contains("searchPolicy?action=delete&")){
265 if(!(uri.endsWith("set_BRMSParamData") || uri.contains("import_dictionary"))){
266 connection.setRequestProperty("Content-Type","application/json");
267 ObjectMapper mapper = new ObjectMapper();
268 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
269 JsonNode root = null;
271 root = mapper.readTree(request.getReader());
272 }catch (Exception e1) {
273 LOGGER.error("Exception Occured while calling PAP"+e1);
276 ObjectMapper mapper1 = new ObjectMapper();
277 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
279 Object obj = mapper1.treeToValue(root, Object.class);
280 String json = mapper1.writeValueAsString(obj);
282 Object content = new ByteArrayInputStream(json.getBytes());
284 if (content instanceof InputStream) {
285 // send current configuration
286 try (OutputStream os = connection.getOutputStream()) {
287 int count = IOUtils.copy((InputStream) content, os);
288 if (LOGGER.isDebugEnabled()) {
289 LOGGER.debug("copied to output, bytes=" + count);
294 if(uri.endsWith("set_BRMSParamData")){
295 connection.setRequestProperty("Content-Type","application/json");
296 try (OutputStream os = connection.getOutputStream()) {
297 IOUtils.copy((InputStream) request.getInputStream(), os);
300 boundary = "===" + System.currentTimeMillis() + "===";
301 connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
302 try (OutputStream os = connection.getOutputStream()) {
304 IOUtils.copy((InputStream) item.getInputStream(), os);
311 connection.connect();
313 int responseCode = connection.getResponseCode();
314 if(responseCode == 200){
315 // get the response content into a String
316 String responseJson = null;
317 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
318 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
319 scanner.useDelimiter("\\A");
320 responseJson = scanner.hasNext() ? scanner.next() : "";
322 LOGGER.info("JSON response from PAP: " + responseJson);
326 } catch (Exception e) {
327 LOGGER.error("Exception Occured"+e);
334 if (connection != null) {
336 // For some reason trying to get the inputStream from the connection
337 // throws an exception rather than returning null when the InputStream does not exist.
338 InputStream is = null;
340 is = connection.getInputStream();
341 } catch (Exception e1) {
348 } catch (IOException ex) {
349 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
351 connection.disconnect();
357 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
358 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
359 String uri = request.getRequestURI().replace("/getDictionary", "");
360 String body = sendToPAP(null, uri, request, HttpMethod.GET).getBody().toString();
361 response.getWriter().write(body);
364 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
365 public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
366 String uri = request.getRequestURI().replace("/saveDictionary", "");
367 if(uri.contains("import_dictionary")){
368 String userId = UserUtils.getUserSession(request).getOrgUserId();
369 uri = uri+ "?userId=" +userId;
371 String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
372 response.getWriter().write(body);
376 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
377 public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
378 String uri = request.getRequestURI().replace("/deleteDictionary", "");
379 String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
380 response.getWriter().write(body);
384 @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
385 public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
386 Object resultList = null;
387 String uri = request.getRequestURI();
388 String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
389 if(body.contains("CouldNotConnectException")){
390 List<String> data = new ArrayList<>();
391 data.add("Elastic Search Server is down");
394 JSONObject json = new JSONObject(body);
395 resultList = json.get("policyresult");
398 response.setCharacterEncoding("UTF-8");
399 response.setContentType("application / json");
400 PrintWriter out = response.getWriter();
401 JSONObject j = new JSONObject("{result: " + resultList + "}");
402 out.write(j.toString());
406 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
407 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
408 Object resultList = null;
409 String uri = request.getRequestURI()+"?action=search";
410 String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
412 JSONObject json = new JSONObject(body);
414 resultList = json.get("policyresult");
416 List<String> data = new ArrayList<>();
417 data.add("Elastic Search Server is down");
421 response.setCharacterEncoding("UTF-8");
422 response.setContentType("application / json");
423 request.setCharacterEncoding("UTF-8");
425 PrintWriter out = response.getWriter();
426 JSONObject j = new JSONObject("{result: " + resultList + "}");
427 out.write(j.toString());
431 public void deleteElasticData(String fileName){
432 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
433 callPAP(null, null, "POST", uri.trim());