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