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);
96 if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
97 policyData.isEditPolicy = true;
99 if(root.get("policyData").get("model").get("path").size() != 0){
101 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
102 dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
104 if(policyData.isEditPolicy){
105 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
107 policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", ""));
110 String domain = root.get("policyData").get("model").get("name").toString();
111 if(domain.contains("/")){
112 domain = domain.substring(0, domain.lastIndexOf("/")).replace("/", File.separator);
114 domain = domain.replace("\"", "");
115 policyData.setDomainDir(domain);
118 if(policyData.getConfigPolicyType() != null){
119 if(policyData.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")){
120 CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
121 policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
122 }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Firewall Config")){
123 CreateFirewallController fwController = new CreateFirewallController();
124 policyData = fwController.setDataToPolicyRestAdapter(policyData);
125 }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Micro Service")){
126 CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
127 policyData = msController.setDataToPolicyRestAdapter(policyData, root);
131 policyData.setUserId(userId);
134 String body = PolicyUtils.objectToJsonString(policyData);
135 String uri = request.getRequestURI();
136 ResponseEntity<?> responseEntity = sendToPAP(body, uri, request, HttpMethod.POST);
137 if(responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
138 result = "PolicyExists";
140 result = responseEntity.getBody().toString();
141 String policyName = responseEntity.getHeaders().get("policyName").get(0).toString();
142 if(policyData.isEditPolicy){
143 if(result.equalsIgnoreCase("success")){
144 PolicyNotificationMail email = new PolicyNotificationMail();
145 String mode = "EditPolicy";
146 String watchPolicyName = policyName.replace(".xml", "");
147 String version = watchPolicyName.substring(watchPolicyName.lastIndexOf(".")+1);
148 watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf(".")).replace(".", File.separator);
149 String policyVersionName = watchPolicyName.replace(".", File.separator);
150 watchPolicyName = watchPolicyName + "." + version + ".xml";
151 PolicyVersion entityItem = new PolicyVersion();
152 entityItem.setPolicyName(policyVersionName);
153 entityItem.setActiveVersion(Integer.parseInt(version));
154 entityItem.setModifiedBy(userId);
155 email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
161 response.setCharacterEncoding("UTF-8");
162 response.setContentType("application / json");
163 request.setCharacterEncoding("UTF-8");
165 PrintWriter out = response.getWriter();
166 String responseString = mapper.writeValueAsString(result);
167 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
168 out.write(j.toString());
174 private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpServletRequest request, HttpMethod method) throws Exception{
175 String papUrl = PolicyController.papUrl;
176 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
177 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
178 LOGGER.info("User Id is " + papID + "Pass is: " + papPass);
180 Base64.Encoder encoder = Base64.getEncoder();
181 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
182 HttpHeaders headers = new HttpHeaders();
183 headers.set("Authorization", "Basic " + encoding);
184 headers.set("Content-Type", "application/json");
186 RestTemplate restTemplate = new RestTemplate();
187 HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
188 ResponseEntity<?> result = null;
189 HttpClientErrorException exception = null;
192 result = ((ResponseEntity<?>) restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class));
194 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
195 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
196 if(e.getMessage().equals("409 Conflict")){
197 return (ResponseEntity<?>) ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
200 if(exception != null && exception.getStatusCode()!=null){
201 if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
202 String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
203 LOGGER.error(message);
204 throw new Exception(message, exception);
206 if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
207 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
208 LOGGER.error(message);
209 throw new Exception(message, exception);
211 if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
212 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
213 LOGGER.error(message);
214 throw new Exception(message, exception);
216 String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
217 LOGGER.error(message);
218 throw new Exception(message, exception);
223 private String callPAP(HttpServletRequest request, HttpServletResponse response, String method, String uri){
224 String papUrl = PolicyController.papUrl;
225 String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
226 String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
227 LOGGER.info("User Id is " + papID + "Pass is: " + papPass);
229 Base64.Encoder encoder = Base64.getEncoder();
230 String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
231 HttpHeaders headers = new HttpHeaders();
232 headers.set("Authorization", "Basic " + encoding);
233 headers.set("Content-Type", "application/json");
236 HttpURLConnection connection = null;
237 List<FileItem> items;
238 FileItem item = null;
240 if(uri.contains("import_dictionary")){
242 items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
244 file = new File(item.getName());
245 String newFile = file.toString();
246 uri = uri +"&dictionaryName="+newFile;
247 } catch (Exception e2) {
248 e2.printStackTrace();
253 URL url = new URL(papUrl + uri);
254 connection = (HttpURLConnection)url.openConnection();
255 connection.setRequestMethod(method);
256 connection.setUseCaches(false);
257 connection.setInstanceFollowRedirects(false);
258 connection.setRequestProperty("Authorization", "Basic " + encoding);
259 connection.setDoOutput(true);
260 connection.setDoInput(true);
262 if(!uri.contains("searchPolicy?action=delete&")){
264 if(!(uri.endsWith("set_BRMSParamData") || uri.contains("import_dictionary"))){
265 connection.setRequestProperty("Content-Type","application/json");
266 ObjectMapper mapper = new ObjectMapper();
267 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
268 JsonNode root = null;
270 root = mapper.readTree(request.getReader());
271 }catch (Exception e1) {
272 e1.printStackTrace();
275 ObjectMapper mapper1 = new ObjectMapper();
276 mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
278 Object obj = mapper1.treeToValue(root, Object.class);
279 String json = mapper1.writeValueAsString(obj);
281 Object content = new ByteArrayInputStream(json.getBytes());
283 if (content != null && (content instanceof InputStream)) {
284 // send current configuration
285 try (OutputStream os = connection.getOutputStream()) {
286 int count = IOUtils.copy((InputStream) content, os);
287 if (LOGGER.isDebugEnabled()) {
288 LOGGER.debug("copied to output, bytes=" + count);
293 if(uri.endsWith("set_BRMSParamData")){
294 connection.setRequestProperty("Content-Type","application/json");
295 try (OutputStream os = connection.getOutputStream()) {
296 IOUtils.copy((InputStream) request.getInputStream(), os);
299 boundary = "===" + System.currentTimeMillis() + "===";
300 connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
301 try (OutputStream os = connection.getOutputStream()) {
302 IOUtils.copy((InputStream) item.getInputStream(), os);
308 connection.connect();
310 int responseCode = connection.getResponseCode();
311 if(responseCode == 200){
312 // get the response content into a String
313 String responseJson = null;
314 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
315 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
316 scanner.useDelimiter("\\A");
317 responseJson = scanner.hasNext() ? scanner.next() : "";
319 LOGGER.info("JSON response from PAP: " + responseJson);
323 } catch (Exception e) {
331 if (connection != null) {
333 // For some reason trying to get the inputStream from the connection
334 // throws an exception rather than returning null when the InputStream does not exist.
335 InputStream is = null;
337 is = connection.getInputStream();
338 } catch (Exception e1) {
345 } catch (IOException ex) {
346 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
348 connection.disconnect();
354 @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
355 public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
356 String uri = request.getRequestURI().replace("/getDictionary", "");
357 String body = sendToPAP(null, uri, request, HttpMethod.GET).getBody().toString();
358 response.getWriter().write(body);
361 @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
362 public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
363 String uri = request.getRequestURI().replace("/saveDictionary", "");
364 if(uri.contains("import_dictionary")){
365 String userId = UserUtils.getUserSession(request).getOrgUserId();
366 uri = uri+ "?userId=" +userId;
368 String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
369 response.getWriter().write(body);
373 @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
374 public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
375 String uri = request.getRequestURI().replace("/deleteDictionary", "");
376 String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
377 response.getWriter().write(body);
381 @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
382 public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
383 String uri = request.getRequestURI()+"?action=search";
384 String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
385 JSONObject json = new JSONObject(body);
386 Object resultList = json.get("policyresult");
388 response.setCharacterEncoding("UTF-8");
389 response.setContentType("application / json");
390 request.setCharacterEncoding("UTF-8");
392 PrintWriter out = response.getWriter();
393 JSONObject j = new JSONObject("{result: " + resultList + "}");
394 out.write(j.toString());
398 public void deleteElasticData(String fileName){
399 String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
400 callPAP(null, null, "POST", uri.trim());