Fixes for sonar critical issues
[policy/engine.git] / PolicyEngineUtils / src / main / java / org / onap / policy / utils / PolicyUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * PolicyEngineUtils
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
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.StringTokenizer;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32
33 import org.drools.core.io.impl.ReaderResource;
34 import org.drools.verifier.Verifier;
35 import org.drools.verifier.VerifierError;
36 import org.drools.verifier.builder.VerifierBuilder;
37 import org.drools.verifier.builder.VerifierBuilderFactory;
38 import org.kie.api.io.ResourceType;
39
40 import com.fasterxml.jackson.core.JsonProcessingException;
41 import com.fasterxml.jackson.databind.ObjectMapper;
42 import com.google.common.base.CharMatcher;
43
44 public class PolicyUtils {
45         
46         public static final String EMAIL_PATTERN =
47             "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
48             + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
49         private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package";
50         private static final String SUCCESS = "success";
51         
52         private PolicyUtils(){
53                 // Private Constructor
54         }
55         public static String objectToJsonString(Object o) throws JsonProcessingException{
56                 ObjectMapper mapper = new ObjectMapper();
57                 return mapper.writeValueAsString(o);
58         }
59         
60         public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
61                 ObjectMapper mapper = new ObjectMapper();
62                 return mapper.readValue(jsonString, className);
63         }
64         
65         public static String decode(String encodedString) throws UnsupportedEncodingException { 
66                 if(encodedString!=null && !encodedString.isEmpty()){ 
67                         return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8"); 
68                 }else{ 
69                         return null; 
70                 } 
71         }
72         
73         public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException {
74                 if(encodedValue!=null && encodedValue.contains("Basic ")){
75                         String encodedUserPassword = encodedValue.replaceFirst("Basic"  + " ", "");
76                         String usernameAndPassword = null;
77                         byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
78                         usernameAndPassword = new String(decodedBytes, "UTF-8");
79                         StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
80                         String username = tokenizer.nextToken();
81                         String password = tokenizer.nextToken();
82                         return new String[]{username, password};
83                 }else{
84                         return new String[]{};
85                 }
86         }
87         
88         public static String  emptyPolicyValidator(String field){
89         String error;
90         if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
91             error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
92             return error;
93         } else {
94             if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
95                  error = SUCCESS;
96             }else{
97                 error = "The Value Contains Non ASCII Characters";
98                 return error;
99             }   
100         }
101         return error;   
102     } 
103     
104         public static String  emptyPolicyValidatorWithSpaceAllowed(String field){
105         String error;
106         if ("".equals(field) || !field.matches("^[a-zA-Z0-9_ ]*$")) {
107             error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
108             return error;
109         } else {
110             if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
111                  error = SUCCESS;
112             }else{
113                 error = "The Value Contains Non ASCII Characters";
114                 return error;
115             }   
116         }
117         return error;   
118     } 
119     public static String descriptionValidator(String field) {
120         String error;
121         if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
122              error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
123              return error;
124         } else {
125             error = SUCCESS;
126         }
127         return error;   
128     }
129     
130     public static Boolean isInteger(String number){
131         try{
132                 Integer.parseInt(number);
133         }catch(NumberFormatException e){
134                 return false;
135         }
136         return true;
137     }
138     
139     public static String validateEmailAddress(String emailAddressValue) {
140         String error = SUCCESS;
141         List<String> emailList = Arrays.asList(emailAddressValue.split(","));
142         for(int i =0 ; i < emailList.size() ; i++){
143             Pattern pattern = Pattern.compile(EMAIL_PATTERN);
144             Matcher matcher = pattern.matcher(emailList.get(i).trim());
145             if(!matcher.matches()){
146                 error = "Please check the Following Email Address is not Valid ....   " +emailList.get(i);
147                 return error;
148             }else{
149                 error = SUCCESS;
150             }
151         }
152         return error;       
153     }
154     
155     /*
156      * Check for "[ERR" to see if there are any errors. 
157      */
158     public static String brmsRawValidate(String rule){
159         VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
160         Verifier verifier = vBuilder.newVerifier();
161         verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
162         // Check if there are any Errors in Verification. 
163         if(!verifier.getErrors().isEmpty()){
164                 boolean ignore = false;
165             StringBuilder message = new StringBuilder("Not a Valid DRL rule"); 
166             for(VerifierError error: verifier.getErrors()){
167                 // Ignore annotations Error Messages
168                 if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){
169                         ignore= true;
170                     message.append("\n" + error.getMessage());
171                 }
172             }
173             // Ignore new package names with {
174             // More checks for message to check if its a package error.
175             if(ignore && !message.toString().contains("Parser returned a null Package")){
176                 message.append("[ERR 107]");
177             }
178             return message.toString();
179         }
180         return "";
181     }
182     
183     /**
184          * Given a version string consisting of integers with dots between them, convert it into an array of ints.
185          * 
186          * @param version
187          * @return
188          * @throws NumberFormatException
189          */
190         public static int[] versionStringToArray(String version) throws NumberFormatException {
191                 if (version == null || version.length() == 0) {
192                         return new int[0];
193                 }
194                 String[] stringArray = version.split("\\.");
195                 int[] resultArray = new int[stringArray.length];
196                 for (int i = 0; i < stringArray.length; i++) {
197                         resultArray[i] = Integer.parseInt(stringArray[i]);
198                 }
199                 return resultArray;
200         }
201 }