2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.XMLConstants;
35 import javax.xml.parsers.SAXParser;
36 import javax.xml.parsers.SAXParserFactory;
38 import org.drools.core.io.impl.ReaderResource;
39 import org.drools.verifier.Verifier;
40 import org.drools.verifier.VerifierError;
41 import org.drools.verifier.builder.VerifierBuilder;
42 import org.drools.verifier.builder.VerifierBuilderFactory;
43 import org.kie.api.io.ResourceType;
44 import org.onap.policy.common.logging.flexlogger.FlexLogger;
45 import org.onap.policy.common.logging.flexlogger.Logger;
46 import org.xml.sax.InputSource;
47 import org.xml.sax.XMLReader;
49 import com.fasterxml.jackson.core.JsonProcessingException;
50 import com.fasterxml.jackson.databind.ObjectMapper;
51 import com.google.common.base.CharMatcher;
52 import com.google.gson.JsonParser;
53 import com.google.gson.JsonSyntaxException;
55 public class PolicyUtils {
56 private static final Logger LOGGER = FlexLogger.getLogger(PolicyUtils.class);
57 public static final String CATCH_EXCEPTION = "PE500: An exception was caught.";
58 public static final String EMAIL_PATTERN =
59 "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
60 + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
61 private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package";
62 public static final String SUCCESS = "success";
64 private PolicyUtils(){
65 // Private Constructor
69 * Converts an Object to JSON String
72 * @return String format of Object JSON.
73 * @throws JsonProcessingException
75 public static String objectToJsonString(Object o) throws JsonProcessingException{
76 ObjectMapper mapper = new ObjectMapper();
77 return mapper.writeValueAsString(o);
81 * Converts JSON string into Object
84 * @param className equivalent Class of the given JSON string
85 * @return T instance of the class given.
88 public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
89 ObjectMapper mapper = new ObjectMapper();
90 return mapper.readValue(jsonString, className);
94 * Decode a base64 string
96 * @param encodedString
98 * @throws UnsupportedEncodingException
100 public static String decode(String encodedString) throws UnsupportedEncodingException {
101 if(encodedString!=null && !encodedString.isEmpty()){
102 return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8");
109 * Decodes Basic Authentication
111 * @param encodedValue
113 * @throws UnsupportedEncodingException
115 public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException {
116 if(encodedValue!=null && encodedValue.contains("Basic ")){
117 String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", "");
118 String usernameAndPassword;
119 byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
120 usernameAndPassword = new String(decodedBytes, "UTF-8");
121 StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
122 String username = tokenizer.nextToken();
123 String password = tokenizer.nextToken();
124 return new String[]{username, password};
126 return new String[]{};
131 * Validate a field if contains space or unacceptable policy input and return "success" if good.
136 public static String policySpecialCharValidator(String field){
138 if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
139 error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
146 * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good.
151 public static String policySpecialCharWithSpaceValidator(String field){
153 if ("".equals(field) || !field.matches("^[a-zA-Z0-9_ ]*$")) {
154 error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
161 * Validate the XACML description tag and return "success" if good.
166 public static String descriptionValidator(String field) {
168 if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
169 error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
178 * Validate if string contains non ASCII characters
183 public static boolean containsNonAsciiEmptyChars(String value) {
184 return (value == null|| value.contains(" ") || "".equals(value.trim())|| !CharMatcher.ASCII.matchesAllOf((CharSequence) value))? true:false;
188 * Validate if given string is an integer.
193 public static Boolean isInteger(String number){
197 for (char c : number.toCharArray()){
198 if (!Character.isDigit(c)) {
206 * Validate Email Address and return "success" if good.
208 * @param emailAddressValue
211 public static String validateEmailAddress(String emailAddressValue) {
212 String error = SUCCESS;
213 List<String> emailList = Arrays.asList(emailAddressValue.split(","));
214 for(int i =0 ; i < emailList.size() ; i++){
215 Pattern pattern = Pattern.compile(EMAIL_PATTERN);
216 Matcher matcher = pattern.matcher(emailList.get(i).trim());
217 if(!matcher.matches()){
218 error = "Please check the Following Email Address is not Valid .... " +emailList.get(i);
228 * Validates BRMS rule as per Policy Platform and return string contains "[ERR" if there are any errors.
231 * @return String error message
233 public static String brmsRawValidate(String rule){
234 VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
235 Verifier verifier = vBuilder.newVerifier();
236 verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
237 // Check if there are any Errors in Verification.
238 if(!verifier.getErrors().isEmpty()){
239 boolean ignore = false;
240 StringBuilder message = new StringBuilder("Not a Valid DRL rule");
241 for(VerifierError error: verifier.getErrors()){
242 // Ignore annotations Error Messages
243 if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){
245 message.append("\n" + error.getMessage());
248 // Ignore new package names with '{'
249 // More checks for message to check if its a package error.
250 if(ignore && !message.toString().contains("Parser returned a null Package")){
251 message.append("[ERR 107]");
253 return message.toString();
259 * Validates if the given string is proper JSON format.
264 public static boolean isJSONValid(String data) {
266 JsonParser parser = new JsonParser();
268 }catch(JsonSyntaxException e){
269 LOGGER.error("Exception Occurred While Validating"+e);
276 * Validates if the given string is proper XML format.
281 public static boolean isXMLValid(String data) {
282 if(data == null || data.isEmpty()){
285 SAXParserFactory factory = SAXParserFactory.newInstance();
286 factory.setValidating(false);
287 factory.setNamespaceAware(true);
290 factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
291 SAXParser parser = factory.newSAXParser();
292 XMLReader reader = parser.getXMLReader();
293 reader.setErrorHandler(new XMLErrorHandler());
294 reader.parse(new InputSource(new StringReader(data)));
295 } catch (Exception e) {
296 LOGGER.error("Exception Occured While Validating"+e);
303 * Validates if given string is valid Properties format.
308 public static boolean isPropValid(String prop) {
309 Scanner scanner = new Scanner(prop);
310 while (scanner.hasNextLine()) {
311 String line = scanner.nextLine();
312 line = line.replaceAll("\\s+", "");
313 if (line.startsWith("#")) {
316 if (line.contains("=")) {
317 String[] parts = line.split("=");
318 if (parts.length < 2) {
322 } else if(!line.trim().isEmpty()){
333 * Given a version string consisting of integers with dots between them, convert it into an array of integers.
337 * @throws NumberFormatException
339 public static int[] versionStringToArray(String version){
340 if (version == null || version.length() == 0) {
343 String[] stringArray = version.split("\\.");
344 int[] resultArray = new int[stringArray.length];
345 for (int i = 0; i < stringArray.length; i++) {
346 resultArray[i] = Integer.parseInt(stringArray[i].trim());