Package org.opends.server.util
Class StaticUtils
- java.lang.Object
-
- org.opends.server.util.StaticUtils
-
@PublicAPI(stability=UNCOMMITTED, mayInvoke=true) public final class StaticUtils extends Object
This class defines a number of static utility methods that may be used throughout the server. Note that because of the frequency with which these methods are expected to be used, very little debug logging will be performed to prevent the log from filling up with unimportant calls and to reduce the impact that debugging may have on performance.
-
-
Field Summary
Fields Modifier and Type Field Description static StringALL_OPERATIONAL_ATTRIBUTESThe pattern that asks a search request to return all operational attributes.static String[]ALL_USER_AND_OPERATIONAL_ATTRIBUTESThe pattern that asks a search request to return all user and operational attributes.static StringALL_USER_ATTRIBUTESThe pattern that asks a search request to return all user attributes.static StringHOST_NAME_FILEThe relative path where the setup stores the name of the host the user provides.static intINT_SIZEThe number of bytes of a Java int.static intKBNumber of bytes in a Kibibyte.static intLONG_SIZEThe number of bytes of a Java long.static intMBNumber of bytes in a Mebibyte.static StringOPENDJ_JAVA_HOMESpecific environment variable used by the scripts to find java.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static voidaddMissingSuperiorObjectClasses(Entry entry)Add all of the superior objectclasses to the specified entry if they are not already present.static EntryaddRdnAttributes(Entry entry)Add the RDN attribute(s) to the provided entry.static FilteranyEqualsTo(Collection<AttributeType> attributeTypes, ByteString value)Builds an "or" filter where one of the provided attribute types must match the provided value.static voidbyteArrayToHexPlusAscii(StringBuilder buffer, byte[] b, int indent)Appends a string representation of the provided byte array to the given buffer using the specified indent.static StringbytesToColonDelimitedHex(byte[] b)Retrieves a string representation of the contents of the provided byte array using hexadecimal characters and a colon between each byte.static StringbytesToHex(ByteSequence b)Retrieves a string representation of the contents of the provided byte sequence using hexadecimal characters and a space between each byte.static StringbytesToHexNoSpace(byte[] b)Retrieves a string representation of the contents of the provided byte array using hexadecimal characters with no space between each byte.static voidcheckVersionMismatch()Checks if the binary version is the same than the instance version.static voidcopyKeepingTargetPermissions(Path source, Path target, CopyOption... copyOptions)Copy a file, but preserve the ACLs/POSIX permissions on any existing target.static EntrycreateEntry(Dn dn, Schema schema)Creates a new, blank entry with the given DN.static voidextractZipArchive(File zipFile, File targetDirectory, List<String> executableDirectories, List<String> executableFiles)Extracts the provided zip archive to the provided target directory.static StringformatDateTimeString(TemporalAccessor instant)Formats a Date to String representation in "yyyyMMddHHmmss'Z'".static PathgetFileForPath(String path)Retrieves aPathobject corresponding to the specified path.static PathgetFileForPath(String path, ServerContext serverContext)Retrieves aPathobject corresponding to the specified path.static PathgetFileForPath(Path path, ServerContext serverContext)Retrieves aPathobject corresponding to the specified path.static List<String>getFileNames(Path[] files)Returns the sorted list of names of provided files.static StringgetObjectClassName(Rdn rdn)Best effort to find structural object class name of the provided base entry RDN.static byte[]hexStringToByteArray(String hexString)Converts the provided hexadecimal string to a byte array.static booleanisEmailAddress(String addr)Indicates whether a string represents a syntactically correct email address.static booleanisServerRunning()Returns whether the server located in the provided path is running.static voidmoveDirectory(Path sourceDirectory, Path targetDirectory)Moves the indicated directory to the specified directory by recursively copying and then removing the existing directory.static voidmoveFileSafely(Path source, Path target)Attempts to move a file atomically and consistently.static booleanneedsBase64Encoding(String valueString)Indicates whether the provided value needs to be base64-encoded if it is represented in LDIF form.static booleanneedsBase64Encoding(ByteSequence valueBytes)Indicates whether the provided value needs to be base64-encoded if it is represented in LDIF form.static InstantparseDateTimeString(String timeStr)Converts a string representing a time in "yyyyMMddHHmmss.SSS'Z'" or "yyyyMMddHHmmss" to aDate.static booleanrecursiveDelete(Path path)Attempts to delete the specified file or directory.static LocalizableMessagesecondsToTimeString(long numSeconds)Retrieves a user-friendly string that indicates the length of time (in days, hours, minutes, and seconds) in the specified number of seconds.static voidsleep(long millis)CallsThread.sleep(long), surrounding it with the mandatorytry/catch(InterruptedException)block.static StringtoLowerCase(String s)Returns a lower-case string representation of a given string, verifying for null input string.static Collection<Pattern>toPatterns(Collection<String> regExps)Returns a collection of patterns representing provided regular expression strings.static booleanvalidatePatterns(Collection<String> blackListRegExps, Collection<String> whiteListRegExps, Collection<LocalizableMessage> unacceptableReasons)Returns whether all the provided black and white list strings are valid regular expression patterns by usingPattern.compile(String).
-
-
-
Field Detail
-
OPENDJ_JAVA_HOME
public static final String OPENDJ_JAVA_HOME
Specific environment variable used by the scripts to find java.- See Also:
- Constant Field Values
-
HOST_NAME_FILE
public static final String HOST_NAME_FILE
The relative path where the setup stores the name of the host the user provides. This is used for instance to generate the self-signed admin certificate the first time the server starts.
-
INT_SIZE
public static final int INT_SIZE
The number of bytes of a Java int. A Java int is 32 bits, i.e. 4 bytes.- See Also:
- Constant Field Values
-
LONG_SIZE
public static final int LONG_SIZE
The number of bytes of a Java long. A Java int is 64 bits, i.e. 8 bytes.- See Also:
- Constant Field Values
-
KB
public static final int KB
Number of bytes in a Kibibyte.Example usage:
int _10KB = 10 * KB;
- See Also:
- Constant Field Values
-
MB
public static final int MB
Number of bytes in a Mebibyte.Example usage:
int _10MB = 10 * MB;
- See Also:
- Constant Field Values
-
ALL_USER_ATTRIBUTES
public static final String ALL_USER_ATTRIBUTES
The pattern that asks a search request to return all user attributes.- See Also:
- Constant Field Values
-
ALL_OPERATIONAL_ATTRIBUTES
public static final String ALL_OPERATIONAL_ATTRIBUTES
The pattern that asks a search request to return all operational attributes.- See Also:
- Constant Field Values
-
ALL_USER_AND_OPERATIONAL_ATTRIBUTES
public static final String[] ALL_USER_AND_OPERATIONAL_ATTRIBUTES
The pattern that asks a search request to return all user and operational attributes.
-
-
Method Detail
-
bytesToHexNoSpace
public static String bytesToHexNoSpace(byte[] b)
Retrieves a string representation of the contents of the provided byte array using hexadecimal characters with no space between each byte.- Parameters:
b- The byte array containing the data.- Returns:
- A string representation of the contents of the provided byte array using hexadecimal characters.
-
bytesToHex
public static String bytesToHex(ByteSequence b)
Retrieves a string representation of the contents of the provided byte sequence using hexadecimal characters and a space between each byte.- Parameters:
b- The byte sequence containing the data.- Returns:
- A string representation of the contents of the provided byte sequence using hexadecimal characters.
-
bytesToColonDelimitedHex
public static String bytesToColonDelimitedHex(byte[] b)
Retrieves a string representation of the contents of the provided byte array using hexadecimal characters and a colon between each byte.- Parameters:
b- The byte array containing the data.- Returns:
- A string representation of the contents of the provided byte array using hexadecimal characters.
-
byteArrayToHexPlusAscii
public static void byteArrayToHexPlusAscii(StringBuilder buffer, byte[] b, int indent)
Appends a string representation of the provided byte array to the given buffer using the specified indent. The data will be formatted with sixteen hex bytes in a row followed by the ASCII representation, then wrapping to a new line as necessary.- Parameters:
buffer- The buffer to which the information is to be appended.b- The byte array containing the data to write.indent- The number of spaces to indent the output.
-
hexStringToByteArray
public static byte[] hexStringToByteArray(String hexString) throws ParseException
Converts the provided hexadecimal string to a byte array.- Parameters:
hexString- The hexadecimal string to convert to a byte array.- Returns:
- The byte array containing the binary representation of the provided hex string.
- Throws:
ParseException- If the provided string contains invalid hexadecimal digits or does not contain an even number of digits.
-
needsBase64Encoding
public static boolean needsBase64Encoding(ByteSequence valueBytes)
Indicates whether the provided value needs to be base64-encoded if it is represented in LDIF form.- Parameters:
valueBytes- The binary representation of the attribute value for which to make the determination.- Returns:
trueif the value needs to be base64-encoded if it is represented in LDIF form, orfalseif not.
-
needsBase64Encoding
public static boolean needsBase64Encoding(String valueString)
Indicates whether the provided value needs to be base64-encoded if it is represented in LDIF form.- Parameters:
valueString- The string representation of the attribute value for which to make the determination.- Returns:
trueif the value needs to be base64-encoded if it is represented in LDIF form, orfalseif not.
-
toLowerCase
public static String toLowerCase(String s)
Returns a lower-case string representation of a given string, verifying for null input string.- Parameters:
s- the mixed case string- Returns:
- a lower-case string
- See Also:
StaticUtils.toLowerCase(String)
-
recursiveDelete
public static boolean recursiveDelete(Path path)
Attempts to delete the specified file or directory. If it is a directory, then any files or subdirectories that it contains will be recursively deleted as well.- Parameters:
path- The file or directory to be removed.- Returns:
trueif the specified file and any subordinates are all successfully removed, orfalseif at least one element in the subtree could not be removed or file does not exists.
-
moveDirectory
public static void moveDirectory(Path sourceDirectory, Path targetDirectory) throws IOException
Moves the indicated directory to the specified directory by recursively copying and then removing the existing directory. The directory to move must exist and must be a directory. The target directory must not exist.- Parameters:
sourceDirectory- The directory to move to the target directory.targetDirectory- The new directory into which the source files and directories should be moved.- Throws:
IOException- If a problem occurs while attempting to move the directory.
-
copyKeepingTargetPermissions
public static void copyKeepingTargetPermissions(Path source, Path target, CopyOption... copyOptions) throws IOException
Copy a file, but preserve the ACLs/POSIX permissions on any existing target.- Parameters:
source- the path to the file to copy.target- the path to the target file.copyOptions- any valid options accepted byFiles.copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...).- Throws:
IOException- if an error occurs copying the file or accessing the permissions.
-
moveFileSafely
public static void moveFileSafely(Path source, Path target) throws IOException
Attempts to move a file atomically and consistently. This method delegates toFiles.move(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...), but enhances it by first ensuring that the source file has been fsync'd to disk. It then attempts to move the file atomically, if supported by the underlying file-system, and then falls back to a non-atomic move.- Parameters:
source- The path of the file to be moved.target- The new path.- Throws:
IOException- If an I/O error occurs.
-
getFileNames
public static List<String> getFileNames(Path[] files)
Returns the sorted list of names of provided files.- Parameters:
files- The files to sort and get the names of- Returns:
- the sorted list of file names
-
getFileForPath
public static Path getFileForPath(String path)
Retrieves aPathobject corresponding to the specified path. If the given path is an absolute path, then it will be used. If the path is relative, then it will be interpreted as if it were relative to the Directory Server root.- Parameters:
path- The path string to be retrieved as aPath- Returns:
- A
Pathobject that corresponds to the specified path.
-
getFileForPath
public static Path getFileForPath(String path, ServerContext serverContext)
Retrieves aPathobject corresponding to the specified path. If the given path is an absolute path, then it will be used. If the path is relative, then it will be interpreted as if it were relative to the Directory Server root.- Parameters:
path- The path object to be retrieved as an absolutePathserverContext- The server context.- Returns:
- A
Pathobject that corresponds to the specified path.
-
getFileForPath
public static Path getFileForPath(Path path, ServerContext serverContext)
Retrieves aPathobject corresponding to the specified path. If the given path is an absolute path, then it will be used. If the path is relative, then it will be interpreted as if it were relative to the Directory Server root.- Parameters:
path- The path object to be retrieved as an absolutePathserverContext- The server context.- Returns:
- A
Pathobject that corresponds to the specified path.
-
createEntry
public static Entry createEntry(Dn dn, Schema schema)
Creates a new, blank entry with the given DN. It will contain only the attribute(s) contained in the RDN. The choice of objectclasses will be based on the RDN attribute. If there is a single RDN attribute, then the following mapping will be used:- c attribute :: country objectclass
- dc attribute :: domain objectclass
- o attribute :: organization objectclass
- ou attribute :: organizationalUnit objectclass
- Parameters:
dn- The DN to use for the entry.schema- the schema from which to create the entry- Returns:
- The entry created with the provided DN.
-
getObjectClassName
public static String getObjectClassName(Rdn rdn)
Best effort to find structural object class name of the provided base entry RDN.
-
secondsToTimeString
public static LocalizableMessage secondsToTimeString(long numSeconds)
Retrieves a user-friendly string that indicates the length of time (in days, hours, minutes, and seconds) in the specified number of seconds.- Parameters:
numSeconds- The number of seconds to be converted to a more user-friendly value.- Returns:
- The user-friendly representation of the specified number of seconds.
-
parseDateTimeString
public static Instant parseDateTimeString(String timeStr) throws ParseException
Converts a string representing a time in "yyyyMMddHHmmss.SSS'Z'" or "yyyyMMddHHmmss" to aDate.- Parameters:
timeStr- string formatted appropriately- Returns:
- Date object; null if
timeStris null - Throws:
ParseException- if there was a problem converting the string to aDate.
-
formatDateTimeString
public static String formatDateTimeString(TemporalAccessor instant)
Formats a Date to String representation in "yyyyMMddHHmmss'Z'".- Parameters:
instant- to format; null ifdateis null- Returns:
- string representation of the date
-
isEmailAddress
public static boolean isEmailAddress(String addr)
Indicates whether a string represents a syntactically correct email address.- Parameters:
addr- to validate- Returns:
- boolean where
trueindicates that the string is a syntactically correct email address
-
addRdnAttributes
public static Entry addRdnAttributes(Entry entry)
Add the RDN attribute(s) to the provided entry.- Parameters:
entry- the entry- Returns:
- the entry itself
-
addMissingSuperiorObjectClasses
public static void addMissingSuperiorObjectClasses(Entry entry)
Add all of the superior objectclasses to the specified entry if they are not already present.- Parameters:
entry- The entry where to add the missing superior object classes.
-
sleep
public static void sleep(long millis)
CallsThread.sleep(long), surrounding it with the mandatorytry/catch(InterruptedException)block.- Parameters:
millis- the length of time to sleep in milliseconds
-
extractZipArchive
public static void extractZipArchive(File zipFile, File targetDirectory, List<String> executableDirectories, List<String> executableFiles) throws IOException
Extracts the provided zip archive to the provided target directory.A file is set to executable if one or more of the following three conditions apply:
- It ends with a suffix identified as executable file suffix (.sh, .bat, .exe)
- It is listed in the provided executableFiles
- It is included in a directory that is listed in the provided executableDirectories
- Parameters:
zipFile- The zip file to extract.targetDirectory- The target directory for the content of the archive.executableDirectories- List of extracted directories which should have all their files set as executable. Each directory must be provided as a path relative to the target directory (e.g. "opendj/bin")executableFiles- List of individual files which should be set as executable. Each file must be provided as a path relative to the target directory (e.g. "opendj/setup")- Throws:
IOException- If zip archive can't be read or target files can be written.
-
checkVersionMismatch
public static void checkVersionMismatch() throws com.forgerock.opendj.cli.ClientExceptionChecks if the binary version is the same than the instance version.- Throws:
com.forgerock.opendj.cli.ClientException- Sends an exception if the version mismatch.
-
toPatterns
public static Collection<Pattern> toPatterns(Collection<String> regExps)
Returns a collection of patterns representing provided regular expression strings.- Parameters:
regExps- A collection of strings to be converted into regular expression patterns.- Returns:
- A collection of
Patterns associated to the provided regular expression strings. - Throws:
PatternSyntaxException- If a provided string cannot be parsed as a valid regular expressionPattern(seePattern.compile(String)for more details).
-
validatePatterns
public static boolean validatePatterns(Collection<String> blackListRegExps, Collection<String> whiteListRegExps, Collection<LocalizableMessage> unacceptableReasons)
Returns whether all the provided black and white list strings are valid regular expression patterns by usingPattern.compile(String). All validation errors will be added to the provided collection of localized messages.- Parameters:
blackListRegExps- ACollectionof strings which represents the black list regular expression patterns to validate.whiteListRegExps- ACollectionof strings which represents the white list regular expression patterns to validate.unacceptableReasons- TheCollectionwhere messages will be added for each invalid regular expression patterns.- Returns:
trueif all provided strings can be parsed as a valid regular expressionPattern,falseotherwise.
-
isServerRunning
public static boolean isServerRunning()
Returns whether the server located in the provided path is running.- Returns:
trueif the server located in the provided path is running,falseotherwise.
-
anyEqualsTo
public static Filter anyEqualsTo(Collection<AttributeType> attributeTypes, ByteString value)
Builds an "or" filter where one of the provided attribute types must match the provided value.- Parameters:
attributeTypes- the attribute types to build the or filtervalue- the attribute value that mus be matched- Returns:
- an "or" filter
-
-