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;
24 import java.io.BufferedReader;
26 import java.io.FileNotFoundException;
27 import java.io.FileReader;
28 import java.io.IOException;
29 import java.io.PrintWriter;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.text.DateFormat;
33 import java.text.ParseException;
34 import java.text.SimpleDateFormat;
35 import java.util.ArrayList;
36 import java.util.Date;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.LinkedHashMap;
40 import java.util.List;
42 import java.util.UUID;
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46 import javax.xml.bind.JAXBElement;
48 //import org.apache.commons.logging.Log;
49 //import org.apache.commons.logging.LogFactory;
50 import org.json.JSONObject;
51 import org.openecomp.policy.adapter.PolicyAdapter;
52 import org.openecomp.policy.admin.PolicyNotificationMail;
53 import org.openecomp.policy.admin.RESTfulPAPEngine;
54 import org.openecomp.policy.dao.PolicyVersionDao;
55 import org.openecomp.policy.dao.RuleAlgorithmsDao;
56 import org.openecomp.policy.dao.WatchPolicyNotificationDao;
57 import org.openecomp.policy.elk.client.PolicyElasticSearchController;
58 import org.openecomp.policy.rest.jpa.PolicyVersion;
59 import org.openecomp.policy.rest.jpa.RuleAlgorithms;
60 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
61 import org.openecomp.portalsdk.core.web.support.UserUtils;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.stereotype.Controller;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.servlet.ModelAndView;
67 import com.att.research.xacml.api.XACML3;
68 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
69 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
70 import com.fasterxml.jackson.databind.DeserializationFeature;
71 import com.fasterxml.jackson.databind.JsonNode;
72 import com.fasterxml.jackson.databind.ObjectMapper;
73 import com.google.common.base.Joiner;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
84 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
86 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
87 import org.openecomp.policy.common.logging.flexlogger.Logger;
91 public class CreateBRMSRawController extends RestrictedBaseController {
93 private static final Logger logger = FlexLogger.getLogger(CreateBRMSRawController.class);
95 private static RuleAlgorithmsDao ruleAlgorithmsDao;
96 private static PolicyVersionDao policyVersionDao;
97 private static WatchPolicyNotificationDao policyNotificationDao;
100 private CreateBRMSRawController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){
101 CreateBRMSRawController.policyVersionDao = policyVersionDao;
102 CreateBRMSRawController.ruleAlgorithmsDao = ruleAlgorithmsDao;
103 CreateBRMSRawController.policyNotificationDao = policyNotificationDao;
106 public CreateBRMSRawController(){}
107 protected PolicyAdapter policyAdapter = null;
108 private ArrayList<Object> attributeList;
109 private String ruleID = "";
110 public String newPolicyID() {
111 return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"),
112 PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID());
117 @RequestMapping(value={"/policyController/save_BRMSRawPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
118 public ModelAndView saveBRMSRawPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
120 String userId = UserUtils.getUserIdFromCookie(request);
121 RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine();
122 ObjectMapper mapper = new ObjectMapper();
123 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
124 JsonNode root = mapper.readTree(request.getReader());
125 PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class);
127 if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
128 policyData.isEditPolicy = true;
130 if(root.get("policyData").get("model").get("path").size() != 0){
132 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
133 dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
135 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
137 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
140 if (policyData.getTtlDate()==null){
141 policyData.setTtlDate("NA");
143 String dateTTL = policyData.getTtlDate();
144 String newDate = convertDate(dateTTL);
145 policyData.setTtlDate(newDate);
149 int highestVersion = 0;
150 int descriptionVersion = 0;
151 //get the highest version of policy from policy version table.
152 //getting the sub scope domain where the policy is created or updated
153 String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_BRMS_Raw_" + policyData.getPolicyName();
154 List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName);
155 if (policyVersionList.size() > 0) {
156 for(int i = 0; i < policyVersionList.size(); i++) {
157 PolicyVersion entityItem = policyVersionList.get(i);
158 if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
159 highestVersion = entityItem.getHigherVersion();
163 if(highestVersion != 0){
164 version = highestVersion;
165 descriptionVersion = highestVersion +1;
168 descriptionVersion = 1;
171 //set policy adapter values for Building JSON object containing policy data
172 String createdBy = "";
173 String modifiedBy = userId;
174 if(descriptionVersion == 1){
177 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
178 File policyPath = new File(policyName);
180 createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
181 } catch (IOException e) {
186 policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
187 Map<String, String> successMap = new HashMap<String, String>();
188 Map<String, String> attributeMap = 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.getAttributes().size() > 0){
200 for(Object attribute : policyData.getAttributes()){
201 if(attribute instanceof LinkedHashMap<?, ?>){
202 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
203 String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
204 attributeMap.put(key, value);
210 policyData.setEcompName("DROOLS");
211 policyData.setConfigName("BRMS_RAW_RULE");
212 policyData.setDynamicFieldConfigAttributes(attributeMap);
213 if (policyData.isEditPolicy()){
214 //increment the version and set in policyAdapter
215 policyData.setVersion(String.valueOf(version));
216 policyData.setHighestVersion(version);
217 policyData.setPolicyID(this.newPolicyID());
218 policyData.setRuleID(ruleID);
219 successMap = engine.updatePolicyRequest(policyData);
221 //send it for policy creation
222 policyData.setVersion(String.valueOf(version));
223 policyData.setHighestVersion(version);
224 successMap = engine.createPolicyRequest(policyData);
227 if (successMap.containsKey("success")) {
228 // Add it into our tree
229 Path finalPolicyPath = null;
230 finalPolicyPath = Paths.get(successMap.get("success"));
231 PolicyElasticSearchController controller = new PolicyElasticSearchController();
232 controller.updateElk(finalPolicyPath.toString());
233 File file = finalPolicyPath.toFile();
235 String policyName = file.toString();
236 String removePath = policyName.substring(policyName.indexOf("repository")+11);
237 String removeXml = removePath.replace(".xml", "");
238 String removeExtension = removeXml.substring(0, removeXml.indexOf("."));
239 List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension);
240 if (versionList.size() > 0) {
241 for(int i = 0; i < versionList.size(); i++) {
242 PolicyVersion entityItem = versionList.get(i);
243 if(entityItem.getPolicyName().equals(removeExtension)){
244 version = entityItem.getHigherVersion() +1;
245 entityItem.setActiveVersion(version);
246 entityItem.setHigherVersion(version);
247 entityItem.setModifiedBy(userId);
248 policyVersionDao.update(entityItem);
249 if(policyData.isEditPolicy){
250 PolicyNotificationMail email = new PolicyNotificationMail();
251 String mode = "EditPolicy";
252 String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
253 email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao);
258 PolicyVersion entityItem = new PolicyVersion();
259 entityItem.setActiveVersion(version);
260 entityItem.setHigherVersion(version);
261 entityItem.setPolicyName(removeExtension);
262 entityItem.setCreatedBy(userId);
263 entityItem.setModifiedBy(userId);
264 policyVersionDao.Save(entityItem);
268 response.setCharacterEncoding("UTF-8");
269 response.setContentType("application / json");
270 request.setCharacterEncoding("UTF-8");
272 PrintWriter out = response.getWriter();
273 String responseString = mapper.writeValueAsString(successMap);
274 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
275 out.write(j.toString());
279 response.setCharacterEncoding("UTF-8");
280 request.setCharacterEncoding("UTF-8");
281 PrintWriter out = response.getWriter();
282 out.write(e.getMessage());
287 private String convertDate(String dateTTL) {
288 String formateDate = null;
289 String[] date = dateTTL.split("T");
290 String[] parts = date[0].split("-");
292 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
296 public void PrePopulateBRMSRawPolicyData(PolicyAdapter policyAdapter) {
297 attributeList = new ArrayList<Object>();
298 if (policyAdapter.getPolicyData() instanceof PolicyType) {
299 PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
300 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
301 // policy name value is the policy name without any prefix and
303 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") +9, policyAdapter.getPolicyName().lastIndexOf("."));
304 if (logger.isDebugEnabled()) {
305 logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
307 policyAdapter.setPolicyName(policyNameValue);
308 String description = "";
310 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
312 description = policy.getDescription();
314 policyAdapter.setPolicyDescription(description);
316 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
317 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
318 for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
319 if(attributeAssignment.getAttributeId().startsWith("key:")){
320 Map<String, String> attribute = new HashMap<String, String>();
321 String key = attributeAssignment.getAttributeId().replace("key:", "");
322 attribute.put("key", key);
323 JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
324 String value = (String) attributevalue.getValue().getContent().get(0);
325 attribute.put("value", value);
326 attributeList.add(attribute);
329 policyAdapter.setAttributes(attributeList);
331 String ruleConfigName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + ".";
332 policyAdapter.setConfigBodyPath(ruleConfigName);
333 // Get the target data under policy.
334 policyAdapter.setConfigBodyData(readFile(policyAdapter));
335 TargetType target = policy.getTarget();
336 if (target != null) {
337 // Under target we have AnyOFType
338 List<AnyOfType> anyOfList = target.getAnyOf();
339 if (anyOfList != null) {
340 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
341 while (iterAnyOf.hasNext()) {
342 AnyOfType anyOf = iterAnyOf.next();
343 // Under AnyOFType we have AllOFType
344 List<AllOfType> allOfList = anyOf.getAllOf();
345 if (allOfList != null) {
346 Iterator<AllOfType> iterAllOf = allOfList.iterator();
348 while (iterAllOf.hasNext()) {
349 AllOfType allOf = iterAllOf.next();
350 // Under AllOFType we have Match
351 List<MatchType> matchList = allOf.getMatch();
352 if (matchList != null) {
353 Iterator<MatchType> iterMatch = matchList.iterator();
354 while (iterMatch.hasNext()) {
355 MatchType match = iterMatch.next();
357 // Under the match we have attributevalue and
358 // attributeDesignator. So,finally down to the actual attribute.
360 AttributeValueType attributeValue = match.getAttributeValue();
361 String value = (String) attributeValue.getContent().get(0);
364 policyAdapter.setRiskType(value);
368 policyAdapter.setRiskLevel(value);
372 policyAdapter.setGuard(value);
374 if (index == 6 && !value.contains("NA")){
375 String newDate = convertDate(value, true);
376 policyAdapter.setTtlDate(newDate);
390 private String convertDate(String dateTTL, boolean portalType) {
391 String formateDate = null;
396 parts = dateTTL.split("-");
397 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
399 date = dateTTL.split("T");
400 parts = date[0].split("-");
401 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
406 // Here we are reading the configurations file
407 protected String readFile(PolicyAdapter policyAdapter) {
408 String fileLocation = null;
409 String fileName = policyAdapter.getConfigBodyPath();
410 if (fileName != null ) {
411 fileLocation = PolicyController.getConfigHome();
413 if (fileLocation == null) {
416 File dir = new File(fileLocation);
417 File[] listOfFiles = dir.listFiles();
418 for (File file : listOfFiles) {
419 if (file.isFile() && file.getName().contains(fileName) && file.toString().endsWith(".txt")) {
421 try (BufferedReader br = new BufferedReader(new FileReader(file))) {
422 StringBuilder sb = new StringBuilder();
423 String line = br.readLine();
424 while (line != null) {
427 line = br.readLine();
429 return sb.toString();
430 } catch (FileNotFoundException e) {
431 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage());
432 } catch (IOException e1) {
433 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e1.getMessage());