Package com.strategyquant.lib
Class SQUtils
java.lang.Object
com.strategyquant.lib.SQUtils
The Class SQUtils.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionaddToErrors(ArrayList<String> errors, String errorMessage)Adds the to errors.static doubleadjustToTickSize(double value, double tickSize)Adjust to tick size.static voidarrayListToFile(ArrayList<String> list, String filePath, String delimiter)Array list to file.static intbetterHashCode(String input)Better hash code.static intbetterHashNumbers(int... params)Better hash numbers.static intbooleansHash(boolean... params)static ObjectcallMethod(Object instance, String methodName, Object arg)Call method.static ObjectcallMethod(Object instance, String methodName, Object[] args, boolean replacePrimitives)Call method.static ObjectcallMethod(Object instance, String methodName, Object[] args, Class[] argsClasses)Call method.static ObjectcallMethod(Object instance, String methodName, Object arg, Class argClass)Call method.static booleanCheck work directory is writable.static ArrayListcloneArrayList(ArrayList list)Clone array list.cloneHashMap(HashMap<String,Object> map)Clone hash map.static ObjectcloneObject(Object value)Clone object.static it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<Object>cloneValuesMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<Object> map)Clone values map.cloneValuesMapOld(HashMap<Integer,Object> map)Clone values map old.static intcompare(double a, double b, int decimals)Compare.static intcomputeFileHash(String filePath, int skipFirstLines)Compute file hash.static StringconvertIntTimetoHHMM(int time)Convert int timeto HHMM.static intconvertPriceToInt(double value, int decimals)Convert price to int.static StringcorrectClassName(String name)Correct class namestatic StringcorrectDirnameToResultKey(String resultKey)Correct dirname to result key.static StringcorrectNullString(String string)Correct null string.static StringcorrectResultKeyToDirname(String resultKey)Correct result key to dirname.static intcountFilesInDirectory(String folderName)Count files in directory.static voidcreateAndHandleBackupFiles(String path)static voidcreateAndHandleBackupFiles(String path, String fileContentsNew, int numberOfBackups)Create named backups of file & keep last 10static FilecreateFile(String filePath)Creates the file.static Stringd2(double d)efficient conversion to 0.00 DecimalFormatstatic StringD 2.static Stringd2String(double value, int decimals)D 2 string.static booleandateFormatValid(String date, String pattern)Date format valid.static StringdCommon(double d, long constant)static StringdecodeXmlKey(String key)Decode xml key.static booleandeleteDirectory(String path)Delete directory.static booleandeleteNestedFiles(File path)Delete nested files.static booleandeleteRecursive(File path)Delete recursive.static booleandoublesAreEqual(double value1, double value2)Doubles are equal.static intdoublesHash(double... params)static StringdoubleToString(double value)Double to string.static StringencodeXmlKey(String key)Encode xml key.static voidensureDirExists(String dirPath)Ensure dir exists.static StringextractNumber(String input)Extract number.static Stringfile2md5Hash(File f)File 2 md 5 hash.static voidfileToArrayList(ArrayList<String> list, String filePath, String delimiter)File to array list.static byte[]fileToBytes(File file)File to bytes.static StringfileToString(File file)File to string.static StringfileToString(File file, String charsetName)File to string.static StringfileToString(String path)File to string.static intfixAllowedRange(int value, int min, int max, int defaultValue)Fix allowed range.static voidfixExitmethodAttributes(org.jdom2.Element elStrategy)Fix exitmethod attributes.static StringfixHeikenAshi(String content)Fix heiken ashi.static doublefixPrice(double tickStep, double price)Fix price.static doublefixPrice(double tickStep, double price, int decimals)Fix price.static doublefixPriceSpecial(int orderType, double tickStep, double price, int decimals)static StringfixRenamedActionParams(String content)Fix renamed action params.static voidforceOpenUrlInDefaultWebBrowser(String url, Component parentComponent)Force open url in default web browser.static Stringformat(double val, int precision)Format.static StringformatBytesToHumanFormat(long allocatedSize)Format bytes to human format.static StringformatDate(long time, String pattern)Format date.static StringformatDuration(long milliseconds)Format duration.static StringgenerateUniqueName(String name, com.strategyquant.lib.utils.IUniqueNameChecker uniqueNameChecker)Generate unique name.static StringgetClasses(Class<?> aClass)Gets the classes.static intgetDecimalPlaces(double value)Gets the decimal places.static StringgetExtension(String name)Gets the extension.static longgetFileCrc(File file)static FilegetFirstFileFromDir(File dir)Gets the first file from dir.static StringGets the stack trace.static StringgetStackTrace(Throwable throwable)Gets the stack trace.static longgetTimeFromDate(String date, String pattern)Gets the time from date.static StringHttp get.static StringHttp get.static StringHttp post.static StringHttps post.static StringhttpUploadFile(String requestURL, String data, Map<String,String> headers, String attachmentName, String fileName, byte[] fileContent)Http upload file.static byte[]Input stream to bytes.static voidinputStreamToFile(InputStream inputStream, File file)Input stream to file.static StringInput stream to string.static StringinsertUppercaseSpaces(String str)Insert uppercase spaces.static intintsHash(int... params)static <T> TinvokeUnchecked(Constructor<T> constructor, Object... arguments)Invoke unchecked.static booleanisInByteArray(byte value, byte[] array)Checks if is in byte array.static booleanisInStringArray(String value, ArrayList<String> array)Checks if is in string array.static booleanisVowel(char c)Checks if is vowel.static StringjoinStrings(String... constants)Join strings.static intlevenshteinDistance(CharSequence lhs, CharSequence rhs)Levenshtein distance.static org.json.JSONArraylistBackupFiles(String path)List backups of file specified in pathlistSubdirectories(String directoryName)List subdirectories.static String[]listToStringArray(ArrayList<String> valueList)List to string array.static byte[]loadDataFromServer(String url)Load data from server.Load lines.static longlongHashCode(String input)Long hash code.static Stringmd5CheckSum(byte[] bytes)Md 5 check sum.static voidopenUrlInDefaultWebBrowser(String url, Component parentComponent)Open url in default web browser.static StringoptimizeLastSettings(String source)Optimize last settings.static doublepctToDouble(int value)Pct to double.static StringreadUTF(ObjectInput dis)Read UTF.static StringreadUTFIntern(ObjectInput dis)Read UTF intern.static StringremapFilePathByMap(String filePath, Map<String,String> fileMap)Remap file paths by mapstatic StringremoveHtmlTags(String input)Removes the html tags.static StringremoveUTF8BOM(String s)Removes the UTF 8 BOM.static StringremoveXmlns(String content)Removes the xmlns.static StringrenameActionParams(String content)Rename action params.static StringreplaceAll(String source, String os, String ns)Replace all.static StringreplaceLast(String string, String from, String to)Replace last.static Integerround(double value)Round.static doubleround(double value, int decimals)Round.static doubleround2(double value)Round 2.static doubleround6(double value)Round 6.static doubleround7(double value)Round 7.static doubleroundDown(double value, int decimals)Round down.static LongroundLong(double value)Round long.static doublesafeDivide(double f1, double f2)Safe divide.static StringsaveFileAs(byte[] data, String destDir, String fileName)Save file as.static StringshortenWord(String name, int charCount)Shorten word.static StringStack trace to string.static voidstringToFile(File file, String str)String to file.static voidstringToFile(String path, String str)String to file.static StringstripExtension(String name)Strip extension.static org.json.JSONArraytoJSONArray(String str)To JSON array.static StringtrimFilePath(String filePath, String trim)Trim file path.static voidwaitForKey(String message)Wait for key.static voidwriteUTF(ObjectOutput dos, String string)Write UTF.static StringxmlPrettyFormat(String uglyXml)Xml pretty format.
-
Constructor Details
-
SQUtils
public SQUtils()
-
-
Method Details
-
openUrlInDefaultWebBrowser
Open url in default web browser.- Parameters:
url- the urlparentComponent- the parent component
-
forceOpenUrlInDefaultWebBrowser
Force open url in default web browser.- Parameters:
url- the urlparentComponent- the parent component
-
fileToBytes
File to bytes.- Parameters:
file- the file- Returns:
- the byte[]
- Throws:
Exception- the exception
-
md5CheckSum
Md 5 check sum.- Parameters:
bytes- the bytes- Returns:
- the string
- Throws:
Exception- the exception
-
file2md5Hash
File 2 md 5 hash.- Parameters:
f- the f- Returns:
- the string
- Throws:
RuntimeException- (unchecked) on error calculating hash
-
fileToString
File to string.- Parameters:
path- the path- Returns:
- the string
- Throws:
Exception- the exception
-
fileToString
File to string.- Parameters:
file- the file- Returns:
- the string
- Throws:
Exception- the exception
-
fileToString
File to string.- Parameters:
file- the filecharsetName- the charset name- Returns:
- the string
- Throws:
Exception- the exception
-
createAndHandleBackupFiles
public static void createAndHandleBackupFiles(String path, String fileContentsNew, int numberOfBackups)Create named backups of file & keep last 10- Parameters:
path- the pathfileContentsNew-numberOfBackups-
-
createAndHandleBackupFiles
-
listBackupFiles
List backups of file specified in path- Parameters:
path- the path
-
stringToFile
String to file.- Parameters:
path- the pathstr- the str
-
stringToFile
String to file.- Parameters:
file- the filestr- the str
-
getFirstFileFromDir
Gets the first file from dir.- Parameters:
dir- the dir- Returns:
- the first file from dir
- Throws:
Exception- the exception
-
checkWorkDirectoryIsWritable
Check work directory is writable.- Parameters:
path- the path- Returns:
- true, if successful
-
convertPriceToInt
public static int convertPriceToInt(double value, int decimals)Convert price to int.- Parameters:
value- the valuedecimals- the decimals- Returns:
- the int
-
round
public static double round(double value, int decimals)Round.- Parameters:
value- the valuedecimals- the decimals- Returns:
- the double
-
round7
public static double round7(double value)Round 7.- Parameters:
value- the value- Returns:
- the double
-
round6
public static double round6(double value)Round 6.- Parameters:
value- the value- Returns:
- the double
-
round
Round.- Parameters:
value- the value- Returns:
- the integer
-
roundLong
Round long.- Parameters:
value- the value- Returns:
- the long
-
adjustToTickSize
public static double adjustToTickSize(double value, double tickSize)Adjust to tick size.- Parameters:
value- the valuetickSize- the tick size- Returns:
- the double
-
round2
public static double round2(double value)Round 2.- Parameters:
value- the value- Returns:
- the double
-
safeDivide
public static double safeDivide(double f1, double f2)Safe divide.- Parameters:
f1- the f 1f2- the f 2- Returns:
- the double
-
trimFilePath
Trim file path.- Parameters:
filePath- the file pathtrim- the trim- Returns:
- the string
-
remapFilePathByMap
Remap file paths by map- Parameters:
filePath- file path to be normalizedfileMap- file path remapping map key: matchPath => replaceValue key: matchPath => replaceValue example: {"/path1/path2/cc/dd" => "$REMAPPED_PATH12$/"} example: "/path1/path3/bb" => "$REMAPPED_PATH13$/" example: "/path1/aa" => "${REMAPPED_PATH1}/"- Returns:
- Normalized/remapped file path
-
getExtension
Gets the extension.- Parameters:
name- the name- Returns:
- the extension
-
stripExtension
Strip extension.- Parameters:
name- the name- Returns:
- the string
-
replaceLast
Replace last.- Parameters:
string- the stringfrom- the fromto- the to- Returns:
- the string
-
replaceAll
Replace all.- Parameters:
source- the sourceos- the osns- the ns- Returns:
- the string
-
joinStrings
Join strings.- Parameters:
constants- the constants- Returns:
- the string
-
listToStringArray
List to string array.- Parameters:
valueList- the value list- Returns:
- the string[]
-
deleteRecursive
Delete recursive.- Parameters:
path- the path- Returns:
- true, if successful
- Throws:
FileNotFoundException- the file not found exception
-
deleteNestedFiles
Delete nested files.- Parameters:
path- the path- Returns:
- true, if successful
-
generateUniqueName
public static String generateUniqueName(String name, com.strategyquant.lib.utils.IUniqueNameChecker uniqueNameChecker) throws ExceptionGenerate unique name.- Parameters:
name- the nameuniqueNameChecker- the unique name checker- Returns:
- the string
- Throws:
Exception- the exception
-
roundDown
public static double roundDown(double value, int decimals)Round down.- Parameters:
value- the valuedecimals- the decimals- Returns:
- the double
-
invokeUnchecked
Invoke unchecked.- Type Parameters:
T- the generic type- Parameters:
constructor- the constructorarguments- the arguments- Returns:
- the t
-
inputStreamToString
Input stream to string.- Parameters:
is- the is- Returns:
- the string
- Throws:
Exception- the exception
-
loadDataFromServer
Load data from server.- Parameters:
url- the url- Returns:
- the byte[]
- Throws:
Exception- the exception
-
inputStreamToBytes
Input stream to bytes.- Parameters:
is- the is- Returns:
- the byte[]
- Throws:
Exception- the exception
-
inputStreamToFile
Input stream to file.- Parameters:
inputStream- the input streamfile- the file- Throws:
Exception- the exception
-
saveFileAs
Save file as.- Parameters:
data- the datadestDir- the dest dirfileName- the file name- Returns:
- the string
- Throws:
Exception- the exception
-
formatDate
Format date.- Parameters:
time- the timepattern- the pattern- Returns:
- the string
-
getTimeFromDate
Gets the time from date.- Parameters:
date- the datepattern- the pattern- Returns:
- the time from date
-
dateFormatValid
Date format valid.- Parameters:
date- the datepattern- the pattern- Returns:
- true, if successful
-
callMethod
Call method.- Parameters:
instance- the instancemethodName- the method namearg- the arg- Returns:
- the object
- Throws:
Exception- the exception
-
callMethod
public static Object callMethod(Object instance, String methodName, Object arg, Class argClass) throws ExceptionCall method.- Parameters:
instance- the instancemethodName- the method namearg- the argargClass- the arg class- Returns:
- the object
- Throws:
Exception- the exception
-
callMethod
public static Object callMethod(Object instance, String methodName, Object[] args, boolean replacePrimitives) throws ExceptionCall method.- Parameters:
instance- the instancemethodName- the method nameargs- the argsreplacePrimitives- the replace primitives- Returns:
- the object
- Throws:
Exception- the exception
-
callMethod
public static Object callMethod(Object instance, String methodName, Object[] args, Class[] argsClasses) throws ExceptionCall method.- Parameters:
instance- the instancemethodName- the method nameargs- the argsargsClasses- the args classes- Returns:
- the object
- Throws:
Exception- the exception
-
removeUTF8BOM
Removes the UTF 8 BOM.- Parameters:
s- the s- Returns:
- the string
-
listSubdirectories
List subdirectories.- Parameters:
directoryName- the directory name- Returns:
- the array list
-
encodeXmlKey
Encode xml key.- Parameters:
key- the key- Returns:
- the string
-
decodeXmlKey
Decode xml key.- Parameters:
key- the key- Returns:
- the string
-
d2
D 2.- Parameters:
value- the value- Returns:
- the string
-
dCommon
- Parameters:
d-constant-- Returns:
-
d2
efficient conversion to 0.00 DecimalFormat- Parameters:
d-- Returns:
-
d2String
D 2 string.- Parameters:
value- the valuedecimals- the decimals- Returns:
- the string
-
doubleToString
Double to string.- Parameters:
value- the value- Returns:
- the string
-
getStackTrace
Gets the stack trace.- Returns:
- the stack trace
-
getStackTrace
Gets the stack trace.- Parameters:
throwable- the throwable- Returns:
- the stack trace
-
correctResultKeyToDirname
Correct result key to dirname.- Parameters:
resultKey- the result key- Returns:
- the string
-
correctDirnameToResultKey
Correct dirname to result key.- Parameters:
resultKey- the result key- Returns:
- the string
-
fixPrice
public static double fixPrice(double tickStep, double price)Fix price.- Parameters:
tickStep- the tick stepprice- the price- Returns:
- the double
-
fixPrice
public static double fixPrice(double tickStep, double price, int decimals)Fix price.- Parameters:
tickStep- the tick stepprice- the pricedecimals- the decimals- Returns:
- the double
-
fixPriceSpecial
public static double fixPriceSpecial(int orderType, double tickStep, double price, int decimals) -
format
Format.- Parameters:
val- the valprecision- the precision- Returns:
- the string
-
compare
public static int compare(double a, double b, int decimals)Compare.- Parameters:
a- the ab- the bdecimals- the decimals- Returns:
- the int
-
getDecimalPlaces
public static int getDecimalPlaces(double value)Gets the decimal places.- Parameters:
value- the value- Returns:
- the decimal places
-
insertUppercaseSpaces
Insert uppercase spaces.- Parameters:
str- the str- Returns:
- the string
-
fileToArrayList
public static void fileToArrayList(ArrayList<String> list, String filePath, String delimiter) throws ExceptionFile to array list.- Parameters:
list- the listfilePath- the file pathdelimiter- the delimiter- Throws:
Exception- the exception
-
arrayListToFile
public static void arrayListToFile(ArrayList<String> list, String filePath, String delimiter) throws ExceptionArray list to file.- Parameters:
list- the listfilePath- the file pathdelimiter- the delimiter- Throws:
Exception- the exception
-
countFilesInDirectory
Count files in directory.- Parameters:
folderName- the folder name- Returns:
- the int
-
createFile
Creates the file.- Parameters:
filePath- the file path- Returns:
- the file
- Throws:
Exception- the exception
-
correctNullString
Correct null string.- Parameters:
string- the string- Returns:
- the string
-
computeFileHash
public static int computeFileHash(String filePath, int skipFirstLines) throws FileNotFoundException, IOExceptionCompute file hash.- Parameters:
filePath- the file pathskipFirstLines- the skip first lines- Returns:
- the int
- Throws:
FileNotFoundException- the file not found exceptionIOException- Signals that an I/O exception has occurred.
-
ensureDirExists
Ensure dir exists.- Parameters:
dirPath- the dir path
-
removeXmlns
Removes the xmlns.- Parameters:
content- the content- Returns:
- the string
-
stackTraceToString
Stack trace to string.- Parameters:
e- the e- Returns:
- the string
-
extractNumber
Extract number.- Parameters:
input- the input- Returns:
- the string
-
removeHtmlTags
Removes the html tags.- Parameters:
input- the input- Returns:
- the string
-
shortenWord
Shorten word.- Parameters:
name- the namecharCount- the char count- Returns:
- the string
-
isVowel
public static boolean isVowel(char c)Checks if is vowel.- Parameters:
c- the c- Returns:
- true, if is vowel
-
getClasses
Gets the classes.- Parameters:
aClass- the a class- Returns:
- the classes
-
addToErrors
Adds the to errors.- Parameters:
errors- the errorserrorMessage- the error message- Returns:
- the array list
-
deleteDirectory
Delete directory.- Parameters:
path- the path- Returns:
- true, if successful
-
isInStringArray
Checks if is in string array.- Parameters:
value- the valuearray- the array- Returns:
- true, if is in string array
-
isInByteArray
public static boolean isInByteArray(byte value, byte[] array)Checks if is in byte array.- Parameters:
value- the valuearray- the array- Returns:
- true, if is in byte array
-
fixRenamedActionParams
Fix renamed action params.- Parameters:
content- the content- Returns:
- the string
-
renameActionParams
Rename action params.- Parameters:
content- the content- Returns:
- the string
-
fixHeikenAshi
Fix heiken ashi.- Parameters:
content- the content- Returns:
- the string
-
fixExitmethodAttributes
public static void fixExitmethodAttributes(org.jdom2.Element elStrategy)Fix exitmethod attributes.- Parameters:
elStrategy- the el strategy
-
loadLines
Load lines.- Parameters:
filePath- the file pathseparator- the separator- Returns:
- the array list
- Throws:
Exception- the exception
-
pctToDouble
public static double pctToDouble(int value)Pct to double.- Parameters:
value- the value- Returns:
- the double
-
httpUploadFile
public static String httpUploadFile(String requestURL, String data, Map<String,String> headers, String attachmentName, String fileName, byte[] fileContent) throws ExceptionHttp upload file.- Parameters:
requestURL- the request URLdata- the dataheaders- the headersattachmentName- the attachment namefileName- the file namefileContent- the file content- Returns:
- the string
- Throws:
Exception- the exception
-
httpPost
public static String httpPost(String url, String data, Map<String,String> headers) throws ExceptionHttp post.- Parameters:
url- the urldata- the dataheaders- the headers- Returns:
- the string
- Throws:
Exception- the exception
-
httpsPost
public static String httpsPost(String url, List<org.apache.http.NameValuePair> data, boolean throwInvalidStatusCode) throws ExceptionHttps post.- Parameters:
url- the urldata- the datathrowInvalidStatusCode- the throw invalid status code- Returns:
- the string
- Throws:
Exception- the exception
-
httpGet
Http get.- Parameters:
url- the url- Returns:
- the string
- Throws:
Exception- the exception
-
httpGet
Http get.- Parameters:
url- the urltimeout- the timeout in ms- Returns:
- the string
- Throws:
Exception- the exception
-
doublesAreEqual
public static boolean doublesAreEqual(double value1, double value2)Doubles are equal.- Parameters:
value1- the value 1value2- the value 2- Returns:
- true, if successful
-
convertIntTimetoHHMM
Convert int timeto HHMM.- Parameters:
time- the time- Returns:
- the string
-
formatBytesToHumanFormat
Format bytes to human format.- Parameters:
allocatedSize- the allocated size- Returns:
- the string
-
formatDuration
Format duration.- Parameters:
milliseconds- the milliseconds- Returns:
- the string
-
levenshteinDistance
Levenshtein distance.- Parameters:
lhs- the lhsrhs- the rhs- Returns:
- the int
-
cloneHashMap
Clone hash map.- Parameters:
map- the map- Returns:
- the hash map
-
cloneValuesMapOld
Clone values map old.- Parameters:
map- the map- Returns:
- the hash map
-
cloneValuesMap
public static it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<Object> cloneValuesMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<Object> map)Clone values map.- Parameters:
map- the map- Returns:
- the int 2 object open hash map
-
cloneArrayList
Clone array list.- Parameters:
list- the list- Returns:
- the array list
-
cloneObject
Clone object.- Parameters:
value- the value- Returns:
- the object
-
optimizeLastSettings
Optimize last settings.- Parameters:
source- the source- Returns:
- the string
-
waitForKey
Wait for key.- Parameters:
message- the message
-
toJSONArray
To JSON array.- Parameters:
str- the str- Returns:
- the JSON array
-
writeUTF
Write UTF.- Parameters:
dos- the dosstring- the string- Throws:
IOException- Signals that an I/O exception has occurred.
-
readUTFIntern
Read UTF intern.- Parameters:
dis- the dis- Returns:
- the string
- Throws:
IOException- Signals that an I/O exception has occurred.
-
readUTF
Read UTF.- Parameters:
dis- the dis- Returns:
- the string
- Throws:
IOException- Signals that an I/O exception has occurred.
-
betterHashCode
Better hash code.- Parameters:
input- the input- Returns:
- the int
-
longHashCode
Long hash code.- Parameters:
input- the input- Returns:
- the long
-
betterHashNumbers
public static int betterHashNumbers(int... params)Better hash numbers.- Parameters:
params- the params- Returns:
- the int
-
intsHash
public static int intsHash(int... params) -
doublesHash
public static int doublesHash(double... params) -
booleansHash
public static int booleansHash(boolean... params) -
xmlPrettyFormat
Xml pretty format.- Parameters:
uglyXml- the ugly xml- Returns:
- the string
- Throws:
Exception- the exception
-
fixAllowedRange
public static int fixAllowedRange(int value, int min, int max, int defaultValue)Fix allowed range.- Parameters:
value- the valuemin- the minmax- the maxdefaultValue- the default value- Returns:
- the int
-
correctClassName
Correct class name- Parameters:
name-- Returns:
- the string
- Throws:
Exception- the exception
-
getFileCrc
- Parameters:
file-- Returns:
- Throws:
Exception
-