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=========================================================
21 package org.openecomp.policy.controller;
25 import java.io.FileInputStream;
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.io.PrintWriter;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.text.DateFormat;
32 import java.text.ParseException;
33 import java.text.SimpleDateFormat;
34 import java.util.Date;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.LinkedHashMap;
38 import java.util.List;
40 import java.util.UUID;
42 import javax.json.Json;
43 import javax.json.JsonReader;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
47 import org.json.JSONObject;
48 import org.openecomp.policy.adapter.ClosedLoopPMBody;
49 import org.openecomp.policy.adapter.PolicyAdapter;
50 import org.openecomp.policy.admin.PolicyNotificationMail;
51 import org.openecomp.policy.admin.RESTfulPAPEngine;
52 import org.openecomp.policy.dao.PolicyVersionDao;
53 import org.openecomp.policy.dao.RuleAlgorithmsDao;
54 import org.openecomp.policy.dao.WatchPolicyNotificationDao;
55 import org.openecomp.policy.elk.client.PolicyElasticSearchController;
56 import org.openecomp.policy.rest.jpa.PolicyVersion;
57 import org.openecomp.policy.rest.jpa.RuleAlgorithms;
58 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
59 import org.openecomp.portalsdk.core.web.support.UserUtils;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.stereotype.Controller;
62 import org.springframework.web.bind.annotation.RequestMapping;
63 import org.springframework.web.servlet.ModelAndView;
65 import com.att.research.xacml.api.XACML3;
66 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
67 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
68 import com.fasterxml.jackson.databind.DeserializationFeature;
69 import com.fasterxml.jackson.databind.JsonNode;
70 import com.fasterxml.jackson.databind.ObjectMapper;
71 import com.google.common.base.Joiner;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
82 public class CreateClosedLoopPMController extends RestrictedBaseController{
84 private static RuleAlgorithmsDao ruleAlgorithmsDao;
85 private static PolicyVersionDao policyVersionDao;
86 private static WatchPolicyNotificationDao policyNotificationDao;
89 private CreateClosedLoopPMController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){
90 CreateClosedLoopPMController.policyVersionDao = policyVersionDao;
91 CreateClosedLoopPMController.ruleAlgorithmsDao = ruleAlgorithmsDao;
92 CreateClosedLoopPMController.policyNotificationDao = policyNotificationDao;
95 public CreateClosedLoopPMController(){}
97 protected PolicyAdapter policyAdapter = null;
98 private String ruleID = "";
100 public String newPolicyID() {
101 return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"),
102 PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID());
105 @RequestMapping(value={"/policyController/save_PMPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
106 public ModelAndView savePMPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
108 String userId = UserUtils.getUserIdFromCookie(request);
109 RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine();
110 ObjectMapper mapper = new ObjectMapper();
111 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
112 JsonNode root = mapper.readTree(request.getReader());
113 PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class);
115 if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
116 policyData.isEditPolicy = true;
118 if(root.get("policyData").get("model").get("path").size() != 0){
120 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
121 dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
123 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
125 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
128 if (policyData.getTtlDate()==null){
129 policyData.setTtlDate("NA");
131 String dateTTL = policyData.getTtlDate();
132 String newDate = convertDate(dateTTL);
133 policyData.setTtlDate(newDate);
137 int highestVersion = 0;
138 int descriptionVersion = 0;
139 //get the highest version of policy from policy version table.
140 //getting the sub scope domain where the policy is created or updated
141 String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_PM_" + policyData.getPolicyName();
142 List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName);
143 if (policyVersionList.size() > 0) {
144 for(int i = 0; i < policyVersionList.size(); i++) {
145 PolicyVersion entityItem = policyVersionList.get(i);
146 if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
147 highestVersion = entityItem.getHigherVersion();
151 if(highestVersion != 0){
152 version = highestVersion;
153 descriptionVersion = highestVersion +1;
156 descriptionVersion = 1;
159 //set policy adapter values for Building JSON object containing policy data
160 String createdBy = "";
161 String modifiedBy = userId;
162 if(descriptionVersion == 1){
165 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
166 File policyPath = new File(policyName);
168 createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
169 } catch (IOException e) {
174 policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
177 if(policyData.getServiceTypePolicyName() != null){
178 policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString());
181 ObjectMapper jsonMapper = new ObjectMapper();
182 String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData());
183 jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\",");
184 jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType());
185 policyData.setJsonBody(jsonBody);
187 Map<String, String> successMap = new HashMap<String, String>();
189 //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
190 List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms();
191 for (int i = 0; i < ruleAlgorithmsList.size(); i++) {
192 RuleAlgorithms a = ruleAlgorithmsList.get(i);
193 if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) {
194 policyData.setRuleCombiningAlgId(a.getXacmlId());
199 if (policyData.isEditPolicy()){
200 //increment the version and set in policyAdapter
201 policyData.setVersion(String.valueOf(version));
202 policyData.setHighestVersion(version);
203 policyData.setPolicyID(this.newPolicyID());
204 policyData.setRuleID(ruleID);
205 successMap = engine.updatePolicyRequest(policyData);
207 //send it for policy creation
208 policyData.setVersion(String.valueOf(version));
209 policyData.setHighestVersion(version);
210 successMap = engine.createPolicyRequest(policyData);
214 if (successMap.containsKey("success")) {
215 // Add it into our tree
216 Path finalPolicyPath = null;
217 finalPolicyPath = Paths.get(successMap.get("success"));
218 PolicyElasticSearchController controller = new PolicyElasticSearchController();
219 controller.updateElk(finalPolicyPath.toString());
220 File file = finalPolicyPath.toFile();
222 String policyName = file.toString();
223 String removePath = policyName.substring(policyName.indexOf("repository")+11);
224 String removeXml = removePath.replace(".xml", "");
225 String removeExtension = removeXml.substring(0, removeXml.indexOf("."));
226 List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension);
227 if (versionList.size() > 0) {
228 for(int i = 0; i < versionList.size(); i++) {
229 PolicyVersion entityItem = versionList.get(i);
230 if(entityItem.getPolicyName().equals(removeExtension)){
231 version = entityItem.getHigherVersion() +1;
232 entityItem.setActiveVersion(version);
233 entityItem.setHigherVersion(version);
234 entityItem.setModifiedBy(userId);
235 policyVersionDao.update(entityItem);
236 if(policyData.isEditPolicy){
237 PolicyNotificationMail email = new PolicyNotificationMail();
238 String mode = "EditPolicy";
239 String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
240 email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao);
245 PolicyVersion entityItem = new PolicyVersion();
246 entityItem.setActiveVersion(version);
247 entityItem.setHigherVersion(version);
248 entityItem.setPolicyName(removeExtension);
249 entityItem.setCreatedBy(userId);
250 entityItem.setModifiedBy(userId);
251 policyVersionDao.Save(entityItem);
255 response.setCharacterEncoding("UTF-8");
256 response.setContentType("application / json");
257 request.setCharacterEncoding("UTF-8");
259 PrintWriter out = response.getWriter();
260 String responseString = mapper.writeValueAsString(successMap);
261 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
262 out.write(j.toString());
266 response.setCharacterEncoding("UTF-8");
267 request.setCharacterEncoding("UTF-8");
268 PrintWriter out = response.getWriter();
269 out.write(e.getMessage());
274 private String convertDate(String dateTTL) {
275 String formateDate = null;
276 String[] date = dateTTL.split("T");
277 String[] parts = date[0].split("-");
279 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
283 public void PrePopulateClosedLoopPMPolicyData(PolicyAdapter policyAdapter) {
284 if (policyAdapter.getPolicyData() instanceof PolicyType) {
285 Object policyData = policyAdapter.getPolicyData();
286 PolicyType policy = (PolicyType) policyData;
287 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
288 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") +3 , policyAdapter.getPolicyName().lastIndexOf("."));
289 policyAdapter.setPolicyName(policyNameValue);
290 String description = "";
292 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
294 description = policy.getDescription();
296 policyAdapter.setPolicyDescription(description);
297 // Get the target data under policy.
298 TargetType target = policy.getTarget();
299 if (target != null) {
300 // Under target we have AnyOFType
301 List<AnyOfType> anyOfList = target.getAnyOf();
302 if (anyOfList != null) {
303 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
304 while (iterAnyOf.hasNext()) {
305 AnyOfType anyOf = iterAnyOf.next();
306 // Under AnyOFType we have AllOFType
307 List<AllOfType> allOfList = anyOf.getAllOf();
308 if (allOfList != null) {
309 Iterator<AllOfType> iterAllOf = allOfList.iterator();
310 while (iterAllOf.hasNext()) {
311 AllOfType allOf = iterAllOf.next();
312 // Under AllOFType we have Match
313 List<MatchType> matchList = allOf.getMatch();
314 if (matchList != null) {
316 Iterator<MatchType> iterMatch = matchList.iterator();
317 while (matchList.size()>1 && iterMatch.hasNext()) {
318 MatchType match = iterMatch.next();
320 // Under the match we have attributevalue and
321 // attributeDesignator. So,finally down to the actual attribute.
323 AttributeValueType attributeValue = match.getAttributeValue();
324 String value = (String) attributeValue.getContent().get(0);
326 // First match in the target is EcompName, so set that value.
328 policyAdapter.setEcompName(value);
332 policyAdapter.setRiskType(value);
336 policyAdapter.setRiskLevel(value);
340 policyAdapter.setGuard(value);
343 if (index == 4 && !value.contains("NA")){
344 String newDate = convertDate(value, true);
345 policyAdapter.setTtlDate(newDate);
348 LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>();
349 String key = "serviceTypePolicyName";
350 serviceTypePolicyName1.put(key, value);
351 policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1);
361 String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+"."+ policyAdapter.getOldPolicyFileName() + ".";
362 policyAdapter.setConfigBodyPath(jsonBodyName);
363 readClosedLoopJSONFile(policyAdapter);
367 private String convertDate(String dateTTL, boolean portalType) {
368 String formateDate = null;
373 parts = dateTTL.split("-");
374 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
376 date = dateTTL.split("T");
377 parts = date[0].split("-");
378 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
383 protected String readClosedLoopJSONFile(PolicyAdapter policyAdapter) {
384 String fileLocation = null;
385 String fileName = policyAdapter.getConfigBodyPath();
386 if (fileName != null ) {
387 fileLocation = PolicyController.getConfigHome();
389 if (fileLocation == null) {
393 File dir = new File(fileLocation);
394 File[] listOfFiles = dir.listFiles();
395 for (File file : listOfFiles) {
396 if (file.isFile() && file.getName().contains(fileName)) {
397 FileInputStream inputStream = null;
398 String location = file.toString();
400 inputStream = new FileInputStream(location);
401 } catch (FileNotFoundException e) {
404 if (location.endsWith("json")) {
405 JsonReader jsonReader = null;
406 jsonReader = Json.createReader(inputStream);
407 ObjectMapper mapper = new ObjectMapper();
409 ClosedLoopPMBody closedLoopBody = mapper.readValue(jsonReader.read().toString(), ClosedLoopPMBody.class);
410 policyAdapter.setJsonBodyData(closedLoopBody);
411 } catch (IOException e) {
413 /*logger.error("JSON Body Mapping Error");*/