- java.lang.Object
-
- com.erudika.para.core.utils.Utils
-
public final class Utils extends Object
Miscellaneous Para utilities.- Author:
- Alex Bogdanovski [alex@erudika.com]
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static Stringabbreviate(String str, int max)Abbreviates a string.static StringabbreviateInt(Number number, int decPlaces)Abbreviates an integer by adding a letter suffix at the end.static StringarrayJoin(List<String> arr, String separator)Joins a list of strings to String using a separator.static Stringbase64dec(String str)Decodes a string from Base64.static Stringbase64enc(byte[] str)Encodes a byte array to Base64.static Stringbase64encURL(byte[] str)Encodes a byte array to Base64.static Stringbcrypt(String s)bcrypt hash function implemented by Spring Security.static booleanbcryptMatches(String plain, String storedHash)Checks if a hash matches a string.static StringcompileMustache(Map<String,Object> context, String template)static StringcompileMustache(Map<String,Object> context, String template, boolean escapeHtml)Compiles a mustache template with a given scope (map of fields and values).static StringescapeJavascript(String str)Escapes JavaScript.static StringformatDate(Long timestamp, String format, Locale loc)Formats a date in a specific format.static StringformatDate(String format, Locale loc)Formats the date for today, in a specific format.static StringformatMessage(String msg, Object... params)Formats a messages containing {0}, {1}...static StringformatPrice(double price)Returns the price with two fractional digits at the end.static StringgenerateSecurityToken()Generates an authentication token - a random 32 byte string encoded in Base64.static StringgenerateSecurityToken(int length)Generates an authentication token - a random string encoded in Base64.static StringgenerateSecurityToken(int length, boolean urlSafe)Generates an authentication token - a random string encoded in Base64.static List<Field>getAllDeclaredFields(Class<? extends ParaObject> clazz)Returns a list of all declared fields in a class.static StringgetBaseURL(String url)The basic URL without any parameters: >scheme<:>authority<.static intgetCurrentYear()Returns the current year.static StringgetHostFromURL(String url)Returns the host part of the URL.static HumanTimegetHumanTime()HumanTime - a relative time formatter.static UtilsgetInstance()Returns an instance of this class.static LocalegetLocale(String localeStr)static String[]getMonths(Locale locale)Returns an array of the months in the Gregorian calendar.static StringgetNewId()Distributed id generator.static StringgetObjectURI(ParaObject obj, boolean includeName, boolean includeId)Returns the default URL for a given domain object.static StringgetSystemProperty(String name)Same asSystem.getProperty(java.lang.String).static StringhmacSHA256(String message, String secret)Computes the HmacSHA256 hash of a message.static booleanisBasicType(Class<?> clazz)Checks if a class is primitive, String or a primitive wrapper.static booleanisJsonType(String contentType)Checks if a response is of type JSON.static booleanisValidEmail(String email)Email validation.static booleanisValidURL(String url)URL validation.static StringmarkdownToHtml(String markdownString)Converts Markdown to HTML.static StringmarkdownToHtml(String markdownString, boolean htmlTagsRenderingEnabled)Converts Markdown to HTML.static Stringmd5(String s)md5 hash function.static StringnoSpaces(String str, String replaceWith)Converts spaces to dashes.static intround(float d)Rounds a float to an int.static doubleroundHalfUp(double d)Round up a double using the "half up" method.static doubleroundHalfUp(double d, int scale)Round up a double using the "half up" method.static StringsingularToPlural(String singul)Quick and dirty singular to plural conversion.static StringstripAndTrim(String str)Strips all symbols, punctuation, whitespace and control chars from a string.static StringstripAndTrim(String str, String replaceWith)Strips all symbols, punctuation, whitespace and control chars from a string.static StringstripAndTrim(String str, String replaceWith, boolean asciiOnly)Strips all symbols, punctuation, whitespace and control chars from a string.static StringstripHtml(String html)Strips all HTML tags from a string.static longtimestamp()Java timestamp.static Stringtype(Class<? extends ParaObject> clazz)Returns the simple name of a class in lowercase (AKA the type).static StringurlDecode(String s)Decodes a URL-encoded string.static StringurlEncode(String s)URL-encodes a string.
-
-
-
Method Detail
-
getInstance
public static Utils getInstance()
Returns an instance of this class.- Returns:
- an instance
-
getHumanTime
public static HumanTime getHumanTime()
HumanTime - a relative time formatter.- Returns:
- humantime instance
-
md5
public static String md5(String s)
md5 hash function.- Parameters:
s- the string to be hashed- Returns:
- an md5 hash
-
hmacSHA256
public static String hmacSHA256(String message, String secret)
Computes the HmacSHA256 hash of a message.- Parameters:
message- a message as UTF-8 encoded stringsecret- a secret key- Returns:
- base64(hmacSHA256(message, secret))
-
bcrypt
public static String bcrypt(String s)
bcrypt hash function implemented by Spring Security.- Parameters:
s- the string to be hashed- Returns:
- the hash
-
bcryptMatches
public static boolean bcryptMatches(String plain, String storedHash)
Checks if a hash matches a string.- Parameters:
plain- plain text stringstoredHash- hashed string- Returns:
- true if the hash matches
-
generateSecurityToken
public static String generateSecurityToken(int length, boolean urlSafe)
Generates an authentication token - a random string encoded in Base64.- Parameters:
length- the length of the generated tokenurlSafe- switches to a URL safe encoding- Returns:
- a random string
-
generateSecurityToken
public static String generateSecurityToken(int length)
Generates an authentication token - a random string encoded in Base64.- Parameters:
length- the length of the generated token- Returns:
- a random string
-
generateSecurityToken
public static String generateSecurityToken()
Generates an authentication token - a random 32 byte string encoded in Base64.- Returns:
- a random string
-
escapeJavascript
public static String escapeJavascript(String str)
Escapes JavaScript.- Parameters:
str- a javascript string- Returns:
- the escaped javascript string
-
stripHtml
public static String stripHtml(String html)
Strips all HTML tags from a string.- Parameters:
html- HTML string- Returns:
- just the text
-
markdownToHtml
public static String markdownToHtml(String markdownString)
Converts Markdown to HTML.- Parameters:
markdownString- Markdown- Returns:
- HTML
-
markdownToHtml
public static String markdownToHtml(String markdownString, boolean htmlTagsRenderingEnabled)
Converts Markdown to HTML.- Parameters:
markdownString- MarkdownhtmlTagsRenderingEnabled- if true, basic HTML tags will be rendered instead of escaped- Returns:
- HTML
-
compileMustache
public static String compileMustache(Map<String,Object> context, String template, boolean escapeHtml)
Compiles a mustache template with a given scope (map of fields and values).- Parameters:
context- a map of fields and valuestemplate- a Mustache template- Returns:
- the compiled template string
-
compileMustache
public static String compileMustache(Map<String,Object> context, String template)
- Parameters:
context- a map of fields and valuestemplate- a Mustache template- Returns:
- the compiled template string
- See Also:
compileMustache(java.util.Map, java.lang.String, boolean)
-
abbreviate
public static String abbreviate(String str, int max)
Abbreviates a string.- Parameters:
str- a stringmax- max length- Returns:
- a substring of that string
-
arrayJoin
public static String arrayJoin(List<String> arr, String separator)
Joins a list of strings to String using a separator.- Parameters:
arr- a list of stringsseparator- a separator string- Returns:
- a string
-
stripAndTrim
public static String stripAndTrim(String str)
Strips all symbols, punctuation, whitespace and control chars from a string.- Parameters:
str- a dirty string- Returns:
- a clean string
-
stripAndTrim
public static String stripAndTrim(String str, String replaceWith)
Strips all symbols, punctuation, whitespace and control chars from a string.- Parameters:
str- a dirty stringreplaceWith- a string to replace spaces with- Returns:
- a clean string
-
stripAndTrim
public static String stripAndTrim(String str, String replaceWith, boolean asciiOnly)
Strips all symbols, punctuation, whitespace and control chars from a string.- Parameters:
str- a dirty stringreplaceWith- a string to replace spaces withasciiOnly- if true, all non-ASCII characters will be stripped- Returns:
- a clean string
-
noSpaces
public static String noSpaces(String str, String replaceWith)
Converts spaces to dashes.- Parameters:
str- a string with spacesreplaceWith- a string to replace spaces with- Returns:
- a string with dashes
-
formatMessage
public static String formatMessage(String msg, Object... params)
Formats a messages containing {0}, {1}... etc. Used for translation.- Parameters:
msg- a message with placeholdersparams- objects used to populate the placeholders- Returns:
- a formatted message
-
base64enc
public static String base64enc(byte[] str)
Encodes a byte array to Base64.- Parameters:
str- the byte array- Returns:
- an encoded string
-
base64encURL
public static String base64encURL(byte[] str)
Encodes a byte array to Base64. URL safe.- Parameters:
str- the byte array- Returns:
- an encoded string
-
base64dec
public static String base64dec(String str)
Decodes a string from Base64.- Parameters:
str- the encoded string- Returns:
- a decoded string
-
formatDate
public static String formatDate(Long timestamp, String format, Locale loc)
Formats a date in a specific format.- Parameters:
timestamp- the Java timestampformat- the date formatloc- the locale instance- Returns:
- a formatted date
-
formatDate
public static String formatDate(String format, Locale loc)
Formats the date for today, in a specific format.- Parameters:
format- the date formatloc- the locale instance- Returns:
- today's date formatted
-
getCurrentYear
public static int getCurrentYear()
Returns the current year.- Returns:
- this year
-
timestamp
public static long timestamp()
Java timestamp.- Returns:
System.currentTimeMillis()
-
getMonths
public static String[] getMonths(Locale locale)
Returns an array of the months in the Gregorian calendar.- Parameters:
locale- the locale used for the months' names- Returns:
- an array of the 12 months
-
getLocale
public static Locale getLocale(String localeStr)
- Parameters:
localeStr- locale string- Returns:
- a
Localeinstance from a locale string.
-
round
public static int round(float d)
Rounds a float to an int.- Parameters:
d- a float- Returns:
- a rounded int
-
formatPrice
public static String formatPrice(double price)
Returns the price with two fractional digits at the end.- Parameters:
price- a price- Returns:
- $###.##
-
roundHalfUp
public static double roundHalfUp(double d)
Round up a double using the "half up" method.- Parameters:
d- a double- Returns:
- a double
-
roundHalfUp
public static double roundHalfUp(double d, int scale)Round up a double using the "half up" method.- Parameters:
d- a doublescale- the scale- Returns:
- a double
-
abbreviateInt
public static String abbreviateInt(Number number, int decPlaces)
Abbreviates an integer by adding a letter suffix at the end. E.g. "M" for millions, "K" for thousands, etc.- Parameters:
number- a big integerdecPlaces- decimal places- Returns:
- the rounded integer as a string
-
urlDecode
public static String urlDecode(String s)
Decodes a URL-encoded string.- Parameters:
s- a string- Returns:
- the decoded string
-
urlEncode
public static String urlEncode(String s)
URL-encodes a string.- Parameters:
s- a string- Returns:
- the encoded string
-
isValidURL
public static boolean isValidURL(String url)
URL validation.- Parameters:
url- a URL- Returns:
- true if the URL is valid
-
isValidEmail
public static boolean isValidEmail(String email)
Email validation.- Parameters:
email- email address- Returns:
- true if the URL is valid
-
getHostFromURL
public static String getHostFromURL(String url)
Returns the host part of the URL.- Parameters:
url- a URL- Returns:
- just the host
-
getBaseURL
public static String getBaseURL(String url)
The basic URL without any parameters: >scheme<:>authority<.- Parameters:
url- a full URL- Returns:
- the basic URL
-
getObjectURI
public static String getObjectURI(ParaObject obj, boolean includeName, boolean includeId)
Returns the default URL for a given domain object.- Parameters:
obj- the domain objectincludeName- true if we want to include the name of the object in the URLincludeId- true if we want to include the ID of the object in the URL- Returns:
- the object's URL - e.g. /users/123-name, /users/, /users/123
-
getSystemProperty
public static String getSystemProperty(String name)
Same asSystem.getProperty(java.lang.String).- Parameters:
name- the name of the property- Returns:
- the property value
-
isJsonType
public static boolean isJsonType(String contentType)
Checks if a response is of type JSON.- Parameters:
contentType- the value of "Content-Type" header- Returns:
- true if JSON
-
singularToPlural
public static String singularToPlural(String singul)
Quick and dirty singular to plural conversion.- Parameters:
singul- a word- Returns:
- a guess of its plural form
-
isBasicType
public static boolean isBasicType(Class<?> clazz)
Checks if a class is primitive, String or a primitive wrapper.- Parameters:
clazz- a class- Returns:
- true if primitive or wrapper
-
type
public static String type(Class<? extends ParaObject> clazz)
Returns the simple name of a class in lowercase (AKA the type).- Parameters:
clazz- a core class- Returns:
- just the name in lowercase or an empty string if clazz is null
-
getAllDeclaredFields
public static List<Field> getAllDeclaredFields(Class<? extends ParaObject> clazz)
Returns a list of all declared fields in a class. Transient and serialVersionUID fields are skipped. This method scans parent classes as well.- Parameters:
clazz- a class to scan- Returns:
- a list of fields including those of the parent classes excluding the Object class.
-
getNewId
public static String getNewId()
Distributed id generator. Relies on node/worker ids and datacenter ids to prevent collisions.- Returns:
- a long unique ID string of digits
-
-