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