com.qmetry.qaf.automation.util.StringUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of qaf Show documentation
Show all versions of qaf Show documentation
Functional test automation framework for web, mobile-web, mobile native and web-service
/*******************************************************************************
* Copyright (c) 2019 Infostretch Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package com.qmetry.qaf.automation.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.WeakHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptException;
import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.JexlExpression;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class StringUtil extends StringUtils {
/**
* @param str
* @return string with first char in upper-case
*/
public static String getTitleCase(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
/**
* Utility method to create variable or method name from string.
*
* @param formStr
* @return
*/
public static String toCamelCaseIdentifier(String formStr) {
StringBuffer res = new StringBuffer();
if (isEmpty(formStr)) {
return "";
}
formStr = formStr.replaceAll("\\{(\\d)*(\\s)*\\}", "");
String[] strArr = formStr.split("\\W");
int i = 0;
for (String str : strArr) {
if (str.trim().length() > 0) {
char[] stringArray = str.trim().toCharArray();
if (i == 0)
stringArray[0] = Character.toLowerCase(stringArray[0]);
else
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str);
}
i++;
}
return res.toString().trim();
}
public static String toTitleCaseIdentifier(String formStr) {
return getTitleCase(toCamelCaseIdentifier(formStr));
}
public static String getRandomString(String format) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < format.length(); i++) {
char c = format.charAt(i);
char a = Character.isDigit(c) ? RandomStringUtils.randomNumeric(1).charAt(0)
: Character.isLetter(c) ? RandomStringUtils.randomAlphabetic(c).charAt(0) : c;
sb.append(a);
}
return sb.toString();
}
/**
* @param str : string to check
* @return true if string contains any number, false otherwise
*/
public boolean containsNumbers(String str) {
return str.matches(".*\\d.*");
}
/**
* Convert date string from one format to another format.
*
* Example:
*
*
* formatDate("2012-01-11",
"yyy-MM-dd", "MMM d, yyyy"))
*
will retrun "Jan 11, 2012"
* - formatDate("2012-01-11T05:38:00+0530", {@link #BPM_DATETIME_FORMAT},
* {@link #GI_DATETIME_FORMAT})) will retrun "Jan 11, 2012 05:38 AM"
*
*
*
* @param dateStr : date string to be formated
* @param formatFrom : format of the given date string
* @param formatTo : String expected format
* @return date string in expected format
*/
public static String getFormatedDate(String dateString, String formatFrom, String formatTo) {
SimpleDateFormat aformat = new SimpleDateFormat(formatFrom);
SimpleDateFormat eformat = new SimpleDateFormat(formatTo);
Date d;
try {
d = aformat.parse(dateString);
} catch (ParseException e) {
throw new RuntimeException(e.getMessage());
}
return eformat.format(d);
}
public static String createRandomString(String prefix) {
Random r = new Random();
String token = Long.toString(Math.abs(r.nextLong()), 36);
return (prefix + "_" + token);
}
public static String createRandomString() {
Random r = new Random();
String token = Long.toString(Math.abs(r.nextLong()), 36);
return (token);
}
public static boolean isNullOrEmpty(String s) {
return (null == s) || s.isEmpty();
}
public static boolean isXpath(String val) {
return !isNullOrEmpty(val) && (val.startsWith("//") || val.toLowerCase().startsWith("xpath"));
}
public static String getWellFormedXPATH(String val) {
String fstr = val;
if (!val.toLowerCase().startsWith("xpath")) {
fstr = "xpath=(" + val + ")[1]";
}
if (!val.endsWith("]")) {
fstr = val + "[1]";
}
return fstr;
}
public static String extractParamValueFromUrl(String urlString, String paramName) {
String retVal = "";
String[] params = urlString.split("\\?|&");
for (String param : params) {
if (param.startsWith(paramName.trim() + "=")) {
retVal = param.substring(paramName.trim().length() + 1);
break;
}
}
return retVal;
}
/**
*
* @param expectedPattern
* @param actual
* @return
*/
public static boolean seleniumEquals(String expectedPattern, String actual) {
return StringMatcher.match(expectedPattern, actual);
}
/**
* @deprecated - unused method will be removed in future.
* @param prefix
* @param expectedPattern
* @param actual
* @param flags
* @return
*/
public static Boolean handleRegex(String prefix, String expectedPattern, String actual, int flags) {
if (expectedPattern.startsWith(prefix)) {
String expectedRegEx = expectedPattern.replaceFirst(prefix, "");// +
// ".*";
Pattern p = Pattern.compile(expectedRegEx, flags);
if (!p.matcher(actual).matches()) {
System.out.println("expected " + actual + " to match regexp " + expectedPattern);
return Boolean.FALSE;
}
return Boolean.TRUE;
}
return null;
}
public static final char NULL = Character.MIN_VALUE;
/**
* get map form key value pair separated by char (default char is ",")
*
* @param csvKeyVal or other char separated key=value pair. For
* example: "foo=bar,xxx=yyy"
* @param ensureKeyUppercase : if true then it will set upper-case key for value
* @param ch (optional) char used to separate key=value pair.
* default separator char is ","
* @return
*/
public static Map toMap(String csvKeyVal, boolean ensureKeyUppercase, char... ch) {
Object[] params = StringUtil.parseCSV(csvKeyVal, ch);
return toMap((String[]) params, ensureKeyUppercase);
}
/**
* @param csvKeyVal array of key=value pair.
* @param ensureKeyUppercase : if true then it will set upper-case key for value
* @return map
*/
public static Map toMap(String[] csvKeyVal, boolean ensureKeyUppercase) {
WeakHashMap map = new WeakHashMap();
if (null == csvKeyVal) {
return map;
}
for (String param : csvKeyVal) {
if (isNotBlank(param)) {
String[] kv = param.split("=", 2);
map.put(ensureKeyUppercase ? kv[0].toUpperCase() : kv[0], kv.length > 1 ? (kv[1]) : "");
}
}
return map;
}
/**
* Method to parse character separated values, generic version of comma
* separated values Supports escape Character. It also supports quoted
* string.Examples:
*
* - "a",1,true,1.5 -> ["a",1,true,1.5]
*
- "a,b",1,true,1.5 -> ["a,b",1,true,1.5]
*
- " a ",1,true,1.5 -> [" a ",1,true,1.5]
*
- ,,, -> [null,null,null,null]
*
- " a " , 1 , true , 1.5 ->[" a ",1,true,1.5]
*
- a | 1 | true | 1.5 Separator |->["a",1,true,1.5]
*
- " a "| 1 |true| 1.5 ->Separator |[" a ",1,true,1.5]
*
- "a, b"| 1 |true| 1.5 ->Separator |["a, b",1,true,1.5]
*
- a b | 1 |true| 1.5 ->Separator |["a b",1,true,1.5]
*
- "a\" b" | 1 |true| 1.5 ->Separator |["a\" b",1,true,1.5]
*
- | | | ->Separator |[null,null,null,null]
*
- "a"" b" | 1 |true| 1.5 ->Separator |["a\" b",1,true,1.5]
*
*
* @param data
* @param char[] optional char args
* char[0] : Separator - default value ','
* char[1] : escape charter - default value '\'
* @return
*/
public static Object[] parseCSV(String data, char... ch) {
List