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.Scanner;
30 import java.util.StringTokenizer;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
34 import javax.xml.parsers.SAXParser;
35 import javax.xml.parsers.SAXParserFactory;
37 import org.drools.core.io.impl.ReaderResource;
38 import org.drools.verifier.Verifier;
39 import org.drools.verifier.VerifierError;
40 import org.drools.verifier.builder.VerifierBuilder;
41 import org.drools.verifier.builder.VerifierBuilderFactory;
42 import org.kie.api.io.ResourceType;
43 import org.onap.policy.common.logging.flexlogger.FlexLogger;
44 import org.onap.policy.common.logging.flexlogger.Logger;
45 import org.xml.sax.InputSource;
46 import org.xml.sax.XMLReader;
48 import com.fasterxml.jackson.core.JsonProcessingException;
49 import com.fasterxml.jackson.databind.ObjectMapper;
50 import com.google.common.base.CharMatcher;
51 import com.google.gson.JsonParser;
52 import com.google.gson.JsonSyntaxException;
54 public class PolicyUtils {
55 private static final Logger LOGGER = FlexLogger.getLogger(PolicyUtils.class);
57 public static final String EMAIL_PATTERN =
58 "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
59 + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
60 private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package";
61 private static final String SUCCESS = "success";
63 private PolicyUtils(){
64 // Private Constructor
68 * Converts an Object to JSON String
71 * @return String format of Object JSON.
72 * @throws JsonProcessingException
74 public static String objectToJsonString(Object o) throws JsonProcessingException{
75 ObjectMapper mapper = new ObjectMapper();
76 return mapper.writeValueAsString(o);
80 * Converts JSON string into Object
83 * @param className equivalent Class of the given JSON string
84 * @return T instance of the class given.
87 public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
88 ObjectMapper mapper = new ObjectMapper();
89 return mapper.readValue(jsonString, className);
93 * Decode a base64 string
95 * @param encodedString
97 * @throws UnsupportedEncodingException
99 public static String decode(String encodedString) throws UnsupportedEncodingException {
100 if(encodedString!=null && !encodedString.isEmpty()){
101 return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8");
108 * Decodes Basic Authentication
110 * @param encodedValue
112 * @throws UnsupportedEncodingException
114 public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException {
115 if(encodedValue!=null && encodedValue.contains("Basic ")){
116 String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", "");
117 String usernameAndPassword = null;
118 byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
119 usernameAndPassword = new String(decodedBytes, "UTF-8");
120 StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
121 String username = tokenizer.nextToken();
122 String password = tokenizer.nextToken();
123 return new String[]{username, password};
125 return new String[]{};
130 * Validate a field if contains space or unacceptable policy input and return "success" if good.
135 public static String policySpecialCharValidator(String field){
137 if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
138 error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
145 * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good.
150 public static String policySpecialCharWithSpaceValidator(String field){
152 if ("".equals(field) || !field.matches("^[a-zA-Z0-9_ ]*$")) {
153 error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
160 * Validate the XACML description tag and return "success" if good.
165 public static String descriptionValidator(String field) {
167 if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
168 error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
177 * Validate if string contains non ASCII characters
182 public static boolean containsNonAsciiEmptyChars(String value) {
183 return (value == null|| value.contains(" ") || "".equals(value.trim())|| !CharMatcher.ASCII.matchesAllOf((CharSequence) value))? true:false;
187 * Validate if given string is an integer.
192 public static Boolean isInteger(String number){
196 for (char c : number.toCharArray()){
197 if (!Character.isDigit(c)) return false;
203 * Validate Email Address and return "success" if good.
205 * @param emailAddressValue
208 public static String validateEmailAddress(String emailAddressValue) {
209 String error = SUCCESS;
210 List<String> emailList = Arrays.asList(emailAddressValue.split(","));
211 for(int i =0 ; i < emailList.size() ; i++){
212 Pattern pattern = Pattern.compile(EMAIL_PATTERN);
213 Matcher matcher = pattern.matcher(emailList.get(i).trim());
214 if(!matcher.matches()){
215 error = "Please check the Following Email Address is not Valid .... " +emailList.get(i);
225 * Validates BRMS rule as per Policy Platform and return string contains "[ERR" if there are any errors.
228 * @return String error message
230 public static String brmsRawValidate(String rule){
231 VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
232 Verifier verifier = vBuilder.newVerifier();
233 verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
234 // Check if there are any Errors in Verification.
235 if(!verifier.getErrors().isEmpty()){
236 boolean ignore = false;
237 StringBuilder message = new StringBuilder("Not a Valid DRL rule");
238 for(VerifierError error: verifier.getErrors()){
239 // Ignore annotations Error Messages
240 if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){
242 message.append("\n" + error.getMessage());
245 // Ignore new package names with '{'
246 // More checks for message to check if its a package error.
247 if(ignore && !message.toString().contains("Parser returned a null Package")){
248 message.append("[ERR 107]");
250 return message.toString();
256 * Validates if the given string is proper JSON format.
261 public static boolean isJSONValid(String data) {
263 JsonParser parser = new JsonParser();
265 }catch(JsonSyntaxException e){
266 LOGGER.error("Exception Occurred While Validating"+e);
273 * Validates if the given string is proper XML format.
278 public static boolean isXMLValid(String data) {
279 SAXParserFactory factory = SAXParserFactory.newInstance();
280 factory.setValidating(false);
281 factory.setNamespaceAware(true);
283 SAXParser parser = factory.newSAXParser();
284 XMLReader reader = parser.getXMLReader();
285 reader.setErrorHandler(new XMLErrorHandler());
286 reader.parse(new InputSource(new StringReader(data)));
287 } catch (Exception e) {
288 LOGGER.error("Exception Occured While Validating"+e);
295 * Validates if given string is valid Properties format.
300 public static boolean isPropValid(String prop) {
301 Scanner scanner = new Scanner(prop);
302 while (scanner.hasNextLine()) {
303 String line = scanner.nextLine();
304 line = line.replaceAll("\\s+", "");
305 if (line.startsWith("#")) {
308 if (line.contains("=")) {
309 String[] parts = line.split("=");
310 if (parts.length < 2) {
314 } else if(!line.trim().isEmpty()){
325 * Given a version string consisting of integers with dots between them, convert it into an array of integers.
329 * @throws NumberFormatException
331 public static int[] versionStringToArray(String version){
332 if (version == null || version.length() == 0) {
335 String[] stringArray = version.split("\\.");
336 int[] resultArray = new int[stringArray.length];
337 for (int i = 0; i < stringArray.length; i++) {
338 resultArray[i] = Integer.parseInt(stringArray[i].trim());