Class 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 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:
        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)
      • 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.
      • moveFileSafely

        public static void moveFileSafely​(Path source,
                                          Path target)
                                   throws IOException
        Attempts to move a file atomically and consistently. This method delegates to Files.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 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.
      • 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 filter
        value - the attribute value that mus be matched
        Returns:
        an "or" filter