Merge "Decision BlackList Guard Enhancements"
[policy/engine.git] / ONAP-XACML / src / main / java / org / onap / policy / xacml / util / XACMLPolicyWriter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-XACML
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.policy.xacml.util;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.File;
26 import java.io.InputStream;
27 import java.io.OutputStream;
28 import java.nio.file.Files;
29 import java.nio.file.Path;
30 import java.util.Iterator;
31 import java.util.List;
32
33 import javax.xml.bind.JAXBContext;
34 import javax.xml.bind.JAXBElement;
35 import javax.xml.bind.JAXBException;
36 import javax.xml.bind.Marshaller;
37 import javax.xml.bind.Unmarshaller;
38
39 import org.onap.policy.common.logging.eelf.MessageCodes;
40 import org.onap.policy.common.logging.eelf.PolicyLogger;
41
42
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
57
58 /**
59  * Helper static class for policy writing.
60  * 
61  *
62  */
63 public class XACMLPolicyWriter {
64
65     /**
66      * Helper static class that does the work to write a policy set to a file on disk.
67      *
68      *
69      */
70     public static Path writePolicyFile(Path filename, PolicySetType policySet) {
71         JAXBElement<PolicySetType> policySetElement = new ObjectFactory().createPolicySet(policySet);
72         try {
73             JAXBContext context = JAXBContext.newInstance(PolicySetType.class);
74             Marshaller m = context.createMarshaller();
75             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
76             m.marshal(policySetElement, filename.toFile());
77
78             if (Files.exists(filename)) {
79                 return filename;
80             } else {
81                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "File does not exist after marshalling.");
82                 return null;
83             }
84
85         } catch (JAXBException e) {
86             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed");
87             return null;
88         }
89     }
90
91     /**
92      * Helper static class that does the work to write a policy set to an output stream.
93      *
94      *
95      */
96     public static void writePolicyFile(OutputStream os, PolicySetType policySet) {
97         JAXBElement<PolicySetType> policySetElement = new ObjectFactory().createPolicySet(policySet);
98         try {
99             JAXBContext context = JAXBContext.newInstance(PolicySetType.class);
100             Marshaller m = context.createMarshaller();
101             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
102             m.marshal(policySetElement, os);
103         } catch (JAXBException e) {
104             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed");
105         }
106     }
107
108     /**
109      * Helper static class that does the work to write a policy to a file on disk.
110      *
111      *
112      */
113     public static Path writePolicyFile(Path filename, PolicyType policy) {
114         JAXBElement<PolicyType> policyElement = new ObjectFactory().createPolicy(policy);
115         try {
116             JAXBContext context = JAXBContext.newInstance(PolicyType.class);
117             Marshaller m = context.createMarshaller();
118             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
119             m.marshal(policyElement, filename.toFile());
120
121             if (Files.exists(filename)) {
122                 return filename;
123             } else {
124                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "File does not exist after marshalling.");
125                 return null;
126             }
127
128         } catch (JAXBException e) {
129             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed");
130             return null;
131         }
132     }
133
134
135     /**
136      * Helper static class that does the work to write a policy to a file on disk.
137      *
138      *
139      */
140     public static InputStream getXmlAsInputStream(PolicyType policy) {
141         JAXBElement<PolicyType> policyElement = new ObjectFactory().createPolicy(policy);
142         try {
143             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
144             JAXBContext context = JAXBContext.newInstance(PolicyType.class);
145             Marshaller m = context.createMarshaller();
146             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
147             m.marshal(policyElement, byteArrayOutputStream);
148             return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
149         } catch (JAXBException e) {
150             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed");
151             throw new IllegalArgumentException("XACMLPolicyWriter writePolicyFile failed", e);
152         }
153     }
154     /**
155      * Helper static class that does the work to write a policy set to an output stream.
156      *
157      *
158      */
159     public static void writePolicyFile(OutputStream os, PolicyType policy) {
160         JAXBElement<PolicyType> policySetElement = new ObjectFactory().createPolicy(policy);
161         try {
162             JAXBContext context = JAXBContext.newInstance(PolicyType.class);
163             Marshaller m = context.createMarshaller();
164             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
165             m.marshal(policySetElement, os);
166         } catch (JAXBException e) {
167             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed");
168         }
169     }
170
171     @SuppressWarnings({ "unchecked", "rawtypes" })
172     public static String changeFileNameInXmlWhenRenamePolicy(Path filename) {
173
174         String extension = "";
175         String domain = null;
176         String repository = "repository";
177         if(filename.toString().contains("Config_")){
178             domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length()+1), filename.toString().indexOf("Config_"));
179         }else if(filename.toString().contains("Action_")){
180             domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length()+1), filename.toString().indexOf("Action_"));
181         }else if(filename.toString().contains("Decision_")){
182             domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.length()+1), filename.toString().indexOf("Decision_"));
183         }
184         if(domain.contains(File.separator)){
185             domain =    domain.replace(File.separator, ".");
186         }
187         try {
188             JAXBContext context = JAXBContext.newInstance(PolicyType.class);
189             Unmarshaller m = context.createUnmarshaller();
190             JAXBElement<PolicyType> policyElement = (JAXBElement<PolicyType>) m.unmarshal(filename.toFile());
191             PolicyType policyType = policyElement.getValue();
192             if (policyType != null) {
193                 TargetType targetType = policyType.getTarget();
194                 List<AnyOfType> anyOfTypes = targetType.getAnyOf();
195                 for( Iterator anyOfIte = anyOfTypes.iterator(); anyOfIte.hasNext(); ){
196                     AnyOfType anyOfType = (AnyOfType) anyOfIte.next();
197                     List<AllOfType> allOf = anyOfType.getAllOf();
198                     for( Iterator allOfIte = allOf.iterator(); allOfIte.hasNext(); ){
199                         AllOfType allOfType = (AllOfType) allOfIte.next();
200                         List<MatchType> match = allOfType.getMatch();
201                         for( Iterator matchIte = match.iterator(); matchIte.hasNext();) {
202                             MatchType  matchType = (MatchType) matchIte.next();
203                             if("PolicyName".equals(matchType.getAttributeDesignator().getAttributeId())){
204                                 AttributeValueType attributeValueType = matchType.getAttributeValue();
205                                 List<Object> contents = attributeValueType.getContent();
206                                 if (contents != null && !contents.isEmpty()) {
207                                     String tmp = filename.getFileName()+"";
208                                     String newName = tmp.substring(0, tmp.lastIndexOf("."));
209                                     attributeValueType.getContent().clear();
210                                     attributeValueType.getContent().add(domain + newName  + "." + "xml");
211                                 }
212                             }
213                         }
214                     }
215                 }
216                 if(filename.toString().contains("Config_") || filename.toString().contains("Action_")){
217                     List<Object> objects = policyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
218                     if (objects != null && !objects.isEmpty()) {
219                         for (Iterator ite = objects.iterator(); ite.hasNext();) {
220
221                             RuleType  ruleType = (RuleType ) ite.next();
222                             AdviceExpressionsType adviceExpressionsType = ruleType.getAdviceExpressions();
223                             if (adviceExpressionsType != null) {
224                                 List<AdviceExpressionType> adviceExpressionTypes = adviceExpressionsType.getAdviceExpression();
225                                 if (adviceExpressionTypes != null && !adviceExpressionTypes.isEmpty()) {
226                                     for (Iterator iterator = adviceExpressionTypes
227                                             .iterator(); iterator.hasNext();) {
228                                         AdviceExpressionType adviceExpressionType = (AdviceExpressionType) iterator
229                                                 .next();
230                                         if (adviceExpressionType.getAdviceId() != null && !"".equals(adviceExpressionType.getAdviceId()) && ("configID".equals(adviceExpressionType.getAdviceId())
231                                                 || "faultID".equals(adviceExpressionType.getAdviceId()) || "PMID".equals(adviceExpressionType.getAdviceId())||"firewallConfigID".equals(adviceExpressionType.getAdviceId()) || "OptimizationID".equals(adviceExpressionType.getAdviceId())
232                                                 || "MSID".equals(adviceExpressionType.getAdviceId())) || "GocID".equals(adviceExpressionType.getAdviceId())||"GocHPID".equals(adviceExpressionType.getAdviceId())||"BRMSRAWID".equals(adviceExpressionType.getAdviceId())
233                                                 || "BRMSPARAMID".equals(adviceExpressionType.getAdviceId())|| "HPSuppID".equals(adviceExpressionType.getAdviceId()) || "HPFlapID".equals(adviceExpressionType.getAdviceId()) || "HPOverID".equals(adviceExpressionType.getAdviceId()))
234                                         {
235                                             List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes = adviceExpressionType.getAttributeAssignmentExpression();
236                                             if (attributeAssignmentExpressionTypes != null && !attributeAssignmentExpressionTypes.isEmpty()) {
237                                                 for (Iterator iterator2 = attributeAssignmentExpressionTypes
238                                                         .iterator(); iterator2.hasNext();) {
239                                                     AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2
240                                                             .next();
241                                                     if ("URLID".equals(attributeAssignmentExpressionType.getAttributeId())) {
242                                                         JAXBElement<AttributeValueType> attributeValueType = (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType.getExpression();
243                                                         AttributeValueType attributeValueType1 = attributeValueType.getValue();
244                                                         String configUrl = "$URL";
245                                                         String urlVal = (String) attributeValueType1.getContent().get(0);
246                                                         String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim();
247                                                         extension = origExtension;
248                                                         attributeValueType1.getContent().clear();
249                                                         String txtFileName = filename.getFileName().toString();
250                                                         txtFileName = txtFileName.substring(0, txtFileName.lastIndexOf(".")+1) + origExtension;
251                                                         txtFileName = configUrl+ File.separator + "Config" + File.separator + domain + txtFileName;
252                                                         attributeValueType1.getContent().add(txtFileName);
253                                                     } else if ("PolicyName".equals(attributeAssignmentExpressionType.getAttributeId())) {
254                                                         JAXBElement<AttributeValueType> attributeValueType = (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType.getExpression();
255                                                         AttributeValueType attributeValueType1 = attributeValueType.getValue();
256                                                         List<Object> contents = attributeValueType1.getContent();
257                                                         if (contents != null && !contents.isEmpty()) {
258                                                             String tmp = filename.getFileName()+"";
259                                                             String newName = tmp.substring(0, tmp.lastIndexOf("."));
260                                                             attributeValueType1.getContent().clear();
261                                                             attributeValueType1.getContent().add(domain + newName + "." + "xml");
262                                                         }
263
264                                                     }
265
266                                                 }
267                                             }
268                                         }
269                                     }
270                                 }
271                             }
272                         }
273                         if (objects != null && !objects.isEmpty()) {
274                             for (Iterator ite1 = objects.iterator(); ite1.hasNext();) {
275
276                                 RuleType  ruleType1 = (RuleType ) ite1.next();
277                                 ObligationExpressionsType obligationExpressionsType = ruleType1.getObligationExpressions();
278                                 if (obligationExpressionsType != null) {
279                                     List<ObligationExpressionType> obligationExpressionType = obligationExpressionsType.getObligationExpression();
280                                     if (obligationExpressionType != null && !obligationExpressionType.isEmpty()) {
281                                         for (Iterator iterator = obligationExpressionType
282                                                 .iterator(); iterator.hasNext();) {
283                                             ObligationExpressionType obligationExpressionTypes = (ObligationExpressionType) iterator
284                                                     .next();
285                                             if (obligationExpressionTypes.getObligationId() != null && !"".equals(obligationExpressionTypes.getObligationId())) {
286                                                 List<AttributeAssignmentExpressionType> attributeAssignmentExpressionTypes = obligationExpressionTypes.getAttributeAssignmentExpression();
287                                                 if (attributeAssignmentExpressionTypes != null && !attributeAssignmentExpressionTypes.isEmpty()) {
288                                                     for (Iterator iterator2 = attributeAssignmentExpressionTypes
289                                                             .iterator(); iterator2.hasNext();) {
290                                                         AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2
291                                                                 .next();
292                                                         if ("body".equals(attributeAssignmentExpressionType.getAttributeId())) {
293                                                             JAXBElement<AttributeValueType> attributeValueType = (JAXBElement<AttributeValueType>) attributeAssignmentExpressionType.getExpression();
294                                                             AttributeValueType attributeValueType1 = attributeValueType.getValue();
295                                                             String configUrl = "$URL";
296                                                             String urlVal = (String) attributeValueType1.getContent().get(0);
297                                                             String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim();
298                                                             extension = "json";
299                                                             attributeValueType1.getContent().clear();
300                                                             String txtFileName = filename.getFileName().toString();
301                                                             txtFileName = txtFileName.substring(0, txtFileName.lastIndexOf(".")+1) + origExtension;
302                                                             txtFileName = configUrl+ File.separator + "Action" + File.separator + domain + txtFileName;
303                                                             attributeValueType1.getContent().add(txtFileName);
304                                                         }
305
306                                                     }
307                                                 }
308
309                                             }
310
311                                         }
312                                     }
313                                 }
314                             }
315                         }
316                     }
317                 }
318                 writePolicyFile(filename, policyType);
319             }
320         }catch (JAXBException e) {
321             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed");
322         }
323
324         return extension;
325     }
326
327 }