2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.utils;
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;
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;
40 import com.fasterxml.jackson.core.JsonProcessingException;
41 import com.fasterxml.jackson.databind.ObjectMapper;
42 import com.google.common.base.CharMatcher;
44 public class PolicyUtils {
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";
52 private PolicyUtils(){
53 // Private Constructor
55 public static String objectToJsonString(Object o) throws JsonProcessingException{
56 ObjectMapper mapper = new ObjectMapper();
57 return mapper.writeValueAsString(o);
60 public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
61 ObjectMapper mapper = new ObjectMapper();
62 return mapper.readValue(jsonString, className);
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");
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};
84 return new String[]{};
88 public static String emptyPolicyValidator(String field){
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";
94 if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
97 error = "The Value Contains Non ASCII Characters";
104 public static String emptyPolicyValidatorWithSpaceAllowed(String field){
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";
110 if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
113 error = "The Value Contains Non ASCII Characters";
119 public static String descriptionValidator(String field) {
121 if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
122 error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
130 public static Boolean isInteger(String number){
132 Integer.parseInt(number);
133 }catch(NumberFormatException e){
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);
156 * Check for "[ERR" to see if there are any errors.
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)){
170 message.append("\n" + error.getMessage());
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]");
178 return message.toString();
184 * Given a version string consisting of integers with dots between them, convert it into an array of ints.
188 * @throws NumberFormatException
190 public static int[] versionStringToArray(String version) throws NumberFormatException {
191 if (version == null || version.length() == 0) {
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]);