Policy 1707 commit to LF
[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.JsonParseException;
41 import com.fasterxml.jackson.core.JsonProcessingException;
42 import com.fasterxml.jackson.databind.JsonMappingException;
43 import com.fasterxml.jackson.databind.ObjectMapper;
44 import com.google.common.base.CharMatcher;
45
46 public class PolicyUtils {
47         
48         public static final String EMAIL_PATTERN =
49             "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
50             + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
51         
52         public static String objectToJsonString(Object o) throws JsonProcessingException{
53                 ObjectMapper mapper = new ObjectMapper();
54                 return mapper.writeValueAsString(o);
55         }
56         
57         public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws JsonParseException, JsonMappingException, IOException{
58                 ObjectMapper mapper = new ObjectMapper();
59                 T t = mapper.readValue(jsonString, className);
60                 return t;
61         }
62         
63         public static String decode(String encodedString) throws UnsupportedEncodingException { 
64                 if(encodedString!=null && !encodedString.isEmpty()){ 
65                         return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8"); 
66                 }else{ 
67                         return null; 
68                 } 
69         }
70         
71         public static String[] decodeBasicEncoding(String encodedValue) throws Exception{
72                 if(encodedValue!=null && encodedValue.contains("Basic ")){
73                         String encodedUserPassword = encodedValue.replaceFirst("Basic"  + " ", "");
74                         String usernameAndPassword = null;
75                         byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
76                         usernameAndPassword = new String(decodedBytes, "UTF-8");
77                         StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
78                         String username = tokenizer.nextToken();
79                         String password = tokenizer.nextToken();
80                         return new String[]{username, password};
81                 }else{
82                         return null;
83                 }
84         }
85         
86         public static String  emptyPolicyValidator(String field){
87         String error = "success";
88         if (field.equals("") || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
89             error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
90             return error;
91         } else {
92             if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
93                  error = "success";
94             }else{
95                 error = "The Value Contains Non ASCII Characters";
96                 return error;
97             }   
98         }
99         return error;   
100     } 
101     
102     public static String descriptionValidator(String field) {
103         String error = "success";
104         if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
105              error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
106              return error;
107         } else {
108             error = "success";
109         }
110         return error;   
111     }
112     
113     public static String validateEmailAddress(String emailAddressValue) {
114         String error = "success";
115         List<String> emailList = Arrays.asList(emailAddressValue.toString().split(","));
116         for(int i =0 ; i < emailList.size() ; i++){
117             Pattern pattern = Pattern.compile(EMAIL_PATTERN);
118             Matcher matcher = pattern.matcher(emailList.get(i).trim());
119             if(!matcher.matches()){
120                 error = "Please check the Following Email Address is not Valid ....   " +emailList.get(i).toString();
121                 return error;
122             }else{
123                 error = "success";
124             }
125         }
126         return error;       
127     }
128     
129     /*
130      * Check for "[ERR" to see if there are any errors. 
131      */
132     public static String brmsRawValidate(String rule){
133         VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
134         Verifier verifier = vBuilder.newVerifier();
135         verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
136         // Check if there are any Errors in Verification. 
137         if(verifier.getErrors().size()!=0){
138             String message = "Not a Valid DRL rule"; 
139             for(VerifierError error: verifier.getErrors()){
140                 // Ignore annotations Error Messages
141                 if(!error.getMessage().contains("'@'")){
142                     message = message + "\n" + error.getMessage();
143                 }
144             }
145             return message;
146         }
147         return "";
148     }
149     
150     /**
151          * Given a version string consisting of integers with dots between them, convert it into an array of ints.
152          * 
153          * @param version
154          * @return
155          * @throws NumberFormatException
156          */
157         public static int[] versionStringToArray(String version) throws NumberFormatException {
158                 if (version == null || version.length() == 0) {
159                         return new int[0];
160                 }
161                 String[] stringArray = version.split("\\.");
162                 int[] resultArray = new int[stringArray.length];
163                 for (int i = 0; i < stringArray.length; i++) {
164                         resultArray[i] = Integer.parseInt(stringArray[i]);
165                 }
166                 return resultArray;
167         }
168 }