aboutsummaryrefslogtreecommitdiffstats
path: root/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java
blob: 06263853e4e6a33d08b870c1fba4cbaf3a1efd01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*-
 * ============LICENSE_START=======================================================
 * PolicyEngineUtils
 * ================================================================================
 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.utils;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.drools.core.io.impl.ReaderResource;
import org.drools.verifier.Verifier;
import org.drools.verifier.VerifierError;
import org.drools.verifier.builder.VerifierBuilder;
import org.drools.verifier.builder.VerifierBuilderFactory;
import org.kie.api.io.ResourceType;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.CharMatcher;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

public class PolicyUtils {
    private static final Logger LOGGER = FlexLogger.getLogger(PolicyUtils.class);
    public static final String CATCH_EXCEPTION = "PE500: An exception was caught.";  
    public static final String EMAIL_PATTERN =
            "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package";
    public static final String SUCCESS = "success";
    
    private PolicyUtils(){
        // Private Constructor
    }
    
    /**
     * Converts an Object to JSON String 
     * 
     * @param o Object 
     * @return String format of Object JSON. 
     * @throws JsonProcessingException
     */
    public static String objectToJsonString(Object o) throws JsonProcessingException{
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(o);
    }
    
    /**
     * Converts JSON string into Object
     * 
     * @param jsonString 
     * @param className equivalent Class of the given JSON string 
     * @return T instance of the class given. 
     * @throws IOException
     */
    public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(jsonString, className);
    }
    
    /**
     * Decode a base64 string 
     * 
     * @param encodedString
     * @return String
     * @throws UnsupportedEncodingException
     */
    public static String decode(String encodedString) throws UnsupportedEncodingException { 
        if(encodedString!=null && !encodedString.isEmpty()){ 
            return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8"); 
        }else{ 
            return null; 
        } 
    }
    
    /**
     * Decodes Basic Authentication 
     * 
     * @param encodedValue
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException {
        if(encodedValue!=null && encodedValue.contains("Basic ")){
            String encodedUserPassword = encodedValue.replaceFirst("Basic"  + " ", "");
            String usernameAndPassword;
            byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
            usernameAndPassword = new String(decodedBytes, "UTF-8");
            StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
            String username = tokenizer.nextToken();
            String password = tokenizer.nextToken();
            return new String[]{username, password};
        }else{
            return new String[]{};
        }
    }
    
    /**
     * Validate a field if contains space or unacceptable policy input and return "success" if good. 
     * 
     * @param field
     * @return
     */
    public static String  policySpecialCharValidator(String field){
        String error;
        if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
            error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
            return error; 
        }
        return SUCCESS;   
    } 
    
    /**
     * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good. 
     * 
     * @param field
     * @return
     */
    public static String  policySpecialCharWithSpaceValidator(String field){
        String error;
        if ("".equals(field) || !field.matches("^[a-zA-Z0-9_ ]*$")) {
            error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
            return error;
        }
        return SUCCESS;   
    } 
    
    /**
     * Validate a field (accepts Dash) if it contains unacceptable policy input and return "success" if good. 
     * 
     * @param field
     * @return
     */
    public static String  policySpecialCharWithDashValidator(String field){
        String error;
        if ("".equals(field) || !field.matches("^[a-zA-Z0-9_-]*$")) {
            error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _, -' following set of Combinations";
            return error;
        }
        return SUCCESS;   
    } 
    
    /**
     * Validate the XACML description tag and return "success" if good. 
     * 
     * @param field
     * @return
     */
    public static String descriptionValidator(String field) {
        String error;
        if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
             error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
             return error;
        } else {
            error = SUCCESS;
        }
        return error;   
    }
    
    /**
     * Validate if string contains non ASCII characters 
     * 
     * @param value
     * @return
     */
    public static boolean containsNonAsciiEmptyChars(String value) {
        return (value == null|| value.contains(" ") || "".equals(value.trim())|| !CharMatcher.ASCII.matchesAllOf((CharSequence) value))? true:false;
    }
    
    /**
     * Validate if given string is an integer. 
     * 
     * @param number
     * @return
     */
    public static Boolean isInteger(String number){
        if(number==null) {
            return false;
        }
        for (char c : number.toCharArray()){
            if (!Character.isDigit(c)) {
            	return false;
            }
        }
        return true;
    }
    
    /**
     * Validate Email Address and return "success" if good. 
     * 
     * @param emailAddressValue
     * @return
     */
    public static String validateEmailAddress(String emailAddressValue) {
        String error = SUCCESS;
        List<String> emailList = Arrays.asList(emailAddressValue.split(","));
        for(int i =0 ; i < emailList.size() ; i++){
            Pattern pattern = Pattern.compile(EMAIL_PATTERN);
            Matcher matcher = pattern.matcher(emailList.get(i).trim());
            if(!matcher.matches()){
                error = "Please check the Following Email Address is not Valid ....   " +emailList.get(i);
                return error;
            }else{
                error = SUCCESS;
            }
        }
        return error;       
    }
    
    /**
     * Validates BRMS rule as per Policy Platform and return string contains "[ERR" if there are any errors.
     * 
     * @param rule
     * @return String error message
     */
    public static String brmsRawValidate(String rule){
        VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
        Verifier verifier = vBuilder.newVerifier();
        verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
        // Check if there are any Errors in Verification. 
        if(!verifier.getErrors().isEmpty()){
            boolean ignore = false;
            StringBuilder message = new StringBuilder("Not a Valid DRL rule"); 
            for(VerifierError error: verifier.getErrors()){
                // Ignore annotations Error Messages
                if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){
                    ignore= true;
                    message.append("\n" + error.getMessage());
                }
            }
            // Ignore new package names with '{'
            // More checks for message to check if its a package error.
            if(ignore && !message.toString().contains("Parser returned a null Package")){
                message.append("[ERR 107]");
            }
            return message.toString();
        }
        return "";
    }
    
    /**
     * Validates if the given string is proper JSON format. 
     * 
     * @param data
     * @return
     */
    public static boolean isJSONValid(String data) {
        try{
            JsonParser parser = new JsonParser();
            parser.parse(data);
        }catch(JsonSyntaxException e){
            LOGGER.error("Exception Occurred While Validating"+e);
            return false;
        }
        return true;
    }

    /**
     * Validates if the given string is proper XML format. 
     * 
     * @param data
     * @return
     */
    public static boolean isXMLValid(String data) {
    	if(data == null || data.isEmpty()){
        	return false;
        }
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        
        try {    
			factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);		
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            reader.setErrorHandler(new XMLErrorHandler());
            reader.parse(new InputSource(new StringReader(data)));
        } catch (Exception e) {
            LOGGER.error("Exception Occured While Validating"+e);
            return false;
        }
        return true;
    }

    /**
     * Validates if given string is valid Properties format. 
     * 
     * @param prop
     * @return
     */
    public static boolean isPropValid(String prop) {
        Scanner scanner = new Scanner(prop);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            line = line.replaceAll("\\s+", "");
            if (line.startsWith("#")) {
                continue;
            } else {
                if (line.contains("=")) {
                    String[] parts = line.split("=");
                    if (parts.length < 2) {
                        scanner.close();
                        return false;
                    }
                } else if(!line.trim().isEmpty()){
                    scanner.close();
                    return false;
                }
            }
        }
        scanner.close();
        return true;
    }
    
    /**
     * Given a version string consisting of integers with dots between them, convert it into an array of integers.
     * 
     * @param version
     * @return 
     * @throws NumberFormatException
     */
    public static int[] versionStringToArray(String version){
        if (version == null || version.length() == 0) {
            return new int[0];
        }
        String[] stringArray = version.split("\\.");
        int[] resultArray = new int[stringArray.length];
        for (int i = 0; i < stringArray.length; i++) {
            resultArray[i] = Integer.parseInt(stringArray[i].trim());
        }
        return resultArray;
    }
}