public class OpenmrsUtil extends Object
Modifier and Type | Method and Description |
---|---|
static <K,V> void |
addToListMap(Map<K,List<V>> map,
K key,
V obj) |
static <K,V> void |
addToSetMap(Map<K,Set<V>> map,
K key,
V obj)
Allows easy manipulation of a Map<?
|
static void |
applyLogLevel(String logClass,
String logLevel)
Deprecated.
As of 2.4.4, 2.5.1, and 2.6.0; replaced by
OpenmrsLoggingUtil.applyLogLevel(String, String) |
static void |
applyLogLevels()
Deprecated.
As of 2.4.4, 2.5.1, and 2.6.0; replaced by
OpenmrsLoggingUtil.applyLogLevels() |
static void |
closeStream(Closeable closableStream)
A null-safe and exception safe way to close an inputstream or an outputstream
|
static boolean |
collectionContains(Collection<?> objects,
Object obj)
Loops over the collection to check to see if the given object is in that collection.
|
static int |
compare(Date d1,
Date d2)
Compares two java.util.Date objects, but handles java.sql.Timestamp (which is not directly
comparable to a date) by dropping its nanosecond value.
|
static <E> Collection<Collection<E>> |
compareLists(Collection<E> origList,
Collection<E> newList)
Compares origList to newList returning map of differences
|
static int |
compareWithNullAsEarliest(Date d1,
Date d2)
Compares two Date/Timestamp objects, treating null as the earliest possible date.
|
static <E extends Comparable<E>> |
compareWithNullAsGreatest(E c1,
E c2) |
static int |
compareWithNullAsLatest(Date d1,
Date d2)
Compares two Date/Timestamp objects, treating null as the earliest possible date.
|
static <E extends Comparable<E>> |
compareWithNullAsLowest(E c1,
E c2) |
static List<Concept> |
conceptListHelper(String descriptor) |
static Set<Concept> |
conceptSetHelper(String descriptor) |
static <T> boolean |
containsAny(Collection<T> collection,
Collection<T> elements) |
static boolean |
containsDigit(String test) |
static boolean |
containsOnlyDigits(String test) |
static boolean |
containsUpperAndLowerCase(String test) |
static Integer |
convertToInteger(Long longValue)
This method converts the given Long value to an Integer.
|
static void |
copyFile(InputStream inputStream,
OutputStream outputStream)
Copy file from inputStream onto the outputStream inputStream is not closed in this method
outputStream /is/ closed at completion of this method
|
static boolean |
deleteDirectory(File dir)
Recursively deletes files in the given
dir folder |
static List<Concept> |
delimitedStringToConceptList(String delimitedString,
String delimiter)
Parses and loads a delimited list of concept ids or names
|
static Map<String,Concept> |
delimitedStringToConceptMap(String delimitedString,
String delimiter) |
static List<Integer> |
delimitedStringToIntegerList(String delimitedString,
String delimiter) |
static Date |
firstSecondOfDay(Date date)
Return a date that is the same day as the passed in date, but the hours and seconds are the
earliest possible for that day.
|
static boolean |
folderContains(File folder,
String filename)
Look for a file named
filename in folder |
static Date |
fromDateHelper(Date comparisonDate,
Integer withinLastDays,
Integer withinLastMonths,
Integer untilDaysAgo,
Integer untilMonthsAgo,
Date sinceDate,
Date untilDate) |
static String |
generateUid()
Creates a uid of length 20
|
static String |
generateUid(Integer size)
Creates a relatively acceptable unique string of the give size
|
static String |
getApplicationDataDirectory()
Returns the application data directory.
|
static File |
getApplicationDataDirectoryAsFile() |
static Map<String,String> |
getCorePrivileges()
These are the privileges that are required by OpenMRS.
|
static Map<String,String> |
getCoreRoles()
All roles returned by this method are inserted into the database if they do not exist
already.
|
static SimpleDateFormat |
getDateFormat(Locale locale)
Get the current user's date format Will look similar to "mm-dd-yyyy".
|
static SimpleDateFormat |
getDateTimeFormat(Locale locale)
Get the current user's datetime format Will look similar to "mm-dd-yyyy hh:mm a".
|
static Set<String> |
getDeclaredFields(Class<?> clazz)
Get declared field names of a class
|
static File |
getDirectoryInApplicationDataDirectory(String folderName)
Find the given folderName in the application data directory.
|
static byte[] |
getFileAsBytes(File file)
Return a byte array representation of the given file
|
static String |
getFileAsString(File file)
Return a string representation of the given file
|
static String |
getFileMimeType(File file)
Get mime type of the given file
|
static Date |
getLastMomentOfDay(Date day)
Gets the date having the last millisecond of a given day.
|
static MemoryAppender |
getMemoryAppender()
Deprecated.
As of 2.4.4, 2.5.1, and 2.6.0; replaced by
OpenmrsLoggingUtil.getMemoryAppender() instead |
static String |
getMessage(String code,
Object... args)
Utility method for getting the translation for the passed code
|
static String |
getOpenmrsLogLocation()
Deprecated.
As of 2.4.4, 2.5.1, and 2.6.0; replaced by
OpenmrsLoggingUtil.getOpenmrsLogLocation() |
static String |
getOpenMRSVersionInTestMode()
Gets OpenMRS version name under test mode.
|
static File |
getOutFile(File dir,
Date date,
User user)
Gets an out File object.
|
static InputStream |
getResourceInputStream(URL url)
Opens input stream for given resource.
|
static Properties |
getRuntimeProperties(String applicationName)
Finds and loads the runtime properties file for a specific OpenMRS application.
|
static String |
getRuntimePropertiesFileNameInTestMode() |
static String |
getRuntimePropertiesFilePathName(String applicationName)
Gets the full path and name of the runtime properties file.
|
static SimpleDateFormat |
getTimeFormat(Locale locale)
Get the current user's time format Will look similar to "hh:mm a".
|
static boolean |
isConceptInList(Concept concept,
List<Concept> list) |
static Boolean |
isInAbsoluteNumericRange(Float value,
ConceptNumeric concept) |
static Boolean |
isInCriticalNumericRange(Float value,
ConceptNumeric concept) |
static Boolean |
isInNormalNumericRange(Float value,
ConceptNumeric concept) |
static boolean |
isStringInArray(String str,
String[] arr) |
static boolean |
isTestMode()
Checks whether the system is running in test mode
|
static Boolean |
isValidNumericValue(Float value,
ConceptNumeric concept) |
static boolean |
isYesterday(Date date)
Checks if the passed in date's day of the year is the one that comes immediately before that
of the current date
|
static <E> String |
join(Collection<E> c,
String separator)
Deprecated.
as of 2.2 use Java's
String.join(java.lang.CharSequence, java.lang.CharSequence...) or Apache Commons StringUtils.join for iterables which do not extend CharSequence |
static void |
loadProperties(Properties props,
File propertyFile)
Convenience method used to load properties from the given file.
|
static void |
loadProperties(Properties props,
InputStream inputStream)
This method is a replacement for Properties.load(InputStream) so that we can load in utf-8
characters.
|
static <Arg1,Arg2 extends Arg1> |
nullSafeEquals(Arg1 d1,
Arg2 d2) |
static boolean |
nullSafeEqualsIgnoreCase(String s1,
String s2)
Performs a case insensitive Comparison of two strings taking care of null values
|
static Object |
parse(String string,
Class clazz)
Takes a String (e.g. a user-entered one) and parses it into an object of the specified class
|
static Map<String,String> |
parseParameterList(String paramList)
Takes a String like "size=compact|order=date" and returns a Map<String,String> from the
keys to the values.
|
static Date |
safeDate(Date d1) |
static void |
saveDocument(Document doc,
File outFile)
Save the given xml document to the given outfile
|
static void |
setApplicationDataDirectory(String path)
Can be used to override default application data directory.
|
static void |
setupLogAppenders()
Deprecated.
As of 2.4.4, 2.5.1, and 2.6.0; replaced by
OpenmrsLoggingUtil.reloadLoggingConfiguration() |
static String |
shortenedStackTrace(String stackTrace)
Convert a stack trace into a shortened version for easier viewing and data storage, excluding
those lines we are least concerned with; should average about 60% reduction in stack trace
length
|
static void |
startup(Properties p)
Initialize global settings Find and load modules
|
static void |
storeProperties(Properties properties,
File file,
String comment)
Convenience method to replace Properties.store(), which isn't UTF-8 compliant
NOTE: In Java 6, you will be able to pass the load() and store() methods a UTF-8 Reader/Writer object as an argument, making this method unnecessary. |
static void |
storeProperties(Properties properties,
OutputStream outStream,
String comment)
Convenience method to replace Properties.store(), which isn't UTF-8 compliant NOTE: In Java
6, you will be able to pass the load() and store() methods a UTF-8 Reader/Writer object as an
argument.
|
static boolean |
stringStartsWith(String str,
String[] prefixes)
Tests if the given String starts with any of the specified prefixes
|
static Date |
toDateHelper(Date comparisonDate,
Integer withinLastDays,
Integer withinLastMonths,
Integer untilDaysAgo,
Integer untilMonthsAgo,
Date sinceDate,
Date untilDate) |
static File |
url2file(URL url)
Utility method to convert local URL to a File object.
|
static void |
validateJavaVersion()
Checks whether the current JVM version is at least Java 8.
|
static void |
validatePassword(String username,
String password,
String systemId)
Utility to check the validity of a password for a certain
User . |
public static <E> Collection<Collection<E>> compareLists(Collection<E> origList, Collection<E> newList)
origList
- newList
- public static Boolean isInNormalNumericRange(Float value, ConceptNumeric concept)
public static Boolean isInCriticalNumericRange(Float value, ConceptNumeric concept)
public static Boolean isInAbsoluteNumericRange(Float value, ConceptNumeric concept)
public static Boolean isValidNumericValue(Float value, ConceptNumeric concept)
public static String getFileAsString(File file) throws IOException
file
- IOException
public static byte[] getFileAsBytes(File file) throws IOException
file
- IOException
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException
inputStream
- Stream to copy fromoutputStream
- Stream/location to copy toIOException
- thrown if an error occurs during read/write
Should not copy the outputstream if outputstream is null
Should not copy the outputstream if inputstream is null
Should copy inputstream to outputstream and close the outputstreampublic static String getFileMimeType(File file)
file
- public static boolean folderContains(File folder, String filename)
filename
in folderfolder
- filename
- public static Map<String,String> getCorePrivileges()
AddOnStartup
to know which privs, upon startup or loading of a module, to insert into
the database if they do not exist already. These privileges are not allowed to be deleted.
They are marked as 'locked' in the administration screens.PrivilegeConstants
,
Context.checkCoreDataset()
public static Map<String,String> getCoreRoles()
public static void startup(Properties p)
p
- properties from runtime configuration@Deprecated public static MemoryAppender getMemoryAppender()
OpenmrsLoggingUtil.getMemoryAppender()
instead@Logging(ignore=true) @Deprecated public static void applyLogLevels()
OpenmrsLoggingUtil.applyLogLevels()
@Deprecated public static void setupLogAppenders()
OpenmrsLoggingUtil.reloadLoggingConfiguration()
@Deprecated public static void applyLogLevel(String logClass, String logLevel)
OpenmrsLoggingUtil.applyLogLevel(String, String)
logClass
to logLevel
.logClass
- optional string giving the class level to change. Defaults to
OpenmrsConstants.LOG_CLASS_DEFAULT . Should be something like org.openmrs.___logLevel
- one of OpenmrsConstants.LOG_LEVEL_*public static Map<String,String> parseParameterList(String paramList)
paramList
- String
with a list of parameterspublic static <Arg1,Arg2 extends Arg1> boolean nullSafeEquals(Arg1 d1, Arg2 d2)
public static int compare(Date d1, Date d2)
public static int compareWithNullAsEarliest(Date d1, Date d2)
public static int compareWithNullAsLatest(Date d1, Date d2)
public static <E extends Comparable<E>> int compareWithNullAsLowest(E c1, E c2)
public static <E extends Comparable<E>> int compareWithNullAsGreatest(E c1, E c2)
@Deprecated public static <E> String join(Collection<E> c, String separator)
String.join(java.lang.CharSequence, java.lang.CharSequence...)
or Apache Commons StringUtils.join for iterables which do not extend CharSequence
c
- Collection to be joinedseparator
- string to put between all elementspublic static List<Concept> delimitedStringToConceptList(String delimitedString, String delimiter)
delimitedString
- the delimited list of concept ids or namesdelimiter
- the delimiter, e.g. ","public static Map<String,Concept> delimitedStringToConceptMap(String delimitedString, String delimiter)
public static Date getLastMomentOfDay(Date day)
day
- the day.public static Date firstSecondOfDay(Date date)
date
- date to adjustpublic static boolean deleteDirectory(File dir) throws IOException
dir
folderdir
- File directory to deleteIOException
- if dir
is not a directorypublic static File url2file(URL url)
url
- an URLnull
if URL is not local
Should return null given null parameterpublic static InputStream getResourceInputStream(URL url) throws IOException
url
- resource URLIOException
- if any I/O error has occurredpublic static String getApplicationDataDirectory()
Returns the application data directory. Searches for the value first in the "OPENMRS_APPLICATION_DATA_DIRECTORY" system property and "application_data_directory" runtime property, then in the servlet init parameter "application.data.directory." If not found, returns: a) "{user.home}/.OpenMRS" on UNIX-based systems b) "{user.home}\Application Data\OpenMRS" on Windows
public static File getApplicationDataDirectoryAsFile()
public static void setApplicationDataDirectory(String path)
Note that it will not override application data directory provided as a system property.
path
- @Deprecated public static String getOpenmrsLogLocation()
OpenmrsLoggingUtil.getOpenmrsLogLocation()
OpenmrsConstants.LOG_OPENMRS_FILE_APPENDER
or if the appender with that name is not one of the default file
appending types.public static void validateJavaVersion()
APIException
- if the current JVM version is earlier than Java 8public static File getDirectoryInApplicationDataDirectory(String folderName) throws APIException
folderName
- APIException
public static void saveDocument(Document doc, File outFile)
doc
- Document to be savedoutFile
- file pointer to the location the xml file is to be saved topublic static List<Integer> delimitedStringToIntegerList(String delimitedString, String delimiter)
public static boolean stringStartsWith(String str, String[] prefixes)
str
- the string to testprefixes
- an array of prefixes to test againstpublic static Date fromDateHelper(Date comparisonDate, Integer withinLastDays, Integer withinLastMonths, Integer untilDaysAgo, Integer untilMonthsAgo, Date sinceDate, Date untilDate)
public static Date toDateHelper(Date comparisonDate, Integer withinLastDays, Integer withinLastMonths, Integer untilDaysAgo, Integer untilMonthsAgo, Date sinceDate, Date untilDate)
public static <T> boolean containsAny(Collection<T> collection, Collection<T> elements)
collection
- elements
- public static <K,V> void addToSetMap(Map<K,Set<V>> map, K key, V obj)
public static SimpleDateFormat getDateFormat(Locale locale)
public static SimpleDateFormat getTimeFormat(Locale locale)
public static SimpleDateFormat getDateTimeFormat(Locale locale)
public static Object parse(String string, Class clazz)
string
- clazz
- clazz
with the data from string
public static boolean collectionContains(Collection<?> objects, Object obj)
obj
will return falseobjects
- collection to loop overobj
- Object to look for in the objects
public static File getOutFile(File dir, Date date, User user)
dir
- directory to make the random filename indate
- optional Date object used for the nameuser
- optional User creating this file objectpublic static String generateUid(Integer size)
public static String generateUid()
generateUid(Integer)
public static void storeProperties(Properties properties, File file, String comment)
properties
- file
- comment
- public static void storeProperties(Properties properties, OutputStream outStream, String comment)
properties
- outStream
- comment
- (which appears in comments in properties file)public static void loadProperties(Properties props, InputStream inputStream)
props
- the properties object to write intoinputStream
- the input stream to read frompublic static void loadProperties(Properties props, File propertyFile)
props
- the properties object to be loaded intopropertyFile
- the properties file to readpublic static String getMessage(String code, Object... args)
code
- the message key to lookupargs
- the replacement values for the translation stringpublic static void validatePassword(String username, String password, String systemId) throws PasswordException
User
. Passwords must be
non-null. Their required strength is configured via global properties:
Description | Property | Default Value |
---|---|---|
Require that it not match the User 's username or system id
| OpenmrsConstants.GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID |
true |
Require a minimum length | OpenmrsConstants.GP_PASSWORD_MINIMUM_LENGTH |
8 |
Require both an upper and lower case character | OpenmrsConstants.GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE |
true |
Require at least one numeric character | OpenmrsConstants.GP_PASSWORD_REQUIRES_DIGIT |
true |
Require at least one non-numeric character | OpenmrsConstants.GP_PASSWORD_REQUIRES_NON_DIGIT |
true |
Require a match on the specified regular expression | OpenmrsConstants.GP_PASSWORD_CUSTOM_REGEX |
null |
username
- user name of the user with password to validatedpassword
- string that will be validatedsystemId
- system id of the user with password to be validatedPasswordException
public static boolean containsUpperAndLowerCase(String test)
test
- the string to testpublic static boolean containsOnlyDigits(String test)
test
- the string to testpublic static boolean containsDigit(String test)
test
- the string to testpublic static void closeStream(Closeable closableStream)
closableStream
- an InputStream or OutputStream to closepublic static String shortenedStackTrace(String stackTrace)
stackTrace
- original stack trace from an errorpublic static Properties getRuntimeProperties(String applicationName)
Finds and loads the runtime properties file for a specific OpenMRS application. Searches for the file in this order: 1) {current directory}/{applicationname}_runtime.properties 2) an environment variable called "{APPLICATIONNAME}_RUNTIME_PROPERTIES_FILE" 3) {openmrs_app_dir}/{applicationName}_runtime.properties // openmrs_app_dir is typically {user_home}/.OpenMRS
applicationName
- (defaults to "openmrs") the name of the running OpenMRS application,
e.g. if you have deployed OpenMRS as a web application you would give the deployed
context path heregetApplicationDataDirectory()
public static boolean isTestMode()
public static String getRuntimePropertiesFilePathName(String applicationName)
applicationName
- (defaults to "openmrs") the name of the running OpenMRS application,
e.g. if you have deployed OpenMRS as a web application you would give the deployed
context path herepublic static String getRuntimePropertiesFileNameInTestMode()
public static String getOpenMRSVersionInTestMode()
public static boolean nullSafeEqualsIgnoreCase(String s1, String s2)
s1
- the string to compares2
- the string to comparepublic static Integer convertToInteger(Long longValue)
longValue
- the value to convertIllegalArgumentException
- if the long value does not fit into an integerpublic static boolean isYesterday(Date date)
date
- the date to checkCopyright © 2024 OpenMRS Inc.. All rights reserved.