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.onap.policy.pap.xacml.rest.components;
24 import java.io.IOException;
25 import java.io.PrintWriter;
27 import java.net.URISyntaxException;
28 import java.nio.charset.Charset;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.HashMap;
35 import org.apache.commons.io.FilenameUtils;
36 import org.onap.policy.common.logging.eelf.MessageCodes;
37 import org.onap.policy.common.logging.eelf.PolicyLogger;
38 import org.onap.policy.common.logging.flexlogger.FlexLogger;
39 import org.onap.policy.common.logging.flexlogger.Logger;
40 import org.onap.policy.rest.adapter.PolicyRestAdapter;
42 import com.att.research.xacml.api.pap.PAPException;
43 import com.att.research.xacml.std.IdentifierImpl;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
59 public class ClosedLoopPolicy extends Policy {
61 private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class);
63 public ClosedLoopPolicy() {
67 public ClosedLoopPolicy(PolicyRestAdapter policyAdapter){
68 this.policyAdapter = policyAdapter;
71 //save configuration of the policy based on the policyname
72 private void saveConfigurations(String policyName, String jsonBody) {
74 String body = jsonBody;
77 //Remove the trapMaxAge in Verification Signature
78 body = body.replace(",\"trapMaxAge\":null", "");
80 LOGGER.debug("No Trap Max Age in JSON body", e);
82 this.policyAdapter.setJsonBody(body);
83 } catch (Exception e) {
84 LOGGER.error("Exception Occured"+e);
87 if(policyName.endsWith(".xml")){
88 policyName = policyName.replace(".xml", "");
90 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator+ policyName +".json");
94 } catch (Exception e) {
95 LOGGER.error("Exception Occured while writing Configuration Data"+e);
99 //Utility to read json data from the existing file to a string
100 static String readFile(String path, Charset encoding) throws IOException {
102 byte[] encoded = Files.readAllBytes(Paths.get(path));
103 return new String(encoded, encoding);
107 //create the configuration file based on the policy name on adding the extension as .json
108 private String getConfigFile(String filename) {
109 filename = FilenameUtils.removeExtension(filename);
110 if (filename.endsWith(".xml")) {
111 filename = filename.substring(0, filename.length() - 4);
113 filename = filename + ".json";
118 public Map<String, String> savePolicies() throws PAPException {
120 Map<String, String> successMap = new HashMap<>();
121 if(isPolicyExists()){
122 successMap.put("EXISTS", "This Policy already exist on the PAP");
126 if(!isPreparedToSave()){
130 // Until here we prepared the data and here calling the method to create xml.
131 Path newPolicyPath = null;
132 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
134 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
138 //This is the method for preparing the policy for saving. We have broken it out
139 //separately because the fully configured policy is used for multiple things
141 public boolean prepareToSave() throws PAPException{
143 if(isPreparedToSave()){
144 //we have already done this
149 String policyID = policyAdapter.getPolicyID();
150 version = policyAdapter.getHighestVersion();
152 // Create the Instance for pojo, PolicyType object is used in marshalling.
153 if (policyAdapter.getPolicyType().equals("Config")) {
154 PolicyType policyConfig = new PolicyType();
156 policyConfig.setVersion(Integer.toString(version));
157 policyConfig.setPolicyId(policyID);
158 policyConfig.setTarget(new TargetType());
159 policyAdapter.setData(policyConfig);
161 policyName = policyAdapter.getNewFileName();
162 if (policyAdapter.getData() != null) {
163 // Save the Configurations file with the policy name with extention based on selection.
164 String jsonBody = policyAdapter.getJsonBody();
165 saveConfigurations(policyName, jsonBody);
167 // Make sure the filename ends with an extension
168 if (policyName.endsWith(".xml") == false) {
169 policyName = policyName + ".xml";
172 PolicyType faultPolicy = (PolicyType) policyAdapter.getData();
174 faultPolicy.setDescription(policyAdapter.getPolicyDescription());
176 faultPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
178 AllOfType allOfOne = new AllOfType();
179 String fileName = policyAdapter.getNewFileName();
180 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
181 if ((name == null) || (name.equals(""))) {
182 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
184 allOfOne.getMatch().add(createMatch("PolicyName", name));
185 AllOfType allOf = new AllOfType();
186 // Adding the matches to AllOfType element
188 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
189 // Match for riskType
190 allOf.getMatch().add(
191 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
192 // Match for riskLevel
193 allOf.getMatch().add(
194 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
195 // Match for riskguard
196 allOf.getMatch().add(
197 createDynamicMatch("guard", policyAdapter.getGuard()));
199 allOf.getMatch().add(
200 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
202 AnyOfType anyOf = new AnyOfType();
203 anyOf.getAllOf().add(allOfOne);
204 anyOf.getAllOf().add(allOf);
206 TargetType target = new TargetType();
207 ((TargetType) target).getAnyOf().add(anyOf);
208 // Adding the target to the policy element
209 faultPolicy.setTarget((TargetType) target);
211 RuleType rule = new RuleType();
212 rule.setRuleId(policyAdapter.getRuleID());
213 rule.setEffect(EffectType.PERMIT);
215 // Create Target in Rule
216 AllOfType allOfInRule = new AllOfType();
218 // Creating match for ACCESS in rule target
219 MatchType accessMatch = new MatchType();
220 AttributeValueType accessAttributeValue = new AttributeValueType();
221 accessAttributeValue.setDataType(STRING_DATATYPE);
222 accessAttributeValue.getContent().add("ACCESS");
223 accessMatch.setAttributeValue(accessAttributeValue);
224 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
225 URI accessURI = null;
227 accessURI = new URI(ACTION_ID);
228 } catch (URISyntaxException e) {
229 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating ACCESS URI");
231 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
232 accessAttributeDesignator.setDataType(STRING_DATATYPE);
233 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
234 accessMatch.setAttributeDesignator(accessAttributeDesignator);
235 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
237 // Creating Config Match in rule Target
238 MatchType closedMatch = new MatchType();
239 AttributeValueType closedAttributeValue = new AttributeValueType();
240 closedAttributeValue.setDataType(STRING_DATATYPE);
241 closedAttributeValue.getContent().add("Config");
242 closedMatch.setAttributeValue(closedAttributeValue);
243 AttributeDesignatorType closedAttributeDesignator = new AttributeDesignatorType();
244 URI closedURI = null;
246 closedURI = new URI(RESOURCE_ID);
247 } catch (URISyntaxException e) {
248 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating closed URI");
250 closedAttributeDesignator.setCategory(CATEGORY_RESOURCE);
251 closedAttributeDesignator.setDataType(STRING_DATATYPE);
252 closedAttributeDesignator.setAttributeId(new IdentifierImpl(closedURI).stringValue());
253 closedMatch.setAttributeDesignator(closedAttributeDesignator);
254 closedMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
256 allOfInRule.getMatch().add(accessMatch);
257 allOfInRule.getMatch().add(closedMatch);
259 AnyOfType anyOfInRule = new AnyOfType();
260 anyOfInRule.getAllOf().add(allOfInRule);
262 TargetType targetInRule = new TargetType();
263 targetInRule.getAnyOf().add(anyOfInRule);
265 rule.setTarget(targetInRule);
266 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
268 faultPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
269 policyAdapter.setPolicyData(faultPolicy);
272 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
275 setPreparedToSave(true);
279 // Data required for Advice part is setting here.
280 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
281 AdviceExpressionsType advices = new AdviceExpressionsType();
282 AdviceExpressionType advice = new AdviceExpressionType();
283 advice.setAdviceId("faultID");
284 advice.setAppliesTo(EffectType.PERMIT);
286 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
287 assignment1.setAttributeId("type");
288 assignment1.setCategory(CATEGORY_RESOURCE);
289 assignment1.setIssuer("");
291 AttributeValueType configNameAttributeValue = new AttributeValueType();
292 configNameAttributeValue.setDataType(STRING_DATATYPE);
293 configNameAttributeValue.getContent().add("Configuration");
294 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
296 advice.getAttributeAssignmentExpression().add(assignment1);
297 // For Config file Url if configurations are provided.
298 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
299 assignment2.setAttributeId("URLID");
300 assignment2.setCategory(CATEGORY_RESOURCE);
301 assignment2.setIssuer("");
303 AttributeValueType AttributeValue = new AttributeValueType();
304 AttributeValue.setDataType(URI_DATATYPE);
305 String content = CONFIG_URL +"/Config/" + getConfigFile(policyName);
306 System.out.println("URL value :" + content);
307 AttributeValue.getContent().add(content);
308 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
310 advice.getAttributeAssignmentExpression().add(assignment2);
311 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
312 assignment3.setAttributeId("PolicyName");
313 assignment3.setCategory(CATEGORY_RESOURCE);
314 assignment3.setIssuer("");
316 AttributeValueType attributeValue3 = new AttributeValueType();
317 attributeValue3.setDataType(STRING_DATATYPE);
318 fileName = FilenameUtils.removeExtension(fileName);
319 fileName = fileName + ".xml";
320 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
321 if ((name == null) || (name.equals(""))) {
322 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
324 attributeValue3.getContent().add(name);
325 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
326 advice.getAttributeAssignmentExpression().add(assignment3);
328 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
329 assignment4.setAttributeId("VersionNumber");
330 assignment4.setCategory(CATEGORY_RESOURCE);
331 assignment4.setIssuer("");
333 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
334 configNameAttributeValue4.setDataType(STRING_DATATYPE);
335 configNameAttributeValue4.getContent().add(Integer.toString(version));
336 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
338 advice.getAttributeAssignmentExpression().add(assignment4);
340 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
341 assignment5.setAttributeId("matching:" + ONAPID);
342 assignment5.setCategory(CATEGORY_RESOURCE);
343 assignment5.setIssuer("");
345 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
346 configNameAttributeValue5.setDataType(STRING_DATATYPE);
347 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
348 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
350 advice.getAttributeAssignmentExpression().add(assignment5);
353 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
354 assignment6.setAttributeId("RiskType");
355 assignment6.setCategory(CATEGORY_RESOURCE);
356 assignment6.setIssuer("");
358 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
359 configNameAttributeValue6.setDataType(STRING_DATATYPE);
360 configNameAttributeValue6.getContent().add(policyAdapter.getRiskType());
361 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
363 advice.getAttributeAssignmentExpression().add(assignment6);
365 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
366 assignment7.setAttributeId("RiskLevel");
367 assignment7.setCategory(CATEGORY_RESOURCE);
368 assignment7.setIssuer("");
370 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
371 configNameAttributeValue7.setDataType(STRING_DATATYPE);
372 configNameAttributeValue7.getContent().add(policyAdapter.getRiskLevel());
373 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
375 advice.getAttributeAssignmentExpression().add(assignment7);
377 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
378 assignment8.setAttributeId("guard");
379 assignment8.setCategory(CATEGORY_RESOURCE);
380 assignment8.setIssuer("");
382 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
383 configNameAttributeValue8.setDataType(STRING_DATATYPE);
384 configNameAttributeValue8.getContent().add(policyAdapter.getGuard());
385 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
387 advice.getAttributeAssignmentExpression().add(assignment8);
389 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
390 assignment9.setAttributeId("TTLDate");
391 assignment9.setCategory(CATEGORY_RESOURCE);
392 assignment9.setIssuer("");
394 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
395 configNameAttributeValue9.setDataType(STRING_DATATYPE);
396 configNameAttributeValue9.getContent().add(policyAdapter.getTtlDate());
397 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
399 advice.getAttributeAssignmentExpression().add(assignment9);
403 advices.getAdviceExpression().add(advice);
408 public Object getCorrectPolicyDataObject() {
409 return policyAdapter.getPolicyData();