e17ddc6819db51cba04b19b2c4e212b95fd30194
[policy/engine.git] / PolicyEngineUtils / src / main / java / org / onap / policy / utils / PolicyUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * PolicyEngineUtils
4  * ================================================================================
5  * Copyright (C) 2017-2018 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
21 package org.onap.policy.utils;
22
23 import java.io.IOException;
24 import java.io.StringReader;
25 import java.io.UnsupportedEncodingException;
26 import java.util.Arrays;
27 import java.util.Base64;
28 import java.util.List;
29 import java.util.Scanner;
30 import java.util.StringTokenizer;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33
34 import javax.xml.XMLConstants;
35 import javax.xml.parsers.SAXParser;
36 import javax.xml.parsers.SAXParserFactory;
37
38 import org.drools.core.io.impl.ReaderResource;
39 import org.drools.verifier.Verifier;
40 import org.drools.verifier.VerifierError;
41 import org.drools.verifier.builder.VerifierBuilder;
42 import org.drools.verifier.builder.VerifierBuilderFactory;
43 import org.kie.api.io.ResourceType;
44 import org.onap.policy.common.logging.flexlogger.FlexLogger;
45 import org.onap.policy.common.logging.flexlogger.Logger;
46 import org.xml.sax.InputSource;
47 import org.xml.sax.XMLReader;
48
49 import com.fasterxml.jackson.core.JsonProcessingException;
50 import com.fasterxml.jackson.databind.ObjectMapper;
51 import com.google.common.base.CharMatcher;
52 import com.google.gson.JsonParser;
53 import com.google.gson.JsonSyntaxException;
54
55 public class PolicyUtils {
56     private static final Logger LOGGER = FlexLogger.getLogger(PolicyUtils.class);
57     public static final String CATCH_EXCEPTION = "PE500: An exception was caught.";  
58     public static final String EMAIL_PATTERN =
59             "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
60             + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
61     private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package";
62     public static final String SUCCESS = "success";
63     
64     private PolicyUtils(){
65         // Private Constructor
66     }
67     
68     /**
69      * Converts an Object to JSON String 
70      * 
71      * @param o Object 
72      * @return String format of Object JSON. 
73      * @throws JsonProcessingException
74      */
75     public static String objectToJsonString(Object o) throws JsonProcessingException{
76         ObjectMapper mapper = new ObjectMapper();
77         return mapper.writeValueAsString(o);
78     }
79     
80     /**
81      * Converts JSON string into Object
82      * 
83      * @param jsonString 
84      * @param className equivalent Class of the given JSON string 
85      * @return T instance of the class given. 
86      * @throws IOException
87      */
88     public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
89         ObjectMapper mapper = new ObjectMapper();
90         return mapper.readValue(jsonString, className);
91     }
92     
93     /**
94      * Decode a base64 string 
95      * 
96      * @param encodedString
97      * @return String
98      * @throws UnsupportedEncodingException
99      */
100     public static String decode(String encodedString) throws UnsupportedEncodingException { 
101         if(encodedString!=null && !encodedString.isEmpty()){ 
102             return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8"); 
103         }else{ 
104             return null; 
105         } 
106     }
107     
108     /**
109      * Decodes Basic Authentication 
110      * 
111      * @param encodedValue
112      * @return
113      * @throws UnsupportedEncodingException
114      */
115     public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException {
116         if(encodedValue!=null && encodedValue.contains("Basic ")){
117             String encodedUserPassword = encodedValue.replaceFirst("Basic"  + " ", "");
118             String usernameAndPassword;
119             byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
120             usernameAndPassword = new String(decodedBytes, "UTF-8");
121             StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
122             String username = tokenizer.nextToken();
123             String password = tokenizer.nextToken();
124             return new String[]{username, password};
125         }else{
126             return new String[]{};
127         }
128     }
129     
130     /**
131      * Validate a field if contains space or unacceptable policy input and return "success" if good. 
132      * 
133      * @param field
134      * @return
135      */
136     public static String  policySpecialCharValidator(String field){
137         String error;
138         if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
139             error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
140             return error; 
141         }
142         return SUCCESS;   
143     } 
144     
145     /**
146      * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good. 
147      * 
148      * @param field
149      * @return
150      */
151     public static String  policySpecialCharWithSpaceValidator(String field){
152         String error;
153         if ("".equals(field) || !field.matches("^[a-zA-Z0-9_ ]*$")) {
154             error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
155             return error;
156         }
157         return SUCCESS;   
158     } 
159     
160     /**
161      * Validate the XACML description tag and return "success" if good. 
162      * 
163      * @param field
164      * @return
165      */
166     public static String descriptionValidator(String field) {
167         String error;
168         if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
169              error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
170              return error;
171         } else {
172             error = SUCCESS;
173         }
174         return error;   
175     }
176     
177     /**
178      * Validate if string contains non ASCII characters 
179      * 
180      * @param value
181      * @return
182      */
183     public static boolean containsNonAsciiEmptyChars(String value) {
184         return (value == null|| value.contains(" ") || "".equals(value.trim())|| !CharMatcher.ASCII.matchesAllOf((CharSequence) value))? true:false;
185     }
186     
187     /**
188      * Validate if given string is an integer. 
189      * 
190      * @param number
191      * @return
192      */
193     public static Boolean isInteger(String number){
194         if(number==null) {
195             return false;
196         }
197         for (char c : number.toCharArray()){
198             if (!Character.isDigit(c)) {
199                 return false;
200             }
201         }
202         return true;
203     }
204     
205     /**
206      * Validate Email Address and return "success" if good. 
207      * 
208      * @param emailAddressValue
209      * @return
210      */
211     public static String validateEmailAddress(String emailAddressValue) {
212         String error = SUCCESS;
213         List<String> emailList = Arrays.asList(emailAddressValue.split(","));
214         for(int i =0 ; i < emailList.size() ; i++){
215             Pattern pattern = Pattern.compile(EMAIL_PATTERN);
216             Matcher matcher = pattern.matcher(emailList.get(i).trim());
217             if(!matcher.matches()){
218                 error = "Please check the Following Email Address is not Valid ....   " +emailList.get(i);
219                 return error;
220             }else{
221                 error = SUCCESS;
222             }
223         }
224         return error;       
225     }
226     
227     /**
228      * Validates BRMS rule as per Policy Platform and return string contains "[ERR" if there are any errors.
229      * 
230      * @param rule
231      * @return String error message
232      */
233     public static String brmsRawValidate(String rule){
234         VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
235         Verifier verifier = vBuilder.newVerifier();
236         verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
237         // Check if there are any Errors in Verification. 
238         if(!verifier.getErrors().isEmpty()){
239             boolean ignore = false;
240             StringBuilder message = new StringBuilder("Not a Valid DRL rule"); 
241             for(VerifierError error: verifier.getErrors()){
242                 // Ignore annotations Error Messages
243                 if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){
244                     ignore= true;
245                     message.append("\n" + error.getMessage());
246                 }
247             }
248             // Ignore new package names with '{'
249             // More checks for message to check if its a package error.
250             if(ignore && !message.toString().contains("Parser returned a null Package")){
251                 message.append("[ERR 107]");
252             }
253             return message.toString();
254         }
255         return "";
256     }
257     
258     /**
259      * Validates if the given string is proper JSON format. 
260      * 
261      * @param data
262      * @return
263      */
264     public static boolean isJSONValid(String data) {
265         try{
266             JsonParser parser = new JsonParser();
267             parser.parse(data);
268         }catch(JsonSyntaxException e){
269             LOGGER.error("Exception Occurred While Validating"+e);
270             return false;
271         }
272         return true;
273     }
274
275     /**
276      * Validates if the given string is proper XML format. 
277      * 
278      * @param data
279      * @return
280      */
281     public static boolean isXMLValid(String data) {
282         if(data == null || data.isEmpty()){
283                 return false;
284         }
285         SAXParserFactory factory = SAXParserFactory.newInstance();
286         factory.setValidating(false);
287         factory.setNamespaceAware(true);
288         
289         try {    
290                         factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);               
291             SAXParser parser = factory.newSAXParser();
292             XMLReader reader = parser.getXMLReader();
293             reader.setErrorHandler(new XMLErrorHandler());
294             reader.parse(new InputSource(new StringReader(data)));
295         } catch (Exception e) {
296             LOGGER.error("Exception Occured While Validating"+e);
297             return false;
298         }
299         return true;
300     }
301
302     /**
303      * Validates if given string is valid Properties format. 
304      * 
305      * @param prop
306      * @return
307      */
308     public static boolean isPropValid(String prop) {
309         Scanner scanner = new Scanner(prop);
310         while (scanner.hasNextLine()) {
311             String line = scanner.nextLine();
312             line = line.replaceAll("\\s+", "");
313             if (line.startsWith("#")) {
314                 continue;
315             } else {
316                 if (line.contains("=")) {
317                     String[] parts = line.split("=");
318                     if (parts.length < 2) {
319                         scanner.close();
320                         return false;
321                     }
322                 } else if(!line.trim().isEmpty()){
323                     scanner.close();
324                     return false;
325                 }
326             }
327         }
328         scanner.close();
329         return true;
330     }
331     
332     /**
333      * Given a version string consisting of integers with dots between them, convert it into an array of integers.
334      * 
335      * @param version
336      * @return 
337      * @throws NumberFormatException
338      */
339     public static int[] versionStringToArray(String version){
340         if (version == null || version.length() == 0) {
341             return new int[0];
342         }
343         String[] stringArray = version.split("\\.");
344         int[] resultArray = new int[stringArray.length];
345         for (int i = 0; i < stringArray.length; i++) {
346             resultArray[i] = Integer.parseInt(stringArray[i].trim());
347         }
348         return resultArray;
349     }
350 }