Class StaticUtils


  • @PublicAPI(stability=UNCOMMITTED,
               mayInstantiate=false,
               mayExtend=false,
               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 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

      • getBytes

        public static byte[] getBytes​(String s)
        Construct a byte array containing the UTF-8 encoding of the provided string. This is significantly faster than calling String.getBytes(String) for ASCII strings.
        Parameters:
        s - The string to convert to a UTF-8 byte array.
        Returns:
        Returns a byte array containing the UTF-8 encoding of the provided string.
      • byteToHex

        public static String byteToHex​(byte b)
        Retrieves a string representation of the provided byte in hexadecimal.
        Parameters:
        b - The byte for which to retrieve the hexadecimal string representation.
        Returns:
        The string representation of the provided byte in hexadecimal.
      • byteToLowerHex

        public static String byteToLowerHex​(byte b)
        Retrieves a string representation of the provided byte in hexadecimal.
        Parameters:
        b - The byte for which to retrieve the hexadecimal string representation.
        Returns:
        The string representation of the provided byte in hexadecimal using lowercase characters.
      • 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.
      • getExceptionMessage

        public static LocalizableMessage getExceptionMessage​(Throwable t)
        Retrieves the best human-readable message for the provided exception. For exceptions defined in the OpenDJ project, it will attempt to use the message (combining it with the message ID if available). For some exceptions that use encapsulation (e.g., InvocationTargetException), it will be unwrapped and the cause will be treated. For all others, the
        Parameters:
        t - The Throwable object for which to retrieve the message.
        Returns:
        The human-readable message generated for the provided exception.
      • stackTraceToSingleLineString

        public static String stackTraceToSingleLineString​(Throwable t)
        Retrieves a stack trace from the provided exception as a single-line string.
        Parameters:
        t - The exception for which to retrieve the stack trace.
        Returns:
        A stack trace from the provided exception as a single-line string.
      • stackTraceToString

        public static String stackTraceToString​(Throwable t)
        Retrieves a string representation of the stack trace for the provided exception.
        Parameters:
        t - The exception for which to retrieve the stack trace.
        Returns:
        A string representation of the stack trace for the provided exception.
      • getBacktrace

        public static String getBacktrace​(Throwable t)
        Retrieves a backtrace for the provided exception consisting of only filenames and line numbers that may be useful in debugging the origin of problems. This is less expensive than the call to getBacktrace without any arguments if an exception has already been thrown.
        Parameters:
        t - The exception for which to obtain the backtrace.
        Returns:
        A backtrace from the provided exception.
      • isDigit

        public static boolean isDigit​(char c)
        Indicates whether the provided character is a numeric digit.
        Parameters:
        c - The character for which to make the determination.
        Returns:
        true if the provided character represents a numeric digit, or false if not.
      • isAlpha

        public static boolean isAlpha​(char c)
        Indicates whether the provided character is an ASCII alphabetic character.
        Parameters:
        c - The character for which to make the determination.
        Returns:
        true if the provided value is an uppercase or lowercase ASCII alphabetic character, or false if it is not.
      • isHexDigit

        public static boolean isHexDigit​(char c)
        Indicates whether the provided character is a hexadecimal digit.
        Parameters:
        c - The character for which to make the determination.
        Returns:
        true if the provided character represents a hexadecimal digit, or false if not.
      • isHexDigit

        public static boolean isHexDigit​(byte b)
        Indicates whether the provided byte represents a hexadecimal digit.
        Parameters:
        b - The byte for which to make the determination.
        Returns:
        true if the provided byte represents a hexadecimal digit, or false if not.
      • 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:
        true if the value needs to be base64-encoded if it is represented in LDIF form, or false if 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:
        true if the value needs to be base64-encoded if it is represented in LDIF form, or false if 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)
      • toRFC3641StringValue

        public static StringBuilder toRFC3641StringValue​(StringBuilder builder,
                                                         String string)
        Append a string to a string builder, escaping any double quotes according to the StringValue production in RFC 3641.

        In RFC 3641 the StringValue production looks like this:

            StringValue       = dquote *SafeUTF8Character dquote
            dquote            = %x22 ; " (double quote)
            SafeUTF8Character = %x00-21 / %x23-7F /   ; ASCII minus dquote
                                dquote dquote /       ; escaped double quote
                                %xC0-DF %x80-BF /     ; 2 byte UTF-8 character
                                %xE0-EF 2(%x80-BF) /  ; 3 byte UTF-8 character
                                %xF0-F7 3(%x80-BF)    ; 4 byte UTF-8 character
         

        That is, strings are surrounded by double-quotes and any internal double-quotes are doubled up.

        Parameters:
        builder - The string builder.
        string - The string to escape and append.
        Returns:
        Returns the string builder.
      • 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:
        true if the specified file and any subordinates are all successfully removed, or false if 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.
      • renameFile

        public static void renameFile​(Path fileToRename,
                                      Path target)
                               throws IOException
        Renames the source file to the target file. If the target file exists it is first deleted. The rename and delete operation return values are checked for success and if unsuccessful, this method throws an exception.
        Parameters:
        fileToRename - The file to rename.
        target - The file to which fileToRename will be moved.
        Throws:
        IOException - If a problem occurs while attempting to rename the file. On the Windows platform, this typically indicates that the file is in use by this or another application.
      • 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 a Path object 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 a Path
        Returns:
        A Path object that corresponds to the specified path.
      • getFileForPath

        public static Path getFileForPath​(String path,
                                          ServerContext serverContext)
        Retrieves a Path object 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 absolute Path
        serverContext - The server context.
        Returns:
        A Path object that corresponds to the specified path.
      • getFileForPath

        public static Path getFileForPath​(Path path,
                                          ServerContext serverContext)
        Retrieves a Path object 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 absolute Path
        serverContext - The server context.
        Returns:
        A Path object 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
        Any other single RDN attribute types, or any case in which there are multiple RDN attributes, will use the untypedObject objectclass. If the RDN includes one or more attributes that are not allowed in the untypedObject objectclass, then the extensibleObject class will also be added. Note that this method cannot be used to generate an entry with an empty or null DN.
        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.
        Parameters:
        rdn - The Rdn
        Returns:
        The structural object class name of the provided 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 a Date.
        Parameters:
        timeStr - string formatted appropriately
        Returns:
        Date object; null if timeStr is null
        Throws:
        ParseException - if there was a problem converting the string to a Date.
      • formatDateTimeString

        public static String formatDateTimeString​(TemporalAccessor instant)
        Formats a Date to String representation in "yyyyMMddHHmmss'Z'".
        Parameters:
        instant - to format; null if date is 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 true indicates 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)
        Calls Thread.sleep(long), surrounding it with the mandatory try / 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.ClientException
        Checks 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 expression Pattern (see Pattern.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 using Pattern.compile(String). All validation errors will be added to the provided collection of localized messages.
        Parameters:
        blackListRegExps - A Collection of strings which represents the black list regular expression patterns to validate.
        whiteListRegExps - A Collection of strings which represents the white list regular expression patterns to validate.
        unacceptableReasons - The Collection where messages will be added for each invalid regular expression patterns.
        Returns:
        true if all provided strings can be parsed as a valid regular expression Pattern, false otherwise.
      • isServerRunning

        public static boolean isServerRunning()
        Returns whether the server located in the provided path is running.
        Returns:
        true if the server located in the provided path is running, false otherwise.