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