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.openecomp.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
56 public static String objectToJsonString(Object o) throws JsonProcessingException{
57 ObjectMapper mapper = new ObjectMapper();
58 return mapper.writeValueAsString(o);
61 public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
62 ObjectMapper mapper = new ObjectMapper();
63 return mapper.readValue(jsonString, className);
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");
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};
85 return new String[]{};
89 public static String emptyPolicyValidator(String field){
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";
95 if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
98 error = "The Value Contains Non ASCII Characters";
105 public static String emptyPolicyValidatorWithSpaceAllowed(String field){
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";
111 if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
114 error = "The Value Contains Non ASCII Characters";
121 public static String descriptionValidator(String field) {
123 if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
124 error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
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();
149 * Check for "[ERR" to see if there are any errors.
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)){
163 message.append("\n" + error.getMessage());
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]");
171 return message.toString();
177 * Given a version string consisting of integers with dots between them, convert it into an array of ints.
181 * @throws NumberFormatException
183 public static int[] versionStringToArray(String version) throws NumberFormatException {
184 if (version == null || version.length() == 0) {
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]);