001/*
002 * Copyright 2007-2023 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2007-2023 Ping Identity Corporation
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *    http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020/*
021 * Copyright (C) 2007-2023 Ping Identity Corporation
022 *
023 * This program is free software; you can redistribute it and/or modify
024 * it under the terms of the GNU General Public License (GPLv2 only)
025 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
026 * as published by the Free Software Foundation.
027 *
028 * This program is distributed in the hope that it will be useful,
029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
031 * GNU General Public License for more details.
032 *
033 * You should have received a copy of the GNU General Public License
034 * along with this program; if not, see <http://www.gnu.org/licenses>.
035 */
036package com.unboundid.util;
037
038
039
040import java.io.BufferedReader;
041import java.io.File;
042import java.io.FileOutputStream;
043import java.io.FileReader;
044import java.io.IOException;
045import java.io.PrintWriter;
046import java.io.StringReader;
047import java.lang.reflect.Array;
048import java.net.Inet4Address;
049import java.net.Inet6Address;
050import java.net.InetAddress;
051import java.net.NetworkInterface;
052import java.nio.charset.StandardCharsets;
053import java.text.DecimalFormat;
054import java.text.Normalizer;
055import java.text.ParseException;
056import java.text.SimpleDateFormat;
057import java.util.ArrayList;
058import java.util.Arrays;
059import java.util.Collection;
060import java.util.Collections;
061import java.util.Date;
062import java.util.Enumeration;
063import java.util.GregorianCalendar;
064import java.util.HashSet;
065import java.util.Iterator;
066import java.util.LinkedHashMap;
067import java.util.LinkedHashSet;
068import java.util.List;
069import java.util.Map;
070import java.util.Properties;
071import java.util.Random;
072import java.util.Set;
073import java.util.StringTokenizer;
074import java.util.TimeZone;
075import java.util.TreeSet;
076import java.util.UUID;
077import java.util.logging.Handler;
078import java.util.logging.Level;
079import java.util.logging.Logger;
080
081import com.unboundid.ldap.sdk.Attribute;
082import com.unboundid.ldap.sdk.Control;
083import com.unboundid.ldap.sdk.LDAPConnectionOptions;
084import com.unboundid.ldap.sdk.LDAPException;
085import com.unboundid.ldap.sdk.LDAPRuntimeException;
086import com.unboundid.ldap.sdk.NameResolver;
087import com.unboundid.ldap.sdk.ResultCode;
088import com.unboundid.ldap.sdk.Version;
089
090import static com.unboundid.util.UtilityMessages.*;
091
092
093
094/**
095 * This class provides a number of static utility functions.
096 */
097@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
098public final class StaticUtils
099{
100  /**
101   * A pre-allocated byte array containing zero bytes.
102   */
103  @NotNull public static final byte[] NO_BYTES = new byte[0];
104
105
106
107  /**
108   * A pre-allocated empty character array.
109   */
110  @NotNull public static final char[] NO_CHARS = new char[0];
111
112
113
114  /**
115   * A pre-allocated empty control array.
116   */
117  @NotNull public static final Control[] NO_CONTROLS = new Control[0];
118
119
120
121  /**
122   * A pre-allocated empty integer array.
123   */
124  @NotNull public static final int[] NO_INTS = new int[0];
125
126
127
128  /**
129   * A pre-allocated empty string array.
130   */
131  @NotNull public static final String[] NO_STRINGS = new String[0];
132
133
134
135  /**
136   * The end-of-line marker for the platform on which the LDAP SDK is
137   * currently running.
138   */
139  @NotNull public static final String EOL =
140       getSystemProperty("line.separator", "\n");
141
142
143
144  /**
145   * The end-of-line marker that consists of a carriage return character
146   * followed by a line feed character, as used on Windows systems.
147   */
148  @NotNull public static final String EOL_CR_LF = "\r\n";
149
150
151
152  /**
153   * The end-of-line marker that consists of just the line feed character, as
154   * used on UNIX-based systems.
155   */
156  @NotNull public static final String EOL_LF = "\n";
157
158
159
160  /**
161   * A byte array containing the end-of-line marker for the platform on which
162   * the LDAP SDK is currently running.
163   */
164  @NotNull public static final byte[] EOL_BYTES = getBytes(EOL);
165
166
167
168  /**
169   * A byte array containing the end-of-line marker that consists of a carriage
170   * return character followed by a line feed character, as used on Windows
171   * systems.
172   */
173  @NotNull public static final byte[] EOL_BYTES_CR_LF = getBytes(EOL_CR_LF);
174
175
176
177  /**
178   * A byte array containing the end-of-line marker that consists of just the
179   * line feed character, as used on UNIX-based systems.
180   */
181  @NotNull public static final byte[] EOL_BYTES_LF = getBytes(EOL_LF);
182
183
184
185  /**
186   * Indicates whether the unit tests are currently running.
187   */
188  private static final boolean IS_WITHIN_UNIT_TESTS =
189       Boolean.getBoolean("com.unboundid.ldap.sdk.RunningUnitTests") ||
190       Boolean.getBoolean("com.unboundid.directory.server.RunningUnitTests");
191
192
193
194  /**
195   * The thread-local date formatter used to encode generalized time values.
196   */
197  @NotNull private static final ThreadLocal<SimpleDateFormat>
198       GENERALIZED_TIME_FORMATTERS = new ThreadLocal<>();
199
200
201
202  /**
203   * The thread-local date formatter used to encode RFC 3339 time values.
204   */
205  @NotNull private static final ThreadLocal<SimpleDateFormat>
206       RFC_3339_TIME_FORMATTERS = new ThreadLocal<>();
207
208
209
210  /**
211   * The {@code TimeZone} object that represents the UTC (universal coordinated
212   * time) time zone.
213   */
214  @NotNull private static final TimeZone UTC_TIME_ZONE =
215       TimeZone.getTimeZone("UTC");
216
217
218
219  /**
220   * A set containing the names of attributes that will be considered sensitive
221   * by the {@code toCode} methods of various request and data structure types.
222   */
223  @NotNull private static volatile Set<String>
224       TO_CODE_SENSITIVE_ATTRIBUTE_NAMES = setOf("userpassword", "2.5.4.35",
225            "authpassword", "1.3.6.1.4.1.4203.1.3.4");
226
227
228
229  /**
230   * The width of the terminal window, in columns.
231   */
232  public static final int TERMINAL_WIDTH_COLUMNS;
233  static
234  {
235    // Try to dynamically determine the size of the terminal window using the
236    // COLUMNS environment variable.
237    int terminalWidth = 80;
238    final String columnsEnvVar = getEnvironmentVariable("COLUMNS");
239    if (columnsEnvVar != null)
240    {
241      try
242      {
243        terminalWidth = Integer.parseInt(columnsEnvVar);
244      }
245      catch (final Exception e)
246      {
247        Debug.debugException(e);
248      }
249    }
250
251    TERMINAL_WIDTH_COLUMNS = terminalWidth;
252  }
253
254
255
256  /**
257   * An array containing the set of lowercase ASCII letters.
258   */
259  @NotNull private static final char[] LOWERCASE_LETTERS =
260       "abcdefghijklmnopqrstuvwxyz".toCharArray();
261
262
263
264  /**
265   * An array containing the set of ASCII numeric digits.
266   */
267  @NotNull private static final char[] NUMERIC_DIGITS =
268       "0123456789".toCharArray();
269
270
271
272  /**
273   * An array containing the set of ASCII alphanumeric characters.  It will
274   * include both uppercase and lowercase letters.
275   */
276  @NotNull private static final char[] ALPHANUMERIC_CHARACTERS =
277       ("abcdefghijklmnopqrstuvwxyz" +
278        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
279        "0123456789").toCharArray();
280
281
282
283  /**
284   * The name of a system property that can be used to explicitly specify the
285   * Unicode normalization type that will be used when comparing two strings in
286   * a Unicode-aware manner.
287   */
288  @NotNull private static final String PROPERTY_DEFAULT_NORMALIZER_FORM =
289       "com.unboundid.ldap.sdk.defaultUnicodeNormalizerForm";
290
291
292
293  /**
294   * The default Unicode normalization type that will be used when comparing
295   * two strings in a Unicode-aware manner.
296   */
297  @NotNull private static final Normalizer.Form DEFAULT_UNICODE_NORMALIZER_FORM;
298  static
299  {
300    final String propertyValue =
301         getSystemProperty(PROPERTY_DEFAULT_NORMALIZER_FORM);
302    if ((propertyValue == null) || propertyValue.equalsIgnoreCase("NFC"))
303    {
304      DEFAULT_UNICODE_NORMALIZER_FORM = Normalizer.Form.NFC;
305    }
306    else if (propertyValue.equalsIgnoreCase("NFD"))
307    {
308      DEFAULT_UNICODE_NORMALIZER_FORM = Normalizer.Form.NFD;
309    }
310    else if (propertyValue.equalsIgnoreCase("NFKC"))
311    {
312      DEFAULT_UNICODE_NORMALIZER_FORM = Normalizer.Form.NFKC;
313    }
314    else if (propertyValue.equalsIgnoreCase("NFKD"))
315    {
316      DEFAULT_UNICODE_NORMALIZER_FORM = Normalizer.Form.NFKD;
317    }
318    else
319    {
320      throw new LDAPRuntimeException(new LDAPException(ResultCode.PARAM_ERROR,
321           ERR_UNRECOGNIZED_NORMALIZER_FORM.get(
322                PROPERTY_DEFAULT_NORMALIZER_FORM, propertyValue)));
323    }
324  }
325
326
327
328  /**
329   * Prevent this class from being instantiated.
330   */
331  private StaticUtils()
332  {
333    // No implementation is required.
334  }
335
336
337
338  /**
339   * Retrieves the set of currently defined system properties.  If possible,
340   * this will simply return the result of a call to
341   * {@code System.getProperties}.  However, the LDAP SDK is known to be used in
342   * environments where a security manager prevents setting system properties,
343   * and in that case, calls to {@code System.getProperties} will be rejected
344   * with a {@code SecurityException} because the returned structure is mutable
345   * and could be used to alter system property values.  In such cases, a new
346   * empty {@code Properties} object will be created, and may optionally be
347   * populated with the values of a specific set of named properties.
348   *
349   * @param  propertyNames  An optional set of property names whose values (if
350   *                        defined) should be included in the
351   *                        {@code Properties} object that will be returned if a
352   *                        security manager prevents retrieving the full set of
353   *                        system properties.  This may be {@code null} or
354   *                        empty if no specific properties should be retrieved.
355   *
356   * @return  The value returned by a call to {@code System.getProperties} if
357   *          possible, or a newly-created properties map (possibly including
358   *          the values of a specified set of system properties) if it is not
359   *          possible to get a mutable set of the system properties.
360   */
361  @NotNull()
362  public static Properties getSystemProperties(
363                                @Nullable final String... propertyNames)
364  {
365    try
366    {
367      final Properties properties = System.getProperties();
368
369      final String forceThrowPropertyName =
370           StaticUtils.class.getName() + ".forceGetSystemPropertiesToThrow";
371
372      // To ensure that we can get coverage for the code below in which there is
373      // a restrictive security manager in place, look for a system property
374      // that will cause us to throw an exception.
375      final Object forceThrowPropertyValue =
376           properties.getProperty(forceThrowPropertyName);
377      if (forceThrowPropertyValue != null)
378      {
379        throw new SecurityException(forceThrowPropertyName + '=' +
380             forceThrowPropertyValue);
381      }
382
383      return properties;
384    }
385    catch (final SecurityException e)
386    {
387      Debug.debugException(e);
388    }
389
390
391    // If we have gotten here, then we can assume that a security manager
392    // prevents us from accessing all system properties.  Create a new proper
393    final Properties properties = new Properties();
394    if (propertyNames != null)
395    {
396      for (final String propertyName : propertyNames)
397      {
398        final Object propertyValue = System.getProperty(propertyName);
399        if (propertyValue != null)
400        {
401          properties.put(propertyName, propertyValue);
402        }
403      }
404    }
405
406    return properties;
407  }
408
409
410
411  /**
412   * Retrieves the value of the specified system property.
413   *
414   * @param  name  The name of the system property for which to retrieve the
415   *               value.
416   *
417   * @return  The value of the requested system property, or {@code null} if
418   *          that variable was not set or its value could not be retrieved
419   *          (for example, because a security manager prevents it).
420   */
421  @Nullable()
422  public static String getSystemProperty(@NotNull final String name)
423  {
424    try
425    {
426      return System.getProperty(name);
427    }
428    catch (final Throwable t)
429    {
430      // It is possible that the call to System.getProperty could fail under
431      // some security managers.  In that case, simply swallow the error and
432      // act as if that system property is not set.
433      Debug.debugException(t);
434      return null;
435    }
436  }
437
438
439
440  /**
441   * Retrieves the value of the specified system property.
442   *
443   * @param  name          The name of the system property for which to retrieve
444   *                       the value.
445   * @param  defaultValue  The default value to return if the specified
446   *                       system property is not set or could not be
447   *                       retrieved.
448   *
449   * @return  The value of the requested system property, or the provided
450   *          default value if that system property was not set or its value
451   *          could not be retrieved (for example, because a security manager
452   *          prevents it).
453   */
454  @Nullable()
455  public static String getSystemProperty(@NotNull final String name,
456                                         @Nullable final String defaultValue)
457  {
458    try
459    {
460      return System.getProperty(name, defaultValue);
461    }
462    catch (final Throwable t)
463    {
464      // It is possible that the call to System.getProperty could fail under
465      // some security managers.  In that case, simply swallow the error and
466      // act as if that system property is not set.
467      Debug.debugException(t);
468      return defaultValue;
469    }
470  }
471
472
473
474  /**
475   * Attempts to set the value of the specified system property.  Note that this
476   * may not be permitted by some security managers, in which case the attempt
477   * will have no effect.
478   *
479   * @param  name   The name of the System property to set.  It must not be
480   *                {@code null}.
481   * @param  value  The value to use for the system property.  If it is
482   *                {@code null}, then the property will be cleared.
483   *
484   * @return  The former value of the system property, or {@code null} if it
485   *          did not have a value or if it could not be set (for example,
486   *          because a security manager prevents it).
487   */
488  @Nullable()
489  public static String setSystemProperty(@NotNull final String name,
490                                         @Nullable final String value)
491  {
492    try
493    {
494      if (value == null)
495      {
496        return System.clearProperty(name);
497      }
498      else
499      {
500        return System.setProperty(name, value);
501      }
502    }
503    catch (final Throwable t)
504    {
505      // It is possible that the call to System.setProperty or
506      // System.clearProperty could fail under some security managers.  In that
507      // case, simply swallow the error and act as if that system property is
508      // not set.
509      Debug.debugException(t);
510      return null;
511    }
512  }
513
514
515
516  /**
517   * Attempts to clear the value of the specified system property.  Note that
518   * this may not be permitted by some security managers, in which case the
519   * attempt will have no effect.
520   *
521   * @param  name  The name of the System property to clear.  It must not be
522   *               {@code null}.
523   *
524   * @return  The former value of the system property, or {@code null} if it
525   *          did not have a value or if it could not be set (for example,
526   *          because a security manager prevents it).
527   */
528  @Nullable()
529  public static String clearSystemProperty(@NotNull final String name)
530  {
531    try
532    {
533      return System.clearProperty(name);
534    }
535    catch (final Throwable t)
536    {
537      // It is possible that the call to System.clearProperty could fail under
538      // some security managers.  In that case, simply swallow the error and
539      // act as if that system property is not set.
540      Debug.debugException(t);
541      return null;
542    }
543  }
544
545
546
547  /**
548   * Retrieves a map of all environment variables defined in the JVM's process.
549   *
550   * @return  A map of all environment variables defined in the JVM's process,
551   *          or an empty map if no environment variables are set or the actual
552   *          set could not be retrieved (for example, because a security
553   *          manager prevents it).
554   */
555  @NotNull()
556  public static Map<String,String> getEnvironmentVariables()
557  {
558    try
559    {
560      return System.getenv();
561    }
562    catch (final Throwable t)
563    {
564      // It is possible that the call to System.getenv could fail under some
565      // security managers.  In that case, simply swallow the error and pretend
566      // that the environment variable is not set.
567      Debug.debugException(t);
568      return Collections.emptyMap();
569    }
570  }
571
572
573
574  /**
575   * Retrieves the value of the specified environment variable.
576   *
577   * @param  name  The name of the environment variable for which to retrieve
578   *               the value.
579   *
580   * @return  The value of the requested environment variable, or {@code null}
581   *          if that variable was not set or its value could not be retrieved
582   *          (for example, because a security manager prevents it).
583   */
584  @Nullable()
585  public static String getEnvironmentVariable(@NotNull final String name)
586  {
587    try
588    {
589      return System.getenv(name);
590    }
591    catch (final Throwable t)
592    {
593      // It is possible that the call to System.getenv could fail under some
594      // security managers.  In that case, simply swallow the error and pretend
595      // that the environment variable is not set.
596      Debug.debugException(t);
597      return null;
598    }
599  }
600
601
602
603  /**
604   * Retrieves the value of the specified environment variable.
605   *
606   * @param  name          The name of the environment variable for which to
607   *                       retrieve the value.
608   * @param  defaultValue  The default value to use if the specified environment
609   *                       variable is not set.  It may be {@code null} if no
610   *                       default should be used.
611   *
612   * @return  The value of the requested environment variable, or {@code null}
613   *          if that variable was not set or its value could not be retrieved
614   *          (for example, because a security manager prevents it) and there
615   *          is no default value.
616   */
617  @Nullable()
618  public static String getEnvironmentVariable(@NotNull final String name,
619                            @Nullable final String defaultValue)
620  {
621    final String value = getEnvironmentVariable(name);
622    if (value == null)
623    {
624      return defaultValue;
625    }
626    else
627    {
628      return value;
629    }
630  }
631
632
633
634  /**
635   * Attempts to set the desired log level for the specified logger.  Note that
636   * this may not be permitted by some security managers, in which case the
637   * attempt will have no effect.
638   *
639   * @param  logger    The logger whose level should be updated.
640   * @param  logLevel  The log level to set for the logger.
641   */
642  public static void setLoggerLevel(@NotNull final Logger logger,
643                                    @NotNull final Level logLevel)
644  {
645    try
646    {
647      logger.setLevel(logLevel);
648    }
649    catch (final Throwable t)
650    {
651      Debug.debugException(t);
652    }
653  }
654
655
656
657  /**
658   * Attempts to set the desired log level for the specified log handler.  Note
659   * that this may not be permitted by some security managers, in which case the
660   * attempt will have no effect.
661   *
662   * @param  logHandler  The log handler whose level should be updated.
663   * @param  logLevel    The log level to set for the log handler.
664   */
665  public static void setLogHandlerLevel(@NotNull final Handler logHandler,
666                                        @NotNull final Level logLevel)
667  {
668    try
669    {
670      logHandler.setLevel(logLevel);
671    }
672    catch (final Throwable t)
673    {
674      Debug.debugException(t);
675    }
676  }
677
678
679
680  /**
681   * Retrieves a UTF-8 byte representation of the provided string.
682   *
683   * @param  s  The string for which to retrieve the UTF-8 byte representation.
684   *
685   * @return  The UTF-8 byte representation for the provided string.
686   */
687  @NotNull()
688  public static byte[] getBytes(@Nullable final String s)
689  {
690    final int length;
691    if ((s == null) || ((length = s.length()) == 0))
692    {
693      return NO_BYTES;
694    }
695
696    final byte[] b = new byte[length];
697    for (int i=0; i < length; i++)
698    {
699      final char c = s.charAt(i);
700      if (c <= 0x7F)
701      {
702        b[i] = (byte) (c & 0x7F);
703      }
704      else
705      {
706        return s.getBytes(StandardCharsets.UTF_8);
707      }
708    }
709
710    return b;
711  }
712
713
714
715  /**
716   * Retrieves a byte array containing the UTF-8 representation of the bytes
717   * that comprise the provided Unicode code point.
718   *
719   * @param  codePoint  The code point for which to retrieve the UTF-8 bytes.
720   *
721   * @return  A byte array containing the UTF-8 representation of the bytes that
722   *          comprise the provided Unicode code point.
723   */
724  @NotNull()
725  public static byte[] getBytesForCodePoint(final int codePoint)
726  {
727    if (codePoint <= 0x7F)
728    {
729      return new byte[] { (byte) codePoint };
730    }
731    else
732    {
733      final String codePointString = new String(new int[] { codePoint }, 0, 1);
734      return codePointString.getBytes(StandardCharsets.UTF_8);
735    }
736  }
737
738
739
740  /**
741   * Indicates whether the contents of the provided byte array represent an
742   * ASCII string, which is also known in LDAP terminology as an IA5 string.
743   * An ASCII string is one that contains only bytes in which the most
744   * significant bit is zero.
745   *
746   * @param  b  The byte array for which to make the determination.  It must
747   *            not be {@code null}.
748   *
749   * @return  {@code true} if the contents of the provided array represent an
750   *          ASCII string, or {@code false} if not.
751   */
752  public static boolean isASCIIString(@NotNull final byte[] b)
753  {
754    for (final byte by : b)
755    {
756      if ((by & 0x80) == 0x80)
757      {
758        return false;
759      }
760    }
761
762    return true;
763  }
764
765
766
767  /**
768   * Indicates whether the contents of the provided string represent an ASCII
769   * string, which is also known in LDAP terminology as an IA5 string.  An ASCII
770   * string is one that contains only bytes in which the most significant bit is
771   * zero.
772   *
773   * @param  s  The string for which to make the determination.  It must not be
774   *            {@code null}.
775   *
776   * @return  {@code true} if the contents of the provided string represent an
777   *          ASCII string, or {@code false} if not.
778   */
779  public static boolean isASCIIString(@NotNull final String s)
780  {
781    return isASCIIString(getBytes(s));
782  }
783
784
785
786  /**
787   * Indicates whether the provided character is a printable ASCII character, as
788   * per RFC 4517 section 3.2.  The only printable characters are:
789   * <UL>
790   *   <LI>All uppercase and lowercase ASCII alphabetic letters</LI>
791   *   <LI>All ASCII numeric digits</LI>
792   *   <LI>The following additional ASCII characters:  single quote, left
793   *       parenthesis, right parenthesis, plus, comma, hyphen, period, equals,
794   *       forward slash, colon, question mark, space.</LI>
795   * </UL>
796   *
797   * @param  c  The character for which to make the determination.
798   *
799   * @return  {@code true} if the provided character is a printable ASCII
800   *          character, or {@code false} if not.
801   */
802  public static boolean isPrintable(final char c)
803  {
804    if (((c >= 'a') && (c <= 'z')) ||
805        ((c >= 'A') && (c <= 'Z')) ||
806        ((c >= '0') && (c <= '9')))
807    {
808      return true;
809    }
810
811    switch (c)
812    {
813      case '\'':
814      case '(':
815      case ')':
816      case '+':
817      case ',':
818      case '-':
819      case '.':
820      case '=':
821      case '/':
822      case ':':
823      case '?':
824      case ' ':
825        return true;
826      default:
827        return false;
828    }
829  }
830
831
832
833  /**
834   * Indicates whether the contents of the provided byte array represent a
835   * printable LDAP string, as per RFC 4517 section 3.2.  The only characters
836   * allowed in a printable string are:
837   * <UL>
838   *   <LI>All uppercase and lowercase ASCII alphabetic letters</LI>
839   *   <LI>All ASCII numeric digits</LI>
840   *   <LI>The following additional ASCII characters:  single quote, left
841   *       parenthesis, right parenthesis, plus, comma, hyphen, period, equals,
842   *       forward slash, colon, question mark, space.</LI>
843   * </UL>
844   * If the provided array contains anything other than the above characters
845   * (i.e., if the byte array contains any non-ASCII characters, or any ASCII
846   * control characters, or if it contains excluded ASCII characters like
847   * the exclamation point, double quote, octothorpe, dollar sign, etc.), then
848   * it will not be considered printable.
849   *
850   * @param  b  The byte array for which to make the determination.  It must
851   *            not be {@code null}.
852   *
853   * @return  {@code true} if the contents of the provided byte array represent
854   *          a printable LDAP string, or {@code false} if not.
855   */
856  public static boolean isPrintableString(@NotNull final byte[] b)
857  {
858    for (final byte by : b)
859    {
860      if ((by & 0x80) == 0x80)
861      {
862        return false;
863      }
864
865      if (((by >= 'a') && (by <= 'z')) ||
866          ((by >= 'A') && (by <= 'Z')) ||
867          ((by >= '0') && (by <= '9')))
868      {
869        continue;
870      }
871
872      switch (by)
873      {
874        case '\'':
875        case '(':
876        case ')':
877        case '+':
878        case ',':
879        case '-':
880        case '.':
881        case '=':
882        case '/':
883        case ':':
884        case '?':
885        case ' ':
886          continue;
887        default:
888          return false;
889      }
890    }
891
892    return true;
893  }
894
895
896
897  /**
898   * Indicates whether the provided string represents a printable LDAP string,
899   * as per RFC 4517 section 3.2.  The only characters allowed in a printable
900   * string are:
901   * <UL>
902   *   <LI>All uppercase and lowercase ASCII alphabetic letters</LI>
903   *   <LI>All ASCII numeric digits</LI>
904   *   <LI>The following additional ASCII characters:  single quote, left
905   *       parenthesis, right parenthesis, plus, comma, hyphen, period, equals,
906   *       forward slash, colon, question mark, space.</LI>
907   * </UL>
908   * If the provided array contains anything other than the above characters
909   * (i.e., if the byte array contains any non-ASCII characters, or any ASCII
910   * control characters, or if it contains excluded ASCII characters like
911   * the exclamation point, double quote, octothorpe, dollar sign, etc.), then
912   * it will not be considered printable.
913   *
914   * @param  s  The string for which to make the determination.  It must not be
915   *            {@code null}.
916   *
917   * @return  {@code true} if the provided string represents a printable LDAP
918   *          string, or {@code false} if not.
919   */
920  public static boolean isPrintableString(@NotNull final String s)
921  {
922    final int length = s.length();
923    for (int i=0; i < length; i++)
924    {
925      final char c = s.charAt(i);
926      if ((c & 0x80) == 0x80)
927      {
928        return false;
929      }
930
931      if (((c >= 'a') && (c <= 'z')) ||
932          ((c >= 'A') && (c <= 'Z')) ||
933          ((c >= '0') && (c <= '9')))
934      {
935        continue;
936      }
937
938      switch (c)
939      {
940        case '\'':
941        case '(':
942        case ')':
943        case '+':
944        case ',':
945        case '-':
946        case '.':
947        case '=':
948        case '/':
949        case ':':
950        case '?':
951        case ' ':
952          continue;
953        default:
954          return false;
955      }
956    }
957
958    return true;
959  }
960
961
962
963  /**
964   * Indicates whether the specified Unicode code point represents a character
965   * that is believed to be displayable.  Displayable characters include
966   * letters, numbers, spaces, dashes, punctuation, symbols, and marks.
967   * Non-displayable characters include control characters, directionality
968   * indicators, like and paragraph separators, format characters, and surrogate
969   * characters.
970   *
971   * @param  codePoint  The code point for which to make the determination.
972   *
973   * @return  {@code true} if the specified Unicode character is believed to be
974   *          displayable, or {@code false} if not.
975   */
976  public static boolean isLikelyDisplayableCharacter(final int codePoint)
977  {
978    final int charType = Character.getType(codePoint);
979    switch (charType)
980    {
981      case Character.UPPERCASE_LETTER:
982      case Character.LOWERCASE_LETTER:
983      case Character.TITLECASE_LETTER:
984      case Character.MODIFIER_LETTER:
985      case Character.OTHER_LETTER:
986      case Character.DECIMAL_DIGIT_NUMBER:
987      case Character.LETTER_NUMBER:
988      case Character.OTHER_NUMBER:
989      case Character.SPACE_SEPARATOR:
990      case Character.DASH_PUNCTUATION:
991      case Character.START_PUNCTUATION:
992      case Character.END_PUNCTUATION:
993      case Character.CONNECTOR_PUNCTUATION:
994      case Character.OTHER_PUNCTUATION:
995      case Character.INITIAL_QUOTE_PUNCTUATION:
996      case Character.FINAL_QUOTE_PUNCTUATION:
997      case Character.MATH_SYMBOL:
998      case Character.CURRENCY_SYMBOL:
999      case Character.MODIFIER_SYMBOL:
1000      case Character.OTHER_SYMBOL:
1001      case Character.NON_SPACING_MARK:
1002      case Character.ENCLOSING_MARK:
1003      case Character.COMBINING_SPACING_MARK:
1004        return true;
1005      case Character.UNASSIGNED:
1006      case Character.LINE_SEPARATOR:
1007      case Character.PARAGRAPH_SEPARATOR:
1008      case Character.CONTROL:
1009      case Character.FORMAT:
1010      case Character.PRIVATE_USE:
1011      case Character.SURROGATE:
1012      default:
1013        return false;
1014    }
1015  }
1016
1017
1018
1019  /**
1020   *Indicates whether the provided string is comprised entirely of characters
1021   * that are believed to be displayable (as determined by the
1022   * {@link #isLikelyDisplayableCharacter} method).
1023   *
1024   * @param  s  The string for which to make the determination.  It must not be
1025   *            {@code null}.
1026   *
1027   * @return  {@code true} if the provided string is believed to be displayable,
1028   *          or {@code false} if not.
1029   */
1030  public static boolean isLikelyDisplayableString(@NotNull final String s)
1031  {
1032    int pos = 0;
1033    while (pos < s.length())
1034    {
1035      final int codePoint = s.codePointAt(pos);
1036      if (! isLikelyDisplayableCharacter(codePoint))
1037      {
1038        return false;
1039      }
1040
1041      pos += Character.charCount(codePoint);
1042    }
1043
1044    return true;
1045  }
1046
1047
1048
1049  /**
1050   * Retrieves an array of the code points that comprise the provided string.
1051   *
1052   * @param  s  The string for which to obtain the code points.  It must not be
1053   *            {@code null}.
1054   *
1055   * @return  An array of the code points that comprise the provided string.
1056   */
1057  @NotNull()
1058  public static int[] getCodePoints(@NotNull final String s)
1059  {
1060    final int numCodePoints = s.codePointCount(0, s.length());
1061    final int[] codePoints = new int[numCodePoints];
1062
1063    int pos = 0;
1064    int arrayIndex = 0;
1065    while (pos < s.length())
1066    {
1067      final int codePoint = s.codePointAt(pos);
1068      codePoints[arrayIndex++] = codePoint;
1069      pos += Character.charCount(codePoint);
1070    }
1071
1072    return codePoints;
1073  }
1074
1075
1076
1077  /**
1078   * Indicates whether the contents of the provided array represent a valid
1079   * UTF-8 string, which may or may not contain non-ASCII characters.  Note that
1080   * this method does not make any attempt to determine whether the characters
1081   * in the UTF-8 string actually map to assigned Unicode code points.
1082   *
1083   * @param  b  The byte array to examine.  It must not be {@code null}.
1084   *
1085   * @return  {@code true} if the byte array can be parsed as a valid UTF-8
1086   *          string, or {@code false} if not.
1087   */
1088  public static boolean isValidUTF8(@NotNull final byte[] b)
1089  {
1090    return isValidUTF8(b, false);
1091  }
1092
1093
1094
1095  /**
1096   * Indicates whether the contents of the provided array represent a valid
1097   * UTF-8 string that contains at least one non-ASCII character (and may
1098   * contain zero or more ASCII characters).  Note that this method does not
1099   * make any attempt to determine whether the characters in the UTF-8 string
1100   * actually map to assigned Unicode code points.
1101   *
1102   * @param  b  The byte array to examine.  It must not be {@code null}.
1103   *
1104   * @return  {@code true} if the byte array can be parsed as a valid UTF-8
1105   *          string and contains at least one non-ASCII character, or
1106   *          {@code false} if not.
1107   */
1108  public static boolean isValidUTF8WithNonASCIICharacters(
1109              @NotNull final byte[] b)
1110  {
1111    return isValidUTF8(b, true);
1112  }
1113
1114
1115
1116  /**
1117   * Indicates whether the contents of the provided array represent a valid
1118   * UTF-8 string that contains at least one non-ASCII character (and may
1119   * contain zero or more ASCII characters).  Note that this method does not
1120   * make any attempt to determine whether the characters in the UTF-8 string
1121   * actually map to assigned Unicode code points.
1122   *
1123   * @param  b                The byte array to examine.  It must not be
1124   *                          {@code null}.
1125   * @param  requireNonASCII  Indicates whether to require at least one
1126   *                          non-ASCII character in the provided string.
1127   *
1128   * @return  {@code true} if the byte array can be parsed as a valid UTF-8
1129   *          string and meets the non-ASCII requirement if appropriate, or
1130   *          {@code false} if not.
1131   */
1132  private static boolean isValidUTF8(@NotNull final byte[] b,
1133                                     final boolean requireNonASCII)
1134  {
1135    int i = 0;
1136    boolean containsNonASCII = false;
1137    while (i < b.length)
1138    {
1139      final byte currentByte = b[i++];
1140
1141      // If the most significant bit is not set, then this represents a valid
1142      // single-byte character.
1143      if ((currentByte & 0b1000_0000) == 0b0000_0000)
1144      {
1145        continue;
1146      }
1147
1148      // If the first byte starts with 0b110, then it must be followed by
1149      // another byte that starts with 0b10.
1150      if ((currentByte & 0b1110_0000) == 0b1100_0000)
1151      {
1152        if (! hasExpectedSubsequentUTF8Bytes(b, i, 1))
1153        {
1154          return false;
1155        }
1156
1157        i++;
1158        containsNonASCII = true;
1159        continue;
1160      }
1161
1162      // If the first byte starts with 0b1110, then it must be followed by two
1163      // more bytes that start with 0b10.
1164      if ((currentByte & 0b1111_0000) == 0b1110_0000)
1165      {
1166        if (! hasExpectedSubsequentUTF8Bytes(b, i, 2))
1167        {
1168          return false;
1169        }
1170
1171        i += 2;
1172        containsNonASCII = true;
1173        continue;
1174      }
1175
1176      // If the first byte starts with 0b11110, then it must be followed by
1177      // three more bytes that start with 0b10.
1178      if ((currentByte & 0b1111_1000) == 0b1111_0000)
1179      {
1180        if (! hasExpectedSubsequentUTF8Bytes(b, i, 3))
1181        {
1182          return false;
1183        }
1184
1185        i += 3;
1186        containsNonASCII = true;
1187        continue;
1188      }
1189
1190      // If the first byte starts with 0b111110, then it must be followed by
1191      // four more bytes that start with 0b10.
1192      if ((currentByte & 0b1111_1100) == 0b1111_1000)
1193      {
1194        if (! hasExpectedSubsequentUTF8Bytes(b, i, 4))
1195        {
1196          return false;
1197        }
1198
1199        i += 4;
1200        containsNonASCII = true;
1201        continue;
1202      }
1203
1204      // If the first byte starts with 0b1111110, then it must be followed by
1205      // five more bytes that start with 0b10.
1206      if ((currentByte & 0b1111_1110) == 0b1111_1100)
1207      {
1208        if (! hasExpectedSubsequentUTF8Bytes(b, i, 5))
1209        {
1210          return false;
1211        }
1212
1213        i += 5;
1214        containsNonASCII = true;
1215        continue;
1216      }
1217
1218      // This is not a valid first byte for a UTF-8 character.
1219      return false;
1220    }
1221
1222
1223    // If we've gotten here, then the provided array represents a valid UTF-8
1224    // string.  If appropriate, make sure it also satisfies the requirement to
1225    // have at leaste one non-ASCII character
1226    return containsNonASCII || (! requireNonASCII);
1227  }
1228
1229
1230
1231  /**
1232   * Ensures that the provided array has the expected number of bytes that start
1233   * with 0b10 starting at the specified position in the array.
1234   *
1235   * @param  b  The byte array to examine.
1236   * @param  p  The position in the byte array at which to start looking.
1237   * @param  n  The number of bytes to examine.
1238   *
1239   * @return  {@code true} if the provided byte array has the expected number of
1240   *          bytes that start with 0b10, or {@code false} if not.
1241   */
1242  private static boolean hasExpectedSubsequentUTF8Bytes(@NotNull final byte[] b,
1243                                                        final int p,
1244                                                        final int n)
1245  {
1246    if (b.length < (p + n))
1247    {
1248      return false;
1249    }
1250
1251    for (int i=0; i < n; i++)
1252    {
1253      if ((b[p+i] & 0b1100_0000) != 0b1000_0000)
1254      {
1255        return false;
1256      }
1257    }
1258
1259    return true;
1260  }
1261
1262
1263
1264  /**
1265   * Retrieves a string generated from the provided byte array using the UTF-8
1266   * encoding.
1267   *
1268   * @param  b  The byte array for which to return the associated string.
1269   *
1270   * @return  The string generated from the provided byte array using the UTF-8
1271   *          encoding.
1272   */
1273  @NotNull()
1274  public static String toUTF8String(@NotNull final byte[] b)
1275  {
1276    try
1277    {
1278      return new String(b, StandardCharsets.UTF_8);
1279    }
1280    catch (final Exception e)
1281    {
1282      // This should never happen.
1283      Debug.debugException(e);
1284      return new String(b);
1285    }
1286  }
1287
1288
1289
1290  /**
1291   * Retrieves a string generated from the specified portion of the provided
1292   * byte array using the UTF-8 encoding.
1293   *
1294   * @param  b       The byte array for which to return the associated string.
1295   * @param  offset  The offset in the array at which the value begins.
1296   * @param  length  The number of bytes in the value to convert to a string.
1297   *
1298   * @return  The string generated from the specified portion of the provided
1299   *          byte array using the UTF-8 encoding.
1300   */
1301  @NotNull()
1302  public static String toUTF8String(@NotNull final byte[] b, final int offset,
1303                                    final int length)
1304  {
1305    try
1306    {
1307      return new String(b, offset, length, StandardCharsets.UTF_8);
1308    }
1309    catch (final Exception e)
1310    {
1311      // This should never happen.
1312      Debug.debugException(e);
1313      return new String(b, offset, length);
1314    }
1315  }
1316
1317
1318
1319  /**
1320   * Indicates whether the provided strings represent an equivalent sequence of
1321   * Unicode characters.  In some cases, Unicode supports multiple ways of
1322   * encoding the same character or sequence of characters, and this method
1323   * accounts for those alternative encodings in the course of making the
1324   * determination.
1325   *
1326   * @param  s1  The first string for which to make the determination.  It must
1327   *             not be {@code null}.
1328   * @param  s2  The second string for which to make the determination.  It must
1329   *             not be {@code null}.
1330   *
1331   * @return  {@code true} if the provided strings represent an equivalent
1332   *          sequence of Unicode characters, or {@code false} if not.
1333   */
1334  public static boolean unicodeStringsAreEquivalent(@NotNull final String s1,
1335                                                    @NotNull final String s2)
1336  {
1337    if (s1.equals(s2))
1338    {
1339      return true;
1340    }
1341
1342    final String normalized1 =  Normalizer.normalize(s1,
1343         DEFAULT_UNICODE_NORMALIZER_FORM);
1344    final String normalized2 = Normalizer.normalize(s2,
1345         DEFAULT_UNICODE_NORMALIZER_FORM);
1346    return normalized1.equals(normalized2);
1347  }
1348
1349
1350
1351  /**
1352   * Indicates whether the provided byte arrays represent UTF-8 strings that
1353   * have an equivalent sequence of Unicode characters.  In some cases, Unicode
1354   * supports multiple ways of encoding the same character or sequence of
1355   * characters, and this method accounts for those alternative encodings in the
1356   * course of making the determination.
1357   *
1358   * @param  b1  The bytes that comprise the UTF-8 representation of the first
1359   *             string for which to make the determination.  It must not be
1360   *             {@code null}.
1361   * @param  b2  The bytes that comprise the UTF-8 representation of the second
1362   *             string for which to make the determination.  It must not be
1363   *             {@code null}.
1364   *
1365   * @return  {@code true} if the provided byte arrays represent UTF-8 strings
1366   *          that have an equivalent sequence of Unicode characters, or
1367   *          {@code false} if not.
1368   */
1369  public static boolean utf8StringsAreEquivalent(@NotNull final byte[] b1,
1370                                                 @NotNull final byte[] b2)
1371  {
1372    if (Arrays.equals(b1, b2))
1373    {
1374      return true;
1375    }
1376
1377    if (isValidUTF8WithNonASCIICharacters(b1) &&
1378         isValidUTF8WithNonASCIICharacters(b2))
1379    {
1380      final String s1 = toUTF8String(b1);
1381      final String normalized1 = Normalizer.normalize(s1,
1382           DEFAULT_UNICODE_NORMALIZER_FORM);
1383
1384      final String s2 = toUTF8String(b2);
1385      final String normalized2 = Normalizer.normalize(s2,
1386           DEFAULT_UNICODE_NORMALIZER_FORM);
1387
1388      return normalized1.equals(normalized2);
1389    }
1390
1391    return false;
1392  }
1393
1394
1395
1396  /**
1397   * Retrieves a version of the provided string with the first character
1398   * converted to lowercase but all other characters retaining their original
1399   * capitalization.
1400   *
1401   * @param  s  The string to be processed.
1402   *
1403   * @return  A version of the provided string with the first character
1404   *          converted to lowercase but all other characters retaining their
1405   *          original capitalization.  It may be {@code null} if the provided
1406   *          string is {@code null}.
1407   */
1408  @Nullable()
1409  public static String toInitialLowerCase(@Nullable final String s)
1410  {
1411    if ((s == null) || s.isEmpty())
1412    {
1413      return s;
1414    }
1415    else if (s.length() == 1)
1416    {
1417      return toLowerCase(s);
1418    }
1419    else
1420    {
1421      final char c = s.charAt(0);
1422      if (((c >= 'A') && (c <= 'Z')) || (c < ' ') || (c > '~'))
1423      {
1424        final StringBuilder b = new StringBuilder(s);
1425        b.setCharAt(0, Character.toLowerCase(c));
1426        return b.toString();
1427      }
1428      else
1429      {
1430        return s;
1431      }
1432    }
1433  }
1434
1435
1436
1437  /**
1438   * Retrieves an all-lowercase version of the provided string.
1439   *
1440   * @param  s  The string for which to retrieve the lowercase version.
1441   *
1442   * @return  An all-lowercase version of the provided string, or {@code null}
1443   *          if the provided string was {@code null}.
1444   */
1445  @Nullable()
1446  public static String toLowerCase(@Nullable final String s)
1447  {
1448    if (s == null)
1449    {
1450      return null;
1451    }
1452
1453    final int length = s.length();
1454    final char[] charArray = s.toCharArray();
1455    for (int i=0; i < length; i++)
1456    {
1457      switch (charArray[i])
1458      {
1459        case 'A':
1460          charArray[i] = 'a';
1461          break;
1462        case 'B':
1463          charArray[i] = 'b';
1464          break;
1465        case 'C':
1466          charArray[i] = 'c';
1467          break;
1468        case 'D':
1469          charArray[i] = 'd';
1470          break;
1471        case 'E':
1472          charArray[i] = 'e';
1473          break;
1474        case 'F':
1475          charArray[i] = 'f';
1476          break;
1477        case 'G':
1478          charArray[i] = 'g';
1479          break;
1480        case 'H':
1481          charArray[i] = 'h';
1482          break;
1483        case 'I':
1484          charArray[i] = 'i';
1485          break;
1486        case 'J':
1487          charArray[i] = 'j';
1488          break;
1489        case 'K':
1490          charArray[i] = 'k';
1491          break;
1492        case 'L':
1493          charArray[i] = 'l';
1494          break;
1495        case 'M':
1496          charArray[i] = 'm';
1497          break;
1498        case 'N':
1499          charArray[i] = 'n';
1500          break;
1501        case 'O':
1502          charArray[i] = 'o';
1503          break;
1504        case 'P':
1505          charArray[i] = 'p';
1506          break;
1507        case 'Q':
1508          charArray[i] = 'q';
1509          break;
1510        case 'R':
1511          charArray[i] = 'r';
1512          break;
1513        case 'S':
1514          charArray[i] = 's';
1515          break;
1516        case 'T':
1517          charArray[i] = 't';
1518          break;
1519        case 'U':
1520          charArray[i] = 'u';
1521          break;
1522        case 'V':
1523          charArray[i] = 'v';
1524          break;
1525        case 'W':
1526          charArray[i] = 'w';
1527          break;
1528        case 'X':
1529          charArray[i] = 'x';
1530          break;
1531        case 'Y':
1532          charArray[i] = 'y';
1533          break;
1534        case 'Z':
1535          charArray[i] = 'z';
1536          break;
1537        default:
1538          if (charArray[i] > 0x7F)
1539          {
1540            return s.toLowerCase();
1541          }
1542          break;
1543      }
1544    }
1545
1546    return new String(charArray);
1547  }
1548
1549
1550
1551  /**
1552   * Retrieves an all-uppercase version of the provided string.
1553   *
1554   * @param  s  The string for which to retrieve the uppercase version.
1555   *
1556   * @return  An all-uppercase version of the provided string, or {@code null}
1557   *          if the provided string was {@code null}.
1558   */
1559  @Nullable()
1560  public static String toUpperCase(@Nullable final String s)
1561  {
1562    if (s == null)
1563    {
1564      return null;
1565    }
1566
1567    final int length = s.length();
1568    final char[] charArray = s.toCharArray();
1569    for (int i=0; i < length; i++)
1570    {
1571      switch (charArray[i])
1572      {
1573        case 'a':
1574          charArray[i] = 'A';
1575          break;
1576        case 'b':
1577          charArray[i] = 'B';
1578          break;
1579        case 'c':
1580          charArray[i] = 'C';
1581          break;
1582        case 'd':
1583          charArray[i] = 'D';
1584          break;
1585        case 'e':
1586          charArray[i] = 'E';
1587          break;
1588        case 'f':
1589          charArray[i] = 'F';
1590          break;
1591        case 'g':
1592          charArray[i] = 'G';
1593          break;
1594        case 'h':
1595          charArray[i] = 'H';
1596          break;
1597        case 'i':
1598          charArray[i] = 'I';
1599          break;
1600        case 'j':
1601          charArray[i] = 'J';
1602          break;
1603        case 'k':
1604          charArray[i] = 'K';
1605          break;
1606        case 'l':
1607          charArray[i] = 'L';
1608          break;
1609        case 'm':
1610          charArray[i] = 'M';
1611          break;
1612        case 'n':
1613          charArray[i] = 'N';
1614          break;
1615        case 'o':
1616          charArray[i] = 'O';
1617          break;
1618        case 'p':
1619          charArray[i] = 'P';
1620          break;
1621        case 'q':
1622          charArray[i] = 'Q';
1623          break;
1624        case 'r':
1625          charArray[i] = 'R';
1626          break;
1627        case 's':
1628          charArray[i] = 'S';
1629          break;
1630        case 't':
1631          charArray[i] = 'T';
1632          break;
1633        case 'u':
1634          charArray[i] = 'U';
1635          break;
1636        case 'v':
1637          charArray[i] = 'V';
1638          break;
1639        case 'w':
1640          charArray[i] = 'W';
1641          break;
1642        case 'x':
1643          charArray[i] = 'X';
1644          break;
1645        case 'y':
1646          charArray[i] = 'Y';
1647          break;
1648        case 'z':
1649          charArray[i] = 'Z';
1650          break;
1651        default:
1652          if (charArray[i] > 0x7F)
1653          {
1654            return s.toUpperCase();
1655          }
1656          break;
1657      }
1658    }
1659
1660    return new String(charArray);
1661  }
1662
1663
1664
1665  /**
1666   * Indicates whether the provided character is a valid hexadecimal digit.
1667   *
1668   * @param  c  The character for which to make the determination.
1669   *
1670   * @return  {@code true} if the provided character does represent a valid
1671   *          hexadecimal digit, or {@code false} if not.
1672   */
1673  public static boolean isHex(final char c)
1674  {
1675    switch (c)
1676    {
1677      case '0':
1678      case '1':
1679      case '2':
1680      case '3':
1681      case '4':
1682      case '5':
1683      case '6':
1684      case '7':
1685      case '8':
1686      case '9':
1687      case 'a':
1688      case 'A':
1689      case 'b':
1690      case 'B':
1691      case 'c':
1692      case 'C':
1693      case 'd':
1694      case 'D':
1695      case 'e':
1696      case 'E':
1697      case 'f':
1698      case 'F':
1699        return true;
1700
1701      default:
1702        return false;
1703    }
1704  }
1705
1706
1707
1708  /**
1709   * Retrieves a hexadecimal representation of the provided byte.
1710   *
1711   * @param  b  The byte to encode as hexadecimal.
1712   *
1713   * @return  A string containing the hexadecimal representation of the provided
1714   *          byte.
1715   */
1716  @NotNull()
1717  public static String toHex(final byte b)
1718  {
1719    final StringBuilder buffer = new StringBuilder(2);
1720    toHex(b, buffer);
1721    return buffer.toString();
1722  }
1723
1724
1725
1726  /**
1727   * Appends a hexadecimal representation of the provided byte to the given
1728   * buffer.
1729   *
1730   * @param  b       The byte to encode as hexadecimal.
1731   * @param  buffer  The buffer to which the hexadecimal representation is to be
1732   *                 appended.
1733   */
1734  public static void toHex(final byte b, @NotNull final StringBuilder buffer)
1735  {
1736    switch (b & 0xF0)
1737    {
1738      case 0x00:
1739        buffer.append('0');
1740        break;
1741      case 0x10:
1742        buffer.append('1');
1743        break;
1744      case 0x20:
1745        buffer.append('2');
1746        break;
1747      case 0x30:
1748        buffer.append('3');
1749        break;
1750      case 0x40:
1751        buffer.append('4');
1752        break;
1753      case 0x50:
1754        buffer.append('5');
1755        break;
1756      case 0x60:
1757        buffer.append('6');
1758        break;
1759      case 0x70:
1760        buffer.append('7');
1761        break;
1762      case 0x80:
1763        buffer.append('8');
1764        break;
1765      case 0x90:
1766        buffer.append('9');
1767        break;
1768      case 0xA0:
1769        buffer.append('a');
1770        break;
1771      case 0xB0:
1772        buffer.append('b');
1773        break;
1774      case 0xC0:
1775        buffer.append('c');
1776        break;
1777      case 0xD0:
1778        buffer.append('d');
1779        break;
1780      case 0xE0:
1781        buffer.append('e');
1782        break;
1783      case 0xF0:
1784        buffer.append('f');
1785        break;
1786    }
1787
1788    switch (b & 0x0F)
1789    {
1790      case 0x00:
1791        buffer.append('0');
1792        break;
1793      case 0x01:
1794        buffer.append('1');
1795        break;
1796      case 0x02:
1797        buffer.append('2');
1798        break;
1799      case 0x03:
1800        buffer.append('3');
1801        break;
1802      case 0x04:
1803        buffer.append('4');
1804        break;
1805      case 0x05:
1806        buffer.append('5');
1807        break;
1808      case 0x06:
1809        buffer.append('6');
1810        break;
1811      case 0x07:
1812        buffer.append('7');
1813        break;
1814      case 0x08:
1815        buffer.append('8');
1816        break;
1817      case 0x09:
1818        buffer.append('9');
1819        break;
1820      case 0x0A:
1821        buffer.append('a');
1822        break;
1823      case 0x0B:
1824        buffer.append('b');
1825        break;
1826      case 0x0C:
1827        buffer.append('c');
1828        break;
1829      case 0x0D:
1830        buffer.append('d');
1831        break;
1832      case 0x0E:
1833        buffer.append('e');
1834        break;
1835      case 0x0F:
1836        buffer.append('f');
1837        break;
1838    }
1839  }
1840
1841
1842
1843  /**
1844   * Appends a hexadecimal representation of the provided byte to the given
1845   * buffer.
1846   *
1847   * @param  b       The byte to encode as hexadecimal.
1848   * @param  buffer  The buffer to which the hexadecimal representation is to be
1849   *                 appended.
1850   */
1851  public static void toHex(final byte b, @NotNull final ByteStringBuffer buffer)
1852  {
1853    switch (b & 0xF0)
1854    {
1855      case 0x00:
1856        buffer.append((byte) '0');
1857        break;
1858      case 0x10:
1859        buffer.append((byte) '1');
1860        break;
1861      case 0x20:
1862        buffer.append((byte) '2');
1863        break;
1864      case 0x30:
1865        buffer.append((byte) '3');
1866        break;
1867      case 0x40:
1868        buffer.append((byte) '4');
1869        break;
1870      case 0x50:
1871        buffer.append((byte) '5');
1872        break;
1873      case 0x60:
1874        buffer.append((byte) '6');
1875        break;
1876      case 0x70:
1877        buffer.append((byte) '7');
1878        break;
1879      case 0x80:
1880        buffer.append((byte) '8');
1881        break;
1882      case 0x90:
1883        buffer.append((byte) '9');
1884        break;
1885      case 0xA0:
1886        buffer.append((byte) 'a');
1887        break;
1888      case 0xB0:
1889        buffer.append((byte) 'b');
1890        break;
1891      case 0xC0:
1892        buffer.append((byte) 'c');
1893        break;
1894      case 0xD0:
1895        buffer.append((byte) 'd');
1896        break;
1897      case 0xE0:
1898        buffer.append((byte) 'e');
1899        break;
1900      case 0xF0:
1901        buffer.append((byte) 'f');
1902        break;
1903    }
1904
1905    switch (b & 0x0F)
1906    {
1907      case 0x00:
1908        buffer.append((byte) '0');
1909        break;
1910      case 0x01:
1911        buffer.append((byte) '1');
1912        break;
1913      case 0x02:
1914        buffer.append((byte) '2');
1915        break;
1916      case 0x03:
1917        buffer.append((byte) '3');
1918        break;
1919      case 0x04:
1920        buffer.append((byte) '4');
1921        break;
1922      case 0x05:
1923        buffer.append((byte) '5');
1924        break;
1925      case 0x06:
1926        buffer.append((byte) '6');
1927        break;
1928      case 0x07:
1929        buffer.append((byte) '7');
1930        break;
1931      case 0x08:
1932        buffer.append((byte) '8');
1933        break;
1934      case 0x09:
1935        buffer.append((byte) '9');
1936        break;
1937      case 0x0A:
1938        buffer.append((byte) 'a');
1939        break;
1940      case 0x0B:
1941        buffer.append((byte) 'b');
1942        break;
1943      case 0x0C:
1944        buffer.append((byte) 'c');
1945        break;
1946      case 0x0D:
1947        buffer.append((byte) 'd');
1948        break;
1949      case 0x0E:
1950        buffer.append((byte) 'e');
1951        break;
1952      case 0x0F:
1953        buffer.append((byte) 'f');
1954        break;
1955    }
1956  }
1957
1958
1959
1960  /**
1961   * Retrieves a hexadecimal representation of the contents of the provided byte
1962   * array.  No delimiter character will be inserted between the hexadecimal
1963   * digits for each byte.
1964   *
1965   * @param  b  The byte array to be represented as a hexadecimal string.  It
1966   *            must not be {@code null}.
1967   *
1968   * @return  A string containing a hexadecimal representation of the contents
1969   *          of the provided byte array.
1970   */
1971  @NotNull()
1972  public static String toHex(@NotNull final byte[] b)
1973  {
1974    Validator.ensureNotNull(b);
1975
1976    final StringBuilder buffer = new StringBuilder(2 * b.length);
1977    toHex(b, buffer);
1978    return buffer.toString();
1979  }
1980
1981
1982
1983  /**
1984   * Retrieves a hexadecimal representation of the contents of the provided byte
1985   * array.  No delimiter character will be inserted between the hexadecimal
1986   * digits for each byte.
1987   *
1988   * @param  b       The byte array to be represented as a hexadecimal string.
1989   *                 It must not be {@code null}.
1990   * @param  buffer  A buffer to which the hexadecimal representation of the
1991   *                 contents of the provided byte array should be appended.
1992   */
1993  public static void toHex(@NotNull final byte[] b,
1994                           @NotNull final StringBuilder buffer)
1995  {
1996    toHex(b, null, buffer);
1997  }
1998
1999
2000
2001  /**
2002   * Retrieves a hexadecimal representation of the contents of the provided byte
2003   * array.  No delimiter character will be inserted between the hexadecimal
2004   * digits for each byte.
2005   *
2006   * @param  b          The byte array to be represented as a hexadecimal
2007   *                    string.  It must not be {@code null}.
2008   * @param  delimiter  A delimiter to be inserted between bytes.  It may be
2009   *                    {@code null} if no delimiter should be used.
2010   * @param  buffer     A buffer to which the hexadecimal representation of the
2011   *                    contents of the provided byte array should be appended.
2012   */
2013  public static void toHex(@NotNull final byte[] b,
2014                           @Nullable final String delimiter,
2015                           @NotNull final StringBuilder buffer)
2016  {
2017    boolean first = true;
2018    for (final byte bt : b)
2019    {
2020      if (first)
2021      {
2022        first = false;
2023      }
2024      else if (delimiter != null)
2025      {
2026        buffer.append(delimiter);
2027      }
2028
2029      toHex(bt, buffer);
2030    }
2031  }
2032
2033
2034
2035  /**
2036   * Retrieves a hex-encoded representation of the contents of the provided
2037   * array, along with an ASCII representation of its contents next to it.  The
2038   * output will be split across multiple lines, with up to sixteen bytes per
2039   * line.  For each of those sixteen bytes, the two-digit hex representation
2040   * will be appended followed by a space.  Then, the ASCII representation of
2041   * those sixteen bytes will follow that, with a space used in place of any
2042   * byte that does not have an ASCII representation.
2043   *
2044   * @param  array   The array whose contents should be processed.
2045   * @param  indent  The number of spaces to insert on each line prior to the
2046   *                 first hex byte.
2047   *
2048   * @return  A hex-encoded representation of the contents of the provided
2049   *          array, along with an ASCII representation of its contents next to
2050   *          it.
2051   */
2052  @NotNull()
2053  public static String toHexPlusASCII(@NotNull final byte[] array,
2054                                      final int indent)
2055  {
2056    final StringBuilder buffer = new StringBuilder();
2057    toHexPlusASCII(array, indent, buffer);
2058    return buffer.toString();
2059  }
2060
2061
2062
2063  /**
2064   * Appends a hex-encoded representation of the contents of the provided array
2065   * to the given buffer, along with an ASCII representation of its contents
2066   * next to it.  The output will be split across multiple lines, with up to
2067   * sixteen bytes per line.  For each of those sixteen bytes, the two-digit hex
2068   * representation will be appended followed by a space.  Then, the ASCII
2069   * representation of those sixteen bytes will follow that, with a space used
2070   * in place of any byte that does not have an ASCII representation.
2071   *
2072   * @param  array   The array whose contents should be processed.
2073   * @param  indent  The number of spaces to insert on each line prior to the
2074   *                 first hex byte.
2075   * @param  buffer  The buffer to which the encoded data should be appended.
2076   */
2077  public static void toHexPlusASCII(@Nullable final byte[] array,
2078                                    final int indent,
2079                                    @NotNull final StringBuilder buffer)
2080  {
2081    if ((array == null) || (array.length == 0))
2082    {
2083      return;
2084    }
2085
2086    for (int i=0; i < indent; i++)
2087    {
2088      buffer.append(' ');
2089    }
2090
2091    int pos = 0;
2092    int startPos = 0;
2093    while (pos < array.length)
2094    {
2095      toHex(array[pos++], buffer);
2096      buffer.append(' ');
2097
2098      if ((pos % 16) == 0)
2099      {
2100        buffer.append("  ");
2101        for (int i=startPos; i < pos; i++)
2102        {
2103          if ((array[i] < ' ') || (array[i] > '~'))
2104          {
2105            buffer.append(' ');
2106          }
2107          else
2108          {
2109            buffer.append((char) array[i]);
2110          }
2111        }
2112        buffer.append(EOL);
2113        startPos = pos;
2114
2115        if (pos < array.length)
2116        {
2117          for (int i=0; i < indent; i++)
2118          {
2119            buffer.append(' ');
2120          }
2121        }
2122      }
2123    }
2124
2125    // If the last line isn't complete yet, then finish it off.
2126    if ((array.length % 16) != 0)
2127    {
2128      final int missingBytes = (16 - (array.length % 16));
2129      for (int i=0; i < missingBytes; i++)
2130      {
2131        buffer.append("   ");
2132      }
2133      buffer.append("  ");
2134      for (int i=startPos; i < array.length; i++)
2135      {
2136        if ((array[i] < ' ') || (array[i] > '~'))
2137        {
2138          buffer.append(' ');
2139        }
2140        else
2141        {
2142          buffer.append((char) array[i]);
2143        }
2144      }
2145      buffer.append(EOL);
2146    }
2147  }
2148
2149
2150
2151  /**
2152   * Retrieves the bytes that correspond to the provided hexadecimal string.
2153   *
2154   * @param  hexString  The hexadecimal string for which to retrieve the bytes.
2155   *                    It must not be {@code null}, and there must not be any
2156   *                    delimiter between bytes.
2157   *
2158   * @return  The bytes that correspond to the provided hexadecimal string.
2159   *
2160   * @throws  ParseException  If the provided string does not represent valid
2161   *                          hexadecimal data, or if the provided string does
2162   *                          not contain an even number of characters.
2163   */
2164  @NotNull()
2165  public static byte[] fromHex(@NotNull final String hexString)
2166         throws ParseException
2167  {
2168    if ((hexString.length() % 2) != 0)
2169    {
2170      throw new ParseException(
2171           ERR_FROM_HEX_ODD_NUMBER_OF_CHARACTERS.get(hexString.length()),
2172           hexString.length());
2173    }
2174
2175    final byte[] decodedBytes = new byte[hexString.length() / 2];
2176    for (int i=0, j=0; i < decodedBytes.length; i++, j+= 2)
2177    {
2178      switch (hexString.charAt(j))
2179      {
2180        case '0':
2181          // No action is required.
2182          break;
2183        case '1':
2184          decodedBytes[i] = 0x10;
2185          break;
2186        case '2':
2187          decodedBytes[i] = 0x20;
2188          break;
2189        case '3':
2190          decodedBytes[i] = 0x30;
2191          break;
2192        case '4':
2193          decodedBytes[i] = 0x40;
2194          break;
2195        case '5':
2196          decodedBytes[i] = 0x50;
2197          break;
2198        case '6':
2199          decodedBytes[i] = 0x60;
2200          break;
2201        case '7':
2202          decodedBytes[i] = 0x70;
2203          break;
2204        case '8':
2205          decodedBytes[i] = (byte) 0x80;
2206          break;
2207        case '9':
2208          decodedBytes[i] = (byte) 0x90;
2209          break;
2210        case 'a':
2211        case 'A':
2212          decodedBytes[i] = (byte) 0xA0;
2213          break;
2214        case 'b':
2215        case 'B':
2216          decodedBytes[i] = (byte) 0xB0;
2217          break;
2218        case 'c':
2219        case 'C':
2220          decodedBytes[i] = (byte) 0xC0;
2221          break;
2222        case 'd':
2223        case 'D':
2224          decodedBytes[i] = (byte) 0xD0;
2225          break;
2226        case 'e':
2227        case 'E':
2228          decodedBytes[i] = (byte) 0xE0;
2229          break;
2230        case 'f':
2231        case 'F':
2232          decodedBytes[i] = (byte) 0xF0;
2233          break;
2234        default:
2235          throw new ParseException(ERR_FROM_HEX_NON_HEX_CHARACTER.get(j), j);
2236      }
2237
2238      switch (hexString.charAt(j+1))
2239      {
2240        case '0':
2241          // No action is required.
2242          break;
2243        case '1':
2244          decodedBytes[i] |= 0x01;
2245          break;
2246        case '2':
2247          decodedBytes[i] |= 0x02;
2248          break;
2249        case '3':
2250          decodedBytes[i] |= 0x03;
2251          break;
2252        case '4':
2253          decodedBytes[i] |= 0x04;
2254          break;
2255        case '5':
2256          decodedBytes[i] |= 0x05;
2257          break;
2258        case '6':
2259          decodedBytes[i] |= 0x06;
2260          break;
2261        case '7':
2262          decodedBytes[i] |= 0x07;
2263          break;
2264        case '8':
2265          decodedBytes[i] |= 0x08;
2266          break;
2267        case '9':
2268          decodedBytes[i] |= 0x09;
2269          break;
2270        case 'a':
2271        case 'A':
2272          decodedBytes[i] |= 0x0A;
2273          break;
2274        case 'b':
2275        case 'B':
2276          decodedBytes[i] |= 0x0B;
2277          break;
2278        case 'c':
2279        case 'C':
2280          decodedBytes[i] |= 0x0C;
2281          break;
2282        case 'd':
2283        case 'D':
2284          decodedBytes[i] |= 0x0D;
2285          break;
2286        case 'e':
2287        case 'E':
2288          decodedBytes[i] |= 0x0E;
2289          break;
2290        case 'f':
2291        case 'F':
2292          decodedBytes[i] |= 0x0F;
2293          break;
2294        default:
2295          throw new ParseException(ERR_FROM_HEX_NON_HEX_CHARACTER.get(j+1),
2296               j+1);
2297      }
2298    }
2299
2300    return decodedBytes;
2301  }
2302
2303
2304
2305  /**
2306   * Appends a hex-encoded representation of the provided character to the given
2307   * buffer.  Each byte of the hex-encoded representation will be prefixed with
2308   * a backslash.
2309   *
2310   * @param  c       The character to be encoded.
2311   * @param  buffer  The buffer to which the hex-encoded representation should
2312   *                 be appended.
2313   */
2314  public static void hexEncode(final char c,
2315                               @NotNull final StringBuilder buffer)
2316  {
2317    final byte[] charBytes;
2318    if (c <= 0x7F)
2319    {
2320      charBytes = new byte[] { (byte) (c & 0x7F) };
2321    }
2322    else
2323    {
2324      charBytes = getBytes(String.valueOf(c));
2325    }
2326
2327    for (final byte b : charBytes)
2328    {
2329      buffer.append('\\');
2330      toHex(b, buffer);
2331    }
2332  }
2333
2334
2335
2336  /**
2337   * Appends a hex-encoded representation of the provided code point to the
2338   * given buffer.  Each byte of the hex-encoded representation will be prefixed
2339   * with a backslash.
2340   *
2341   * @param  codePoint  The code point to be encoded.
2342   * @param  buffer     The buffer to which the hex-encoded representation
2343   *                    should be appended.
2344   */
2345  public static void hexEncode(final int codePoint,
2346                               @NotNull final StringBuilder buffer)
2347  {
2348    final byte[] charBytes =
2349         getBytes(new String(new int[] { codePoint }, 0, 1));
2350
2351    for (final byte b : charBytes)
2352    {
2353      buffer.append('\\');
2354      toHex(b, buffer);
2355    }
2356  }
2357
2358
2359
2360  /**
2361   * Appends the Java code that may be used to create the provided byte
2362   * array to the given buffer.
2363   *
2364   * @param  array   The byte array containing the data to represent.  It must
2365   *                 not be {@code null}.
2366   * @param  buffer  The buffer to which the code should be appended.
2367   */
2368  public static void byteArrayToCode(@NotNull final byte[] array,
2369                                     @NotNull final StringBuilder buffer)
2370  {
2371    buffer.append("new byte[] {");
2372    for (int i=0; i < array.length; i++)
2373    {
2374      if (i > 0)
2375      {
2376        buffer.append(',');
2377      }
2378
2379      buffer.append(" (byte) 0x");
2380      toHex(array[i], buffer);
2381    }
2382    buffer.append(" }");
2383  }
2384
2385
2386
2387  /**
2388   * Retrieves a single-line string representation of the stack trace for the
2389   * provided {@code Throwable}.  It will include the unqualified name of the
2390   * {@code Throwable} class, a list of source files and line numbers (if
2391   * available) for the stack trace, and will also include the stack trace for
2392   * the cause (if present).
2393   *
2394   * @param  t  The {@code Throwable} for which to retrieve the stack trace.
2395   *
2396   * @return  A single-line string representation of the stack trace for the
2397   *          provided {@code Throwable}.
2398   */
2399  @NotNull()
2400  public static String getStackTrace(@NotNull final Throwable t)
2401  {
2402    final StringBuilder buffer = new StringBuilder();
2403    getStackTrace(t, buffer);
2404    return buffer.toString();
2405  }
2406
2407
2408
2409  /**
2410   * Appends a single-line string representation of the stack trace for the
2411   * provided {@code Throwable} to the given buffer.  It will include the
2412   * unqualified name of the {@code Throwable} class, a list of source files and
2413   * line numbers (if available) for the stack trace, and will also include the
2414   * stack trace for the cause (if present).
2415   *
2416   * @param  t       The {@code Throwable} for which to retrieve the stack
2417   *                 trace.
2418   * @param  buffer  The buffer to which the information should be appended.
2419   */
2420  public static void getStackTrace(@NotNull final Throwable t,
2421                                   @NotNull final StringBuilder buffer)
2422  {
2423    buffer.append(getUnqualifiedClassName(t.getClass()));
2424    buffer.append('(');
2425
2426    final String message = t.getMessage();
2427    if (message != null)
2428    {
2429      buffer.append("message='");
2430      buffer.append(message);
2431      buffer.append("', ");
2432    }
2433
2434    buffer.append("trace='");
2435    getStackTrace(t.getStackTrace(), buffer);
2436    buffer.append('\'');
2437
2438    final Throwable cause = t.getCause();
2439    if (cause != null)
2440    {
2441      buffer.append(", cause=");
2442      getStackTrace(cause, buffer);
2443    }
2444
2445    final String ldapSDKVersionString = ", ldapSDKVersion=" +
2446         Version.NUMERIC_VERSION_STRING + ", revision=" + Version.REVISION_ID;
2447    if (buffer.indexOf(ldapSDKVersionString) < 0)
2448    {
2449      buffer.append(ldapSDKVersionString);
2450    }
2451
2452    buffer.append(')');
2453  }
2454
2455
2456
2457  /**
2458   * Returns a single-line string representation of the stack trace.  It will
2459   * include a list of source files and line numbers (if available) for the
2460   * stack trace.
2461   *
2462   * @param  elements  The stack trace.
2463   *
2464   * @return  A single-line string representation of the stack trace.
2465   */
2466  @NotNull()
2467  public static String getStackTrace(
2468                            @NotNull final StackTraceElement[] elements)
2469  {
2470    final StringBuilder buffer = new StringBuilder();
2471    getStackTrace(elements, buffer);
2472    return buffer.toString();
2473  }
2474
2475
2476
2477  /**
2478   * Appends a single-line string representation of the stack trace to the given
2479   * buffer.  It will include a list of source files and line numbers
2480   * (if available) for the stack trace.
2481   *
2482   * @param  elements  The stack trace.
2483   * @param  buffer    The buffer to which the information should be appended.
2484   */
2485  public static void getStackTrace(@NotNull final StackTraceElement[] elements,
2486                                   @NotNull final StringBuilder buffer)
2487  {
2488    getStackTrace(elements, buffer, -1);
2489  }
2490
2491
2492
2493  /**
2494   * Appends a single-line string representation of the stack trace to the given
2495   * buffer.  It will include a list of source files and line numbers
2496   * (if available) for the stack trace.
2497   *
2498   * @param  elements         The stack trace.
2499   * @param  buffer           The buffer to which the information should be
2500   *                          appended.
2501   * @param  maxPreSDKFrames  The maximum number of stack trace frames to
2502   *                          include from code invoked before calling into the
2503   *                          LDAP SDK.  A value of zero indicates that only
2504   *                          stack trace frames from the LDAP SDK itself (or
2505   *                          things that it calls) will be included.  A
2506   *                          negative value indicates that
2507   */
2508  public static void getStackTrace(@NotNull final StackTraceElement[] elements,
2509                                   @NotNull final StringBuilder buffer,
2510                                   final int maxPreSDKFrames)
2511  {
2512    boolean sdkElementFound = false;
2513    int numPreSDKElementsFound = 0;
2514    for (int i=0; i < elements.length; i++)
2515    {
2516      if (i > 0)
2517      {
2518        buffer.append(" / ");
2519      }
2520
2521      if (elements[i].getClassName().startsWith("com.unboundid."))
2522      {
2523        sdkElementFound = true;
2524      }
2525      else if (sdkElementFound)
2526      {
2527        if ((maxPreSDKFrames >= 0) &&
2528             (numPreSDKElementsFound >= maxPreSDKFrames))
2529        {
2530          buffer.append("...");
2531          return;
2532        }
2533
2534        numPreSDKElementsFound++;
2535      }
2536
2537      buffer.append(elements[i].getMethodName());
2538      buffer.append('(');
2539      buffer.append(elements[i].getFileName());
2540
2541      final int lineNumber = elements[i].getLineNumber();
2542      if (lineNumber > 0)
2543      {
2544        buffer.append(':');
2545        buffer.append(lineNumber);
2546      }
2547      else if (elements[i].isNativeMethod())
2548      {
2549        buffer.append(":native");
2550      }
2551      else
2552      {
2553        buffer.append(":unknown");
2554      }
2555      buffer.append(')');
2556    }
2557  }
2558
2559
2560
2561  /**
2562   * Retrieves a string representation of the provided {@code Throwable} object
2563   * suitable for use in a message.  For runtime exceptions and errors, then a
2564   * full stack trace for the exception will be provided.  For exception types
2565   * defined in the LDAP SDK, then its {@code getExceptionMessage} method will
2566   * be used to get the string representation.  For all other types of
2567   * exceptions, then the standard string representation will be used.
2568   * <BR><BR>
2569   * For all types of exceptions, the message will also include the cause if one
2570   * exists.
2571   *
2572   * @param  t  The {@code Throwable} for which to generate the exception
2573   *            message.
2574   *
2575   * @return  A string representation of the provided {@code Throwable} object
2576   *          suitable for use in a message.
2577   */
2578  @NotNull()
2579  public static String getExceptionMessage(@NotNull final Throwable t)
2580  {
2581    final boolean includeCause =
2582         Boolean.getBoolean(Debug.PROPERTY_INCLUDE_CAUSE_IN_EXCEPTION_MESSAGES);
2583    final boolean includeStackTrace = Boolean.getBoolean(
2584         Debug.PROPERTY_INCLUDE_STACK_TRACE_IN_EXCEPTION_MESSAGES);
2585
2586    return getExceptionMessage(t, includeCause, includeStackTrace);
2587  }
2588
2589
2590
2591  /**
2592   * Retrieves a string representation of the provided {@code Throwable} object
2593   * suitable for use in a message.  For runtime exceptions and errors, then a
2594   * full stack trace for the exception will be provided.  For exception types
2595   * defined in the LDAP SDK, then its {@code getExceptionMessage} method will
2596   * be used to get the string representation.  For all other types of
2597   * exceptions, then the standard string representation will be used.
2598   * <BR><BR>
2599   * For all types of exceptions, the message will also include the cause if one
2600   * exists.
2601   *
2602   * @param  t                  The {@code Throwable} for which to generate the
2603   *                            exception message.
2604   * @param  includeCause       Indicates whether to include information about
2605   *                            the cause (if any) in the exception message.
2606   * @param  includeStackTrace  Indicates whether to include a condensed
2607   *                            representation of the stack trace in the
2608   *                            exception message.
2609   *
2610   * @return  A string representation of the provided {@code Throwable} object
2611   *          suitable for use in a message.
2612   */
2613  @NotNull()
2614  public static String getExceptionMessage(@Nullable final Throwable t,
2615                                           final boolean includeCause,
2616                                           final boolean includeStackTrace)
2617  {
2618    if (t == null)
2619    {
2620      return ERR_NO_EXCEPTION.get();
2621    }
2622
2623    final StringBuilder buffer = new StringBuilder();
2624    if (t instanceof LDAPSDKException)
2625    {
2626      buffer.append(((LDAPSDKException) t).getExceptionMessage());
2627    }
2628    else if (t instanceof LDAPSDKRuntimeException)
2629    {
2630      buffer.append(((LDAPSDKRuntimeException) t).getExceptionMessage());
2631    }
2632    else if (t instanceof NullPointerException)
2633    {
2634      // For NullPointerExceptions, we'll always print at least a portion of
2635      // the stack trace that includes all of the LDAP SDK code, and up to
2636      // three frames of whatever called into the SDK.
2637      buffer.append("NullPointerException(");
2638      getStackTrace(t.getStackTrace(), buffer, 3);
2639      buffer.append(')');
2640    }
2641    else if ((t.getMessage() == null) || t.getMessage().isEmpty() ||
2642         t.getMessage().equalsIgnoreCase("null"))
2643    {
2644      getStackTrace(t, buffer);
2645    }
2646    else
2647    {
2648      buffer.append(t.getClass().getSimpleName());
2649      buffer.append('(');
2650      buffer.append(t.getMessage());
2651      buffer.append(')');
2652
2653      if (includeStackTrace)
2654      {
2655        buffer.append(" trace=");
2656        getStackTrace(t, buffer);
2657      }
2658      else if (includeCause)
2659      {
2660        final Throwable cause = t.getCause();
2661        if (cause != null)
2662        {
2663          buffer.append(" caused by ");
2664          buffer.append(getExceptionMessage(cause));
2665        }
2666      }
2667    }
2668
2669    final String ldapSDKVersionString = ", ldapSDKVersion=" +
2670         Version.NUMERIC_VERSION_STRING + ", revision=" + Version.REVISION_ID;
2671    if (buffer.indexOf(ldapSDKVersionString) < 0)
2672    {
2673      buffer.append(ldapSDKVersionString);
2674    }
2675
2676    return buffer.toString();
2677  }
2678
2679
2680
2681  /**
2682   * Retrieves the unqualified name (i.e., the name without package information)
2683   * for the provided class.
2684   *
2685   * @param  c  The class for which to retrieve the unqualified name.
2686   *
2687   * @return  The unqualified name for the provided class.
2688   */
2689  @NotNull()
2690  public static String getUnqualifiedClassName(@NotNull final Class<?> c)
2691  {
2692    final String className     = c.getName();
2693    final int    lastPeriodPos = className.lastIndexOf('.');
2694
2695    if (lastPeriodPos > 0)
2696    {
2697      return className.substring(lastPeriodPos+1);
2698    }
2699    else
2700    {
2701      return className;
2702    }
2703  }
2704
2705
2706
2707  /**
2708   * Retrieves a {@code TimeZone} object that represents the UTC (universal
2709   * coordinated time) time zone.
2710   *
2711   * @return  A {@code TimeZone} object that represents the UTC time zone.
2712   */
2713  @NotNull()
2714  public static TimeZone getUTCTimeZone()
2715  {
2716    return UTC_TIME_ZONE;
2717  }
2718
2719
2720
2721  /**
2722   * Encodes the provided timestamp in generalized time format.
2723   *
2724   * @param  timestamp  The timestamp to be encoded in generalized time format.
2725   *                    It should use the same format as the
2726   *                    {@code System.currentTimeMillis()} method (i.e., the
2727   *                    number of milliseconds since 12:00am UTC on January 1,
2728   *                    1970).
2729   *
2730   * @return  The generalized time representation of the provided date.
2731   */
2732  @NotNull()
2733  public static String encodeGeneralizedTime(final long timestamp)
2734  {
2735    return encodeGeneralizedTime(new Date(timestamp));
2736  }
2737
2738
2739
2740  /**
2741   * Encodes the provided date in generalized time format.
2742   *
2743   * @param  d  The date to be encoded in generalized time format.
2744   *
2745   * @return  The generalized time representation of the provided date.
2746   */
2747  @NotNull()
2748  public static String encodeGeneralizedTime(@NotNull final Date d)
2749  {
2750    SimpleDateFormat dateFormat = GENERALIZED_TIME_FORMATTERS.get();
2751    if (dateFormat == null)
2752    {
2753      dateFormat = new SimpleDateFormat("yyyyMMddHHmmss.SSS'Z'");
2754      dateFormat.setTimeZone(UTC_TIME_ZONE);
2755      GENERALIZED_TIME_FORMATTERS.set(dateFormat);
2756    }
2757
2758    return dateFormat.format(d);
2759  }
2760
2761
2762
2763  /**
2764   * Decodes the provided string as a timestamp in generalized time format.
2765   *
2766   * @param  t  The timestamp to be decoded.  It must not be {@code null}.
2767   *
2768   * @return  The {@code Date} object decoded from the provided timestamp.
2769   *
2770   * @throws  ParseException  If the provided string could not be decoded as a
2771   *                          timestamp in generalized time format.
2772   */
2773  @NotNull()
2774  public static Date decodeGeneralizedTime(@NotNull final String t)
2775         throws ParseException
2776  {
2777    Validator.ensureNotNull(t);
2778
2779    // Extract the time zone information from the end of the value.
2780    int tzPos;
2781    final TimeZone tz;
2782    if (t.endsWith("Z"))
2783    {
2784      tz = TimeZone.getTimeZone("UTC");
2785      tzPos = t.length() - 1;
2786    }
2787    else
2788    {
2789      tzPos = t.lastIndexOf('-');
2790      if (tzPos < 0)
2791      {
2792        tzPos = t.lastIndexOf('+');
2793        if (tzPos < 0)
2794        {
2795          throw new ParseException(ERR_GENTIME_DECODE_CANNOT_PARSE_TZ.get(t),
2796                                   0);
2797        }
2798      }
2799
2800      tz = TimeZone.getTimeZone("GMT" + t.substring(tzPos));
2801      if (tz.getRawOffset() == 0)
2802      {
2803        // This is the default time zone that will be returned if the value
2804        // cannot be parsed.  If it's valid, then it will end in "+0000" or
2805        // "-0000".  Otherwise, it's invalid and GMT was just a fallback.
2806        if (! (t.endsWith("+0000") || t.endsWith("-0000")))
2807        {
2808          throw new ParseException(ERR_GENTIME_DECODE_CANNOT_PARSE_TZ.get(t),
2809                                   tzPos);
2810        }
2811      }
2812    }
2813
2814
2815    // See if the timestamp has a sub-second portion.  Note that if there is a
2816    // sub-second portion, then we may need to massage the value so that there
2817    // are exactly three sub-second characters so that it can be interpreted as
2818    // milliseconds.
2819    final String subSecFormatStr;
2820    final String trimmedTimestamp;
2821    int periodPos = t.lastIndexOf('.', tzPos);
2822    if (periodPos > 0)
2823    {
2824      final int subSecondLength = tzPos - periodPos - 1;
2825      switch (subSecondLength)
2826      {
2827        case 0:
2828          subSecFormatStr  = "";
2829          trimmedTimestamp = t.substring(0, periodPos);
2830          break;
2831        case 1:
2832          subSecFormatStr  = ".SSS";
2833          trimmedTimestamp = t.substring(0, (periodPos+2)) + "00";
2834          break;
2835        case 2:
2836          subSecFormatStr  = ".SSS";
2837          trimmedTimestamp = t.substring(0, (periodPos+3)) + '0';
2838          break;
2839        default:
2840          subSecFormatStr  = ".SSS";
2841          trimmedTimestamp = t.substring(0, periodPos+4);
2842          break;
2843      }
2844    }
2845    else
2846    {
2847      subSecFormatStr  = "";
2848      periodPos        = tzPos;
2849      trimmedTimestamp = t.substring(0, tzPos);
2850    }
2851
2852
2853    // Look at where the period is (or would be if it existed) to see how many
2854    // characters are in the integer portion.  This will give us what we need
2855    // for the rest of the format string.
2856    final String formatStr;
2857    switch (periodPos)
2858    {
2859      case 10:
2860        formatStr = "yyyyMMddHH" + subSecFormatStr;
2861        break;
2862      case 12:
2863        formatStr = "yyyyMMddHHmm" + subSecFormatStr;
2864        break;
2865      case 14:
2866        formatStr = "yyyyMMddHHmmss" + subSecFormatStr;
2867        break;
2868      default:
2869        throw new ParseException(ERR_GENTIME_CANNOT_PARSE_INVALID_LENGTH.get(t),
2870                                 periodPos);
2871    }
2872
2873
2874    // We should finally be able to create an appropriate date format object
2875    // to parse the trimmed version of the timestamp.
2876    final SimpleDateFormat dateFormat = new SimpleDateFormat(formatStr);
2877    dateFormat.setTimeZone(tz);
2878    dateFormat.setLenient(false);
2879    return dateFormat.parse(trimmedTimestamp);
2880  }
2881
2882
2883
2884  /**
2885   * Encodes the provided timestamp to the ISO 8601 format described in RFC
2886   * 3339.
2887   *
2888   * @param  timestamp  The timestamp to be encoded in the RFC 3339 format.
2889   *                    It should use the same format as the
2890   *                    {@code System.currentTimeMillis()} method (i.e., the
2891   *                    number of milliseconds since 12:00am UTC on January 1,
2892   *                    1970).
2893   *
2894   * @return  The RFC 3339 representation of the provided date.
2895   */
2896  @NotNull()
2897  public static String encodeRFC3339Time(final long timestamp)
2898  {
2899    return encodeRFC3339Time(new Date(timestamp));
2900  }
2901
2902
2903
2904  /**
2905   * Encodes the provided timestamp to the ISO 8601 format described in RFC
2906   * 3339.
2907   *
2908   * @param  d  The date to be encoded in the RFC 3339 format.
2909   *
2910   * @return  The RFC 3339 representation of the provided date.
2911   */
2912  @NotNull()
2913  public static String encodeRFC3339Time(@NotNull final Date d)
2914  {
2915    SimpleDateFormat dateFormat = RFC_3339_TIME_FORMATTERS.get();
2916    if (dateFormat == null)
2917    {
2918      dateFormat = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'");
2919      dateFormat.setTimeZone(UTC_TIME_ZONE);
2920      RFC_3339_TIME_FORMATTERS.set(dateFormat);
2921    }
2922
2923    return dateFormat.format(d);
2924  }
2925
2926
2927
2928  /**
2929   * Decodes the provided string as a timestamp encoded in the ISO 8601 format
2930   * described in RFC 3339.
2931   *
2932   * @param  timestamp  The timestamp to be decoded in the RFC 3339 format.
2933   *
2934   * @return  The {@code Date} object decoded from the provided timestamp.
2935   *
2936   * @throws  ParseException  If the provided string could not be decoded as a
2937   *                          timestamp in the RFC 3339 time format.
2938   */
2939  @NotNull()
2940  public static Date decodeRFC3339Time(@NotNull final String timestamp)
2941         throws ParseException
2942  {
2943    // Make sure that the string representation has the minimum acceptable
2944    // length.
2945    if (timestamp.length() < 20)
2946    {
2947      throw new ParseException(ERR_RFC_3339_TIME_TOO_SHORT.get(timestamp), 0);
2948    }
2949
2950
2951    // Parse the year, month, day, hour, minute, and second components from the
2952    // timestamp, and make sure the appropriate separator characters are between
2953    // those components.
2954    final int year = parseRFC3339Number(timestamp, 0, 4);
2955    validateRFC3339TimestampSeparatorCharacter(timestamp, 4, '-');
2956    final int month = parseRFC3339Number(timestamp, 5, 2);
2957    validateRFC3339TimestampSeparatorCharacter(timestamp, 7, '-');
2958    final int day = parseRFC3339Number(timestamp, 8, 2);
2959    validateRFC3339TimestampSeparatorCharacter(timestamp, 10, 'T');
2960    final int hour = parseRFC3339Number(timestamp, 11, 2);
2961    validateRFC3339TimestampSeparatorCharacter(timestamp, 13, ':');
2962    final int minute = parseRFC3339Number(timestamp, 14, 2);
2963    validateRFC3339TimestampSeparatorCharacter(timestamp, 16, ':');
2964    final int second = parseRFC3339Number(timestamp, 17, 2);
2965
2966
2967    // Make sure that the month and day values are acceptable.
2968    switch (month)
2969    {
2970      case 1:
2971      case 3:
2972      case 5:
2973      case 7:
2974      case 8:
2975      case 10:
2976      case 12:
2977        // January, March, May, July, August, October, and December all have 31
2978        // days.
2979        if ((day < 1) || (day > 31))
2980        {
2981          throw new ParseException(
2982               ERR_RFC_3339_TIME_INVALID_DAY_FOR_MONTH.get(timestamp, day,
2983                    month),
2984               8);
2985        }
2986        break;
2987
2988      case 4:
2989      case 6:
2990      case 9:
2991      case 11:
2992        // April, June, September, and November all have 30 days.
2993        if ((day < 1) || (day > 30))
2994        {
2995          throw new ParseException(
2996               ERR_RFC_3339_TIME_INVALID_DAY_FOR_MONTH.get(timestamp, day,
2997                    month),
2998               8);
2999        }
3000        break;
3001
3002      case 2:
3003        // February can have 28 or 29 days, depending on whether it's a leap
3004        // year.  Although we could determine whether the provided year is a
3005        // leap year, we'll just always accept up to 29 days for February.
3006        if ((day < 1) || (day > 29))
3007        {
3008          throw new ParseException(
3009               ERR_RFC_3339_TIME_INVALID_DAY_FOR_MONTH.get(timestamp, day,
3010                    month),
3011               8);
3012        }
3013        break;
3014
3015      default:
3016        throw new ParseException(
3017             ERR_RFC_3339_TIME_INVALID_MONTH.get(timestamp, month), 5);
3018    }
3019
3020
3021    // Make sure that the hour, minute, and second values are acceptable.  Note
3022    // that while ISO 8601 permits a value of 24 for the hour, RFC 3339 only
3023    // permits hour values between 0 and 23.  Also note that some minutes can
3024    // have up to 61 seconds for leap seconds, so we'll always account for that.
3025    if ((hour < 0) || (hour > 23))
3026    {
3027      throw new ParseException(
3028           ERR_RFC_3339_TIME_INVALID_HOUR.get(timestamp, hour), 11);
3029    }
3030
3031    if ((minute < 0) || (minute > 59))
3032    {
3033      throw new ParseException(
3034           ERR_RFC_3339_TIME_INVALID_MINUTE.get(timestamp, minute), 14);
3035    }
3036
3037    if ((second < 0) || (second > 60))
3038    {
3039      throw new ParseException(
3040           ERR_RFC_3339_TIME_INVALID_SECOND.get(timestamp, second), 17);
3041    }
3042
3043
3044    // See if there is a sub-second portion.  If so, then there will be a
3045    // period at position 19 followed by at least one digit.  This
3046    // implementation will only support timestamps with no more than three
3047    // sub-second digits.
3048    int milliseconds = 0;
3049    int timeZoneStartPos = -1;
3050    if (timestamp.charAt(19) == '.')
3051    {
3052      int numDigits = 0;
3053      final StringBuilder subSecondString = new StringBuilder(3);
3054      for (int pos=20; pos < timestamp.length(); pos++)
3055      {
3056        final char c = timestamp.charAt(pos);
3057        switch (c)
3058        {
3059          case '0':
3060            numDigits++;
3061            if (subSecondString.length() > 0)
3062            {
3063              // Only add a zero if it's not the first digit.
3064              subSecondString.append(c);
3065            }
3066            break;
3067          case '1':
3068          case '2':
3069          case '3':
3070          case '4':
3071          case '5':
3072          case '6':
3073          case '7':
3074          case '8':
3075          case '9':
3076            numDigits++;
3077            subSecondString.append(c);
3078            break;
3079          case 'Z':
3080          case '+':
3081          case '-':
3082            timeZoneStartPos = pos;
3083            break;
3084          default:
3085            throw new ParseException(
3086                 ERR_RFC_3339_TIME_INVALID_SUB_SECOND_CHAR.get(timestamp, c,
3087                      pos),
3088                 pos);
3089        }
3090
3091        if (timeZoneStartPos > 0)
3092        {
3093          break;
3094        }
3095
3096        if (numDigits > 3)
3097        {
3098          throw new ParseException(
3099               ERR_RFC_3339_TIME_TOO_MANY_SUB_SECOND_DIGITS.get(timestamp),
3100               20);
3101        }
3102      }
3103
3104      if (timeZoneStartPos < 0)
3105      {
3106        throw new ParseException(
3107             ERR_RFC_3339_TIME_MISSING_TIME_ZONE_AFTER_SUB_SECOND.get(
3108                  timestamp),
3109             (timestamp.length() - 1));
3110      }
3111
3112      if (numDigits == 0)
3113      {
3114        throw new ParseException(
3115             ERR_RFC_3339_TIME_NO_SUB_SECOND_DIGITS.get(timestamp), 19);
3116      }
3117
3118      if (subSecondString.length() == 0)
3119      {
3120        // This is possible if the sub-second portion is all zeroes.
3121        subSecondString.append('0');
3122      }
3123
3124      milliseconds = Integer.parseInt(subSecondString.toString());
3125      if (numDigits == 1)
3126      {
3127        milliseconds *= 100;
3128      }
3129      else if (numDigits == 2)
3130      {
3131        milliseconds *= 10;
3132      }
3133    }
3134    else
3135    {
3136      timeZoneStartPos = 19;
3137    }
3138
3139
3140    // The remainder of the timestamp should be the time zone.
3141    final TimeZone timeZone;
3142    if (timestamp.substring(timeZoneStartPos).equals("Z"))
3143    {
3144      // This is shorthand for the UTC time zone.
3145      timeZone = UTC_TIME_ZONE;
3146    }
3147    else
3148    {
3149      // This is an offset from UTC, which should be in the form "+HH:MM" or
3150      // "-HH:MM".  Make sure it has the expected length.
3151      if ((timestamp.length() - timeZoneStartPos) != 6)
3152      {
3153        throw new ParseException(
3154             ERR_RFC_3339_TIME_INVALID_TZ.get(timestamp), timeZoneStartPos);
3155      }
3156
3157      // Make sure it starts with "+" or "-".
3158      final int firstChar = timestamp.charAt(timeZoneStartPos);
3159      if ((firstChar != '+') && (firstChar != '-'))
3160      {
3161        throw new ParseException(
3162             ERR_RFC_3339_TIME_INVALID_TZ.get(timestamp), timeZoneStartPos);
3163      }
3164
3165
3166      // Make sure the hour offset is valid.
3167      final int timeZoneHourOffset =
3168           parseRFC3339Number(timestamp, (timeZoneStartPos+1), 2);
3169      if ((timeZoneHourOffset < 0) || (timeZoneHourOffset > 23))
3170      {
3171        throw new ParseException(
3172             ERR_RFC_3339_TIME_INVALID_TZ.get(timestamp), timeZoneStartPos);
3173      }
3174
3175
3176      // Make sure there is a colon between the hour and the minute portions of
3177      // the offset.
3178      if (timestamp.charAt(timeZoneStartPos+3) != ':')
3179      {
3180        throw new ParseException(
3181             ERR_RFC_3339_TIME_INVALID_TZ.get(timestamp), timeZoneStartPos);
3182      }
3183
3184      final int timeZoneMinuteOffset =
3185           parseRFC3339Number(timestamp, (timeZoneStartPos+4), 2);
3186      if ((timeZoneMinuteOffset < 0) || (timeZoneMinuteOffset > 59))
3187      {
3188        throw new ParseException(
3189             ERR_RFC_3339_TIME_INVALID_TZ.get(timestamp), timeZoneStartPos);
3190      }
3191
3192      timeZone = TimeZone.getTimeZone(
3193           "GMT" + timestamp.substring(timeZoneStartPos));
3194    }
3195
3196
3197    // Put everything together to construct the appropriate date.
3198    final GregorianCalendar calendar =
3199         new GregorianCalendar(year,
3200              (month-1), // NOTE:  Calendar stupidly uses zero-indexed months.
3201              day, hour, minute, second);
3202    calendar.set(GregorianCalendar.MILLISECOND, milliseconds);
3203    calendar.setTimeZone(timeZone);
3204    return calendar.getTime();
3205  }
3206
3207
3208
3209  /**
3210   * Ensures that the provided timestamp string has the expected character at
3211   * the specified position.
3212   *
3213   * @param  timestamp     The timestamp to examine.
3214   *                       It must not be {@code null}.
3215   * @param  pos           The position of the character to examine.
3216   * @param  expectedChar  The character expected at the specified position.
3217   *
3218   * @throws  ParseException  If the provided timestamp does not have the
3219   * expected
3220   */
3221  private static void validateRFC3339TimestampSeparatorCharacter(
3222                           @NotNull final String timestamp, final int pos,
3223                           final char expectedChar)
3224          throws ParseException
3225  {
3226    if (timestamp.charAt(pos) != expectedChar)
3227    {
3228      throw new ParseException(
3229           ERR_RFC_3339_INVALID_SEPARATOR.get(timestamp, timestamp.charAt(pos),
3230                pos, expectedChar),
3231           pos);
3232    }
3233  }
3234
3235
3236
3237  /**
3238   * Parses the number at the specified location in the timestamp.
3239   *
3240   * @param  timestamp  The timestamp to examine.  It must not be {@code null}.
3241   * @param  pos        The position at which to begin parsing the number.
3242   * @param  numDigits  The number of digits in the number.
3243   *
3244   * @return  The number parsed from the provided timestamp.
3245   *
3246   * @throws  ParseException  If a problem is encountered while trying to parse
3247   *                          the number from the timestamp.
3248   */
3249  private static int parseRFC3339Number(@NotNull final String timestamp,
3250                                        final int pos, final int numDigits)
3251          throws ParseException
3252  {
3253    int value = 0;
3254    for (int i=0; i < numDigits; i++)
3255    {
3256      value *= 10;
3257      switch (timestamp.charAt(pos+i))
3258      {
3259        case '0':
3260          break;
3261        case '1':
3262          value += 1;
3263          break;
3264        case '2':
3265          value += 2;
3266          break;
3267        case '3':
3268          value += 3;
3269          break;
3270        case '4':
3271          value += 4;
3272          break;
3273        case '5':
3274          value += 5;
3275          break;
3276        case '6':
3277          value += 6;
3278          break;
3279        case '7':
3280          value += 7;
3281          break;
3282        case '8':
3283          value += 8;
3284          break;
3285        case '9':
3286          value += 9;
3287          break;
3288        default:
3289          throw new ParseException(
3290               ERR_RFC_3339_INVALID_DIGIT.get(timestamp,
3291                    timestamp.charAt(pos+i), (pos+i)),
3292               (pos+i));
3293      }
3294    }
3295
3296    return value;
3297  }
3298
3299
3300
3301  /**
3302   * Trims only leading spaces from the provided string, leaving any trailing
3303   * spaces intact.
3304   *
3305   * @param  s  The string to be processed.  It must not be {@code null}.
3306   *
3307   * @return  The original string if no trimming was required, or a new string
3308   *          without leading spaces if the provided string had one or more.  It
3309   *          may be an empty string if the provided string was an empty string
3310   *          or contained only spaces.
3311   */
3312  @NotNull()
3313  public static String trimLeading(@NotNull final String s)
3314  {
3315    Validator.ensureNotNull(s);
3316
3317    int nonSpacePos = 0;
3318    final int length = s.length();
3319    while ((nonSpacePos < length) && (s.charAt(nonSpacePos) == ' '))
3320    {
3321      nonSpacePos++;
3322    }
3323
3324    if (nonSpacePos == 0)
3325    {
3326      // There were no leading spaces.
3327      return s;
3328    }
3329    else if (nonSpacePos >= length)
3330    {
3331      // There were no non-space characters.
3332      return "";
3333    }
3334    else
3335    {
3336      // There were leading spaces, so return the string without them.
3337      return s.substring(nonSpacePos, length);
3338    }
3339  }
3340
3341
3342
3343  /**
3344   * Trims only trailing spaces from the provided string, leaving any leading
3345   * spaces intact.
3346   *
3347   * @param  s  The string to be processed.  It must not be {@code null}.
3348   *
3349   * @return  The original string if no trimming was required, or a new string
3350   *          without trailing spaces if the provided string had one or more.
3351   *          It may be an empty string if the provided string was an empty
3352   *          string or contained only spaces.
3353   */
3354  @NotNull()
3355  public static String trimTrailing(@NotNull final String s)
3356  {
3357    Validator.ensureNotNull(s);
3358
3359    final int lastPos = s.length() - 1;
3360    int nonSpacePos = lastPos;
3361    while ((nonSpacePos >= 0) && (s.charAt(nonSpacePos) == ' '))
3362    {
3363      nonSpacePos--;
3364    }
3365
3366    if (nonSpacePos < 0)
3367    {
3368      // There were no non-space characters.
3369      return "";
3370    }
3371    else if (nonSpacePos == lastPos)
3372    {
3373      // There were no trailing spaces.
3374      return s;
3375    }
3376    else
3377    {
3378      // There were trailing spaces, so return the string without them.
3379      return s.substring(0, (nonSpacePos+1));
3380    }
3381  }
3382
3383
3384
3385  /**
3386   * Wraps the contents of the specified line using the given width.  It will
3387   * attempt to wrap at spaces to preserve words, but if that is not possible
3388   * (because a single "word" is longer than the maximum width), then it will
3389   * wrap in the middle of the word at the specified maximum width.
3390   *
3391   * @param  line      The line to be wrapped.  It must not be {@code null}.
3392   * @param  maxWidth  The maximum width for lines in the resulting list.  A
3393   *                   value less than or equal to zero will cause no wrapping
3394   *                   to be performed.
3395   *
3396   * @return  A list of the wrapped lines.  It may be empty if the provided line
3397   *          contained only spaces.
3398   */
3399  @NotNull()
3400  public static List<String> wrapLine(@NotNull final String line,
3401                                      final int maxWidth)
3402  {
3403    return wrapLine(line, maxWidth, maxWidth);
3404  }
3405
3406
3407
3408  /**
3409   * Wraps the contents of the specified line using the given width.  It will
3410   * attempt to wrap at spaces to preserve words, but if that is not possible
3411   * (because a single "word" is longer than the maximum width), then it will
3412   * wrap in the middle of the word at the specified maximum width.
3413   *
3414   * @param  line                    The line to be wrapped.  It must not be
3415   *                                 {@code null}.
3416   * @param  maxFirstLineWidth       The maximum length for the first line in
3417   *                                 the resulting list.  A value less than or
3418   *                                 equal to zero will cause no wrapping to be
3419   *                                 performed.
3420   * @param  maxSubsequentLineWidth  The maximum length for all lines except the
3421   *                                 first line.  This must be greater than zero
3422   *                                 unless {@code maxFirstLineWidth} is less
3423   *                                 than or equal to zero.
3424   *
3425   * @return  A list of the wrapped lines.  It may be empty if the provided line
3426   *          contained only spaces.
3427   */
3428  @NotNull()
3429  public static List<String> wrapLine(@NotNull final String line,
3430                                      final int maxFirstLineWidth,
3431                                      final int maxSubsequentLineWidth)
3432  {
3433    if (maxFirstLineWidth > 0)
3434    {
3435      Validator.ensureTrue(maxSubsequentLineWidth > 0);
3436    }
3437
3438    // See if the provided string already contains line breaks.  If so, then
3439    // treat it as multiple lines rather than a single line.
3440    final int breakPos = line.indexOf('\n');
3441    if (breakPos >= 0)
3442    {
3443      final ArrayList<String> lineList = new ArrayList<>(10);
3444      final StringTokenizer tokenizer = new StringTokenizer(line, "\r\n");
3445      while (tokenizer.hasMoreTokens())
3446      {
3447        lineList.addAll(wrapLine(tokenizer.nextToken(), maxFirstLineWidth,
3448             maxSubsequentLineWidth));
3449      }
3450
3451      return lineList;
3452    }
3453
3454    final int length = line.length();
3455    if ((maxFirstLineWidth <= 0) || (length < maxFirstLineWidth))
3456    {
3457      return Collections.singletonList(line);
3458    }
3459
3460
3461    int wrapPos = maxFirstLineWidth;
3462    int lastWrapPos = 0;
3463    final ArrayList<String> lineList = new ArrayList<>(5);
3464    while (true)
3465    {
3466      final int spacePos = line.lastIndexOf(' ', wrapPos);
3467      if (spacePos > lastWrapPos)
3468      {
3469        // We found a space in an acceptable location, so use it after trimming
3470        // any trailing spaces.
3471        final String s = trimTrailing(line.substring(lastWrapPos, spacePos));
3472
3473        // Don't bother adding the line if it contained only spaces.
3474        if (! s.isEmpty())
3475        {
3476          lineList.add(s);
3477        }
3478
3479        wrapPos = spacePos;
3480      }
3481      else
3482      {
3483        // We didn't find any spaces, so we'll have to insert a hard break at
3484        // the specified wrap column.
3485        lineList.add(line.substring(lastWrapPos, wrapPos));
3486      }
3487
3488      // Skip over any spaces before the next non-space character.
3489      while ((wrapPos < length) && (line.charAt(wrapPos) == ' '))
3490      {
3491        wrapPos++;
3492      }
3493
3494      lastWrapPos = wrapPos;
3495      wrapPos += maxSubsequentLineWidth;
3496      if (wrapPos >= length)
3497      {
3498        // The last fragment can fit on the line, so we can handle that now and
3499        // break.
3500        if (lastWrapPos >= length)
3501        {
3502          break;
3503        }
3504        else
3505        {
3506          final String s = line.substring(lastWrapPos);
3507          lineList.add(s);
3508          break;
3509        }
3510      }
3511    }
3512
3513    return lineList;
3514  }
3515
3516
3517
3518  /**
3519   * This method returns a form of the provided argument that is safe to
3520   * use on the command line for the local platform. This method is provided as
3521   * a convenience wrapper around {@link ExampleCommandLineArgument}.  Calling
3522   * this method is equivalent to:
3523   *
3524   * <PRE>
3525   *  return ExampleCommandLineArgument.getCleanArgument(s).getLocalForm();
3526   * </PRE>
3527   *
3528   * For getting direct access to command line arguments that are safe to
3529   * use on other platforms, call
3530   * {@link ExampleCommandLineArgument#getCleanArgument}.
3531   *
3532   * @param  s  The string to be processed.  It must not be {@code null}.
3533   *
3534   * @return  A cleaned version of the provided string in a form that will allow
3535   *          it to be displayed as the value of a command-line argument on.
3536   */
3537  @NotNull()
3538  public static String cleanExampleCommandLineArgument(@NotNull final String s)
3539  {
3540    return ExampleCommandLineArgument.getCleanArgument(s).getLocalForm();
3541  }
3542
3543
3544
3545  /**
3546   * Retrieves a single string which is a concatenation of all of the provided
3547   * strings.
3548   *
3549   * @param  a  The array of strings to concatenate.  It must not be
3550   *            {@code null} but may be empty.
3551   *
3552   * @return  A string containing a concatenation of all of the strings in the
3553   *          provided array.
3554   */
3555  @NotNull()
3556  public static String concatenateStrings(@NotNull final String... a)
3557  {
3558    return concatenateStrings(null, null, "  ", null, null, a);
3559  }
3560
3561
3562
3563  /**
3564   * Retrieves a single string which is a concatenation of all of the provided
3565   * strings.
3566   *
3567   * @param  l  The list of strings to concatenate.  It must not be
3568   *            {@code null} but may be empty.
3569   *
3570   * @return  A string containing a concatenation of all of the strings in the
3571   *          provided list.
3572   */
3573  @NotNull()
3574  public static String concatenateStrings(@NotNull final List<String> l)
3575  {
3576    return concatenateStrings(null, null, "  ", null, null, l);
3577  }
3578
3579
3580
3581  /**
3582   * Retrieves a single string which is a concatenation of all of the provided
3583   * strings.
3584   *
3585   * @param  beforeList       A string that should be placed at the beginning of
3586   *                          the list.  It may be {@code null} or empty if
3587   *                          nothing should be placed at the beginning of the
3588   *                          list.
3589   * @param  beforeElement    A string that should be placed before each element
3590   *                          in the list.  It may be {@code null} or empty if
3591   *                          nothing should be placed before each element.
3592   * @param  betweenElements  The separator that should be placed between
3593   *                          elements in the list.  It may be {@code null} or
3594   *                          empty if no separator should be placed between
3595   *                          elements.
3596   * @param  afterElement     A string that should be placed after each element
3597   *                          in the list.  It may be {@code null} or empty if
3598   *                          nothing should be placed after each element.
3599   * @param  afterList        A string that should be placed at the end of the
3600   *                          list.  It may be {@code null} or empty if nothing
3601   *                          should be placed at the end of the list.
3602   * @param  a                The array of strings to concatenate.  It must not
3603   *                          be {@code null} but may be empty.
3604   *
3605   * @return  A string containing a concatenation of all of the strings in the
3606   *          provided list.
3607   */
3608  @NotNull()
3609  public static String concatenateStrings(@Nullable final String beforeList,
3610                            @Nullable final String beforeElement,
3611                            @Nullable final String betweenElements,
3612                            @Nullable final String afterElement,
3613                            @Nullable final String afterList,
3614                            @NotNull final String... a)
3615  {
3616    return concatenateStrings(beforeList, beforeElement, betweenElements,
3617         afterElement, afterList, Arrays.asList(a));
3618  }
3619
3620
3621
3622  /**
3623   * Retrieves a single string which is a concatenation of all of the provided
3624   * strings.
3625   *
3626   * @param  beforeList       A string that should be placed at the beginning of
3627   *                          the list.  It may be {@code null} or empty if
3628   *                          nothing should be placed at the beginning of the
3629   *                          list.
3630   * @param  beforeElement    A string that should be placed before each element
3631   *                          in the list.  It may be {@code null} or empty if
3632   *                          nothing should be placed before each element.
3633   * @param  betweenElements  The separator that should be placed between
3634   *                          elements in the list.  It may be {@code null} or
3635   *                          empty if no separator should be placed between
3636   *                          elements.
3637   * @param  afterElement     A string that should be placed after each element
3638   *                          in the list.  It may be {@code null} or empty if
3639   *                          nothing should be placed after each element.
3640   * @param  afterList        A string that should be placed at the end of the
3641   *                          list.  It may be {@code null} or empty if nothing
3642   *                          should be placed at the end of the list.
3643   * @param  l                The list of strings to concatenate.  It must not
3644   *                          be {@code null} but may be empty.
3645   *
3646   * @return  A string containing a concatenation of all of the strings in the
3647   *          provided list.
3648   */
3649  @NotNull()
3650  public static String concatenateStrings(@Nullable final String beforeList,
3651                            @Nullable final String beforeElement,
3652                            @Nullable final String betweenElements,
3653                            @Nullable final String afterElement,
3654                            @Nullable final String afterList,
3655                            @NotNull final List<String> l)
3656  {
3657    Validator.ensureNotNull(l);
3658
3659    final StringBuilder buffer = new StringBuilder();
3660
3661    if (beforeList != null)
3662    {
3663      buffer.append(beforeList);
3664    }
3665
3666    final Iterator<String> iterator = l.iterator();
3667    while (iterator.hasNext())
3668    {
3669      if (beforeElement != null)
3670      {
3671        buffer.append(beforeElement);
3672      }
3673
3674      buffer.append(iterator.next());
3675
3676      if (afterElement != null)
3677      {
3678        buffer.append(afterElement);
3679      }
3680
3681      if ((betweenElements != null) && iterator.hasNext())
3682      {
3683        buffer.append(betweenElements);
3684      }
3685    }
3686
3687    if (afterList != null)
3688    {
3689      buffer.append(afterList);
3690    }
3691
3692    return buffer.toString();
3693  }
3694
3695
3696
3697  /**
3698   * Converts a duration in seconds to a string with a human-readable duration
3699   * which may include days, hours, minutes, and seconds, to the extent that
3700   * they are needed.
3701   *
3702   * @param  s  The number of seconds to be represented.
3703   *
3704   * @return  A string containing a human-readable representation of the
3705   *          provided time.
3706   */
3707  @NotNull()
3708  public static String secondsToHumanReadableDuration(final long s)
3709  {
3710    return millisToHumanReadableDuration(s * 1000L);
3711  }
3712
3713
3714
3715  /**
3716   * Converts a duration in seconds to a string with a human-readable duration
3717   * which may include days, hours, minutes, and seconds, to the extent that
3718   * they are needed.
3719   *
3720   * @param  m  The number of milliseconds to be represented.
3721   *
3722   * @return  A string containing a human-readable representation of the
3723   *          provided time.
3724   */
3725  @NotNull()
3726  public static String millisToHumanReadableDuration(final long m)
3727  {
3728    final StringBuilder buffer = new StringBuilder();
3729    long numMillis = m;
3730
3731    final long numDays = numMillis / 86_400_000L;
3732    if (numDays > 0)
3733    {
3734      numMillis -= (numDays * 86_400_000L);
3735      if (numDays == 1)
3736      {
3737        buffer.append(INFO_NUM_DAYS_SINGULAR.get(numDays));
3738      }
3739      else
3740      {
3741        buffer.append(INFO_NUM_DAYS_PLURAL.get(numDays));
3742      }
3743    }
3744
3745    final long numHours = numMillis / 3_600_000L;
3746    if (numHours > 0)
3747    {
3748      numMillis -= (numHours * 3_600_000L);
3749      if (buffer.length() > 0)
3750      {
3751        buffer.append(", ");
3752      }
3753
3754      if (numHours == 1)
3755      {
3756        buffer.append(INFO_NUM_HOURS_SINGULAR.get(numHours));
3757      }
3758      else
3759      {
3760        buffer.append(INFO_NUM_HOURS_PLURAL.get(numHours));
3761      }
3762    }
3763
3764    final long numMinutes = numMillis / 60_000L;
3765    if (numMinutes > 0)
3766    {
3767      numMillis -= (numMinutes * 60_000L);
3768      if (buffer.length() > 0)
3769      {
3770        buffer.append(", ");
3771      }
3772
3773      if (numMinutes == 1)
3774      {
3775        buffer.append(INFO_NUM_MINUTES_SINGULAR.get(numMinutes));
3776      }
3777      else
3778      {
3779        buffer.append(INFO_NUM_MINUTES_PLURAL.get(numMinutes));
3780      }
3781    }
3782
3783    if (numMillis == 1000)
3784    {
3785      if (buffer.length() > 0)
3786      {
3787        buffer.append(", ");
3788      }
3789
3790      buffer.append(INFO_NUM_SECONDS_SINGULAR.get(1));
3791    }
3792    else if ((numMillis > 0) || (buffer.length() == 0))
3793    {
3794      if (buffer.length() > 0)
3795      {
3796        buffer.append(", ");
3797      }
3798
3799      final long numSeconds = numMillis / 1000L;
3800      numMillis -= (numSeconds * 1000L);
3801      if ((numMillis % 1000L) != 0L)
3802      {
3803        final double numSecondsDouble = numSeconds + (numMillis / 1000.0);
3804        final DecimalFormat decimalFormat = new DecimalFormat("0.000");
3805        buffer.append(INFO_NUM_SECONDS_WITH_DECIMAL.get(
3806             decimalFormat.format(numSecondsDouble)));
3807      }
3808      else
3809      {
3810        buffer.append(INFO_NUM_SECONDS_PLURAL.get(numSeconds));
3811      }
3812    }
3813
3814    return buffer.toString();
3815  }
3816
3817
3818
3819  /**
3820   * Converts the provided number of nanoseconds to milliseconds.
3821   *
3822   * @param  nanos  The number of nanoseconds to convert to milliseconds.
3823   *
3824   * @return  The number of milliseconds that most closely corresponds to the
3825   *          specified number of nanoseconds.
3826   */
3827  public static long nanosToMillis(final long nanos)
3828  {
3829    return Math.max(0L, Math.round(nanos / 1_000_000.0d));
3830  }
3831
3832
3833
3834  /**
3835   * Converts the provided number of milliseconds to nanoseconds.
3836   *
3837   * @param  millis  The number of milliseconds to convert to nanoseconds.
3838   *
3839   * @return  The number of nanoseconds that most closely corresponds to the
3840   *          specified number of milliseconds.
3841   */
3842  public static long millisToNanos(final long millis)
3843  {
3844    return Math.max(0L, (millis * 1_000_000L));
3845  }
3846
3847
3848
3849  /**
3850   * Indicates whether the provided string is a valid numeric OID.  A numeric
3851   * OID must start and end with a digit, must have at least on period, must
3852   * contain only digits and periods, and must not have two consecutive periods.
3853   *
3854   * @param  s  The string to examine.  It must not be {@code null}.
3855   *
3856   * @return  {@code true} if the provided string is a valid numeric OID, or
3857   *          {@code false} if not.
3858   */
3859  public static boolean isNumericOID(@NotNull final String s)
3860  {
3861    boolean digitRequired = true;
3862    boolean periodFound   = false;
3863    for (final char c : s.toCharArray())
3864    {
3865      switch (c)
3866      {
3867        case '0':
3868        case '1':
3869        case '2':
3870        case '3':
3871        case '4':
3872        case '5':
3873        case '6':
3874        case '7':
3875        case '8':
3876        case '9':
3877          digitRequired = false;
3878          break;
3879
3880        case '.':
3881          if (digitRequired)
3882          {
3883            return false;
3884          }
3885          else
3886          {
3887            digitRequired = true;
3888          }
3889          periodFound = true;
3890          break;
3891
3892        default:
3893          return false;
3894      }
3895
3896    }
3897
3898    return (periodFound && (! digitRequired));
3899  }
3900
3901
3902
3903  /**
3904   * Capitalizes the provided string.  The first character will be converted to
3905   * uppercase, and the rest of the string will be left unaltered.
3906   *
3907   * @param  s  The string to be capitalized.
3908   *
3909   * @return  A capitalized version of the provided string, or {@code null} if
3910   *          the provided string was {@code null}.
3911   */
3912  @Nullable()
3913  public static String capitalize(@Nullable final String s)
3914  {
3915    return capitalize(s, false);
3916  }
3917
3918
3919
3920  /**
3921   * Capitalizes the provided string.  The first character of the string (or
3922   * optionally the first character of each word in the string)
3923   *
3924   * @param  s         The string to be capitalized.
3925   * @param  allWords  Indicates whether to capitalize all words in the string,
3926   *                   or only the first word.
3927   *
3928   * @return  A capitalized version of the provided string, or {@code null} if
3929   *          the provided string was {@code null}.
3930   */
3931  @Nullable()
3932  public static String capitalize(@Nullable final String s,
3933                                  final boolean allWords)
3934  {
3935    if (s == null)
3936    {
3937      return null;
3938    }
3939
3940    switch (s.length())
3941    {
3942      case 0:
3943        return s;
3944
3945      case 1:
3946        return s.toUpperCase();
3947
3948      default:
3949        boolean capitalize = true;
3950        final char[] chars = s.toCharArray();
3951        final StringBuilder buffer = new StringBuilder(chars.length);
3952        for (final char c : chars)
3953        {
3954          // Whitespace and punctuation will be considered word breaks.
3955          if (Character.isWhitespace(c) ||
3956              (((c >= '!') && (c <= '.')) ||
3957               ((c >= ':') && (c <= '@')) ||
3958               ((c >= '[') && (c <= '`')) ||
3959               ((c >= '{') && (c <= '~'))))
3960          {
3961            buffer.append(c);
3962            capitalize |= allWords;
3963          }
3964          else if (capitalize)
3965          {
3966            buffer.append(Character.toUpperCase(c));
3967            capitalize = false;
3968          }
3969          else
3970          {
3971            buffer.append(c);
3972          }
3973        }
3974        return buffer.toString();
3975    }
3976  }
3977
3978
3979
3980  /**
3981   * Encodes the provided UUID to a byte array containing its 128-bit
3982   * representation.
3983   *
3984   * @param  uuid  The UUID to be encoded.  It must not be {@code null}.
3985   *
3986   * @return  The byte array containing the 128-bit encoded UUID.
3987   */
3988  @NotNull()
3989  public static byte[] encodeUUID(@NotNull final UUID uuid)
3990  {
3991    final byte[] b = new byte[16];
3992
3993    final long mostSignificantBits  = uuid.getMostSignificantBits();
3994    b[0]  = (byte) ((mostSignificantBits >> 56) & 0xFF);
3995    b[1]  = (byte) ((mostSignificantBits >> 48) & 0xFF);
3996    b[2]  = (byte) ((mostSignificantBits >> 40) & 0xFF);
3997    b[3]  = (byte) ((mostSignificantBits >> 32) & 0xFF);
3998    b[4]  = (byte) ((mostSignificantBits >> 24) & 0xFF);
3999    b[5]  = (byte) ((mostSignificantBits >> 16) & 0xFF);
4000    b[6]  = (byte) ((mostSignificantBits >> 8) & 0xFF);
4001    b[7]  = (byte) (mostSignificantBits & 0xFF);
4002
4003    final long leastSignificantBits = uuid.getLeastSignificantBits();
4004    b[8]  = (byte) ((leastSignificantBits >> 56) & 0xFF);
4005    b[9]  = (byte) ((leastSignificantBits >> 48) & 0xFF);
4006    b[10] = (byte) ((leastSignificantBits >> 40) & 0xFF);
4007    b[11] = (byte) ((leastSignificantBits >> 32) & 0xFF);
4008    b[12] = (byte) ((leastSignificantBits >> 24) & 0xFF);
4009    b[13] = (byte) ((leastSignificantBits >> 16) & 0xFF);
4010    b[14] = (byte) ((leastSignificantBits >> 8) & 0xFF);
4011    b[15] = (byte) (leastSignificantBits & 0xFF);
4012
4013    return b;
4014  }
4015
4016
4017
4018  /**
4019   * Decodes the value of the provided byte array as a Java UUID.
4020   *
4021   * @param  b  The byte array to be decoded as a UUID.  It must not be
4022   *            {@code null}.
4023   *
4024   * @return  The decoded UUID.
4025   *
4026   * @throws  ParseException  If the provided byte array cannot be parsed as a
4027   *                         UUID.
4028   */
4029  @NotNull()
4030  public static UUID decodeUUID(@NotNull final byte[] b)
4031         throws ParseException
4032  {
4033    if (b.length != 16)
4034    {
4035      throw new ParseException(ERR_DECODE_UUID_INVALID_LENGTH.get(toHex(b)), 0);
4036    }
4037
4038    long mostSignificantBits = 0L;
4039    for (int i=0; i < 8; i++)
4040    {
4041      mostSignificantBits = (mostSignificantBits << 8) | (b[i] & 0xFF);
4042    }
4043
4044    long leastSignificantBits = 0L;
4045    for (int i=8; i < 16; i++)
4046    {
4047      leastSignificantBits = (leastSignificantBits << 8) | (b[i] & 0xFF);
4048    }
4049
4050    return new UUID(mostSignificantBits, leastSignificantBits);
4051  }
4052
4053
4054
4055  /**
4056   * Returns {@code true} if and only if the current process is running on
4057   * a Windows-based operating system.
4058   *
4059   * @return  {@code true} if the current process is running on a Windows-based
4060   *          operating system and {@code false} otherwise.
4061   */
4062  public static boolean isWindows()
4063  {
4064    final String osName = toLowerCase(getSystemProperty("os.name"));
4065    return ((osName != null) && osName.contains("windows"));
4066  }
4067
4068
4069
4070  /**
4071   * Retrieves the string that should be appended to the end of all but the last
4072   * line of a multi-line command to indicate that the command continues onto
4073   * the next line.
4074   * <BR><BR>
4075   * This will be the caret (also called a circumflex accent) character on
4076   * Windows systems, and a backslash (also called a reverse solidus) character
4077   * on Linux and UNIX-based systems.
4078   * <BR><BR>
4079   * The string value that is returned will not include a space, but it should
4080   * generally be preceded by one or more space to separate it from the previous
4081   * component on the command line.
4082   *
4083   * @return  The string that should be appended (generally after one or more
4084   *          spaces to separate it from the previous component) to the end of
4085   *          all but the last line of a multi-line command to indicate that the
4086   *          command continues onto the next line.
4087   */
4088  @NotNull()
4089  public static String getCommandLineContinuationString()
4090  {
4091    if (isWindows())
4092    {
4093      return "^";
4094    }
4095    else
4096    {
4097      return "\\";
4098    }
4099  }
4100
4101
4102
4103  /**
4104   * Attempts to parse the contents of the provided string to an argument list
4105   * (e.g., converts something like "--arg1 arg1value --arg2 --arg3 arg3value"
4106   * to a list of "--arg1", "arg1value", "--arg2", "--arg3", "arg3value").
4107   *
4108   * @param  s  The string to be converted to an argument list.
4109   *
4110   * @return  The parsed argument list.
4111   *
4112   * @throws  ParseException  If a problem is encountered while attempting to
4113   *                          parse the given string to an argument list.
4114   */
4115  @NotNull()
4116  public static List<String> toArgumentList(@Nullable final String s)
4117         throws ParseException
4118  {
4119    if ((s == null) || s.isEmpty())
4120    {
4121      return Collections.emptyList();
4122    }
4123
4124    int quoteStartPos = -1;
4125    boolean inEscape = false;
4126    final ArrayList<String> argList = new ArrayList<>(20);
4127    final StringBuilder currentArg = new StringBuilder();
4128    for (int i=0; i < s.length(); i++)
4129    {
4130      final char c = s.charAt(i);
4131      if (inEscape)
4132      {
4133        currentArg.append(c);
4134        inEscape = false;
4135        continue;
4136      }
4137
4138      if (c == '\\')
4139      {
4140        inEscape = true;
4141      }
4142      else if (c == '"')
4143      {
4144        if (quoteStartPos >= 0)
4145        {
4146          quoteStartPos = -1;
4147        }
4148        else
4149        {
4150          quoteStartPos = i;
4151        }
4152      }
4153      else if (c == ' ')
4154      {
4155        if (quoteStartPos >= 0)
4156        {
4157          currentArg.append(c);
4158        }
4159        else if (currentArg.length() > 0)
4160        {
4161          argList.add(currentArg.toString());
4162          currentArg.setLength(0);
4163        }
4164      }
4165      else
4166      {
4167        currentArg.append(c);
4168      }
4169    }
4170
4171    if (s.endsWith("\\") && (! s.endsWith("\\\\")))
4172    {
4173      throw new ParseException(ERR_ARG_STRING_DANGLING_BACKSLASH.get(),
4174           (s.length() - 1));
4175    }
4176
4177    if (quoteStartPos >= 0)
4178    {
4179      throw new ParseException(ERR_ARG_STRING_UNMATCHED_QUOTE.get(
4180           quoteStartPos), quoteStartPos);
4181    }
4182
4183    if (currentArg.length() > 0)
4184    {
4185      argList.add(currentArg.toString());
4186    }
4187
4188    return Collections.unmodifiableList(argList);
4189  }
4190
4191
4192
4193  /**
4194   * Retrieves an array containing the elements of the provided collection.
4195   *
4196   * @param  <T>         The type of element included in the provided
4197   *                     collection.
4198   * @param  collection  The collection to convert to an array.
4199   * @param  type        The type of element contained in the collection.
4200   *
4201   * @return  An array containing the elements of the provided list, or
4202   *          {@code null} if the provided list is {@code null}.
4203   */
4204  @Nullable()
4205  public static <T> T[] toArray(@Nullable final Collection<T> collection,
4206                                @NotNull final Class<T> type)
4207  {
4208    if (collection == null)
4209    {
4210      return null;
4211    }
4212
4213    @SuppressWarnings("unchecked")
4214    final T[] array = (T[]) Array.newInstance(type, collection.size());
4215
4216    return collection.toArray(array);
4217  }
4218
4219
4220
4221  /**
4222   * Creates a modifiable list with all of the items of the provided array in
4223   * the same order.  This method behaves much like {@code Arrays.asList},
4224   * except that if the provided array is {@code null}, then it will return a
4225   * {@code null} list rather than throwing an exception.
4226   *
4227   * @param  <T>  The type of item contained in the provided array.
4228   *
4229   * @param  array  The array of items to include in the list.
4230   *
4231   * @return  The list that was created, or {@code null} if the provided array
4232   *          was {@code null}.
4233   */
4234  @Nullable()
4235  public static <T> List<T> toList(@Nullable final T[] array)
4236  {
4237    if (array == null)
4238    {
4239      return null;
4240    }
4241
4242    final ArrayList<T> l = new ArrayList<>(array.length);
4243    l.addAll(Arrays.asList(array));
4244    return l;
4245  }
4246
4247
4248
4249  /**
4250   * Creates a modifiable list with all of the items of the provided array in
4251   * the same order.  This method behaves much like {@code Arrays.asList},
4252   * except that if the provided array is {@code null}, then it will return an
4253   * empty list rather than throwing an exception.
4254   *
4255   * @param  <T>  The type of item contained in the provided array.
4256   *
4257   * @param  array  The array of items to include in the list.
4258   *
4259   * @return  The list that was created, or an empty list if the provided array
4260   *          was {@code null}.
4261   */
4262  @NotNull()
4263  public static <T> List<T> toNonNullList(@Nullable final T[] array)
4264  {
4265    if (array == null)
4266    {
4267      return new ArrayList<>(0);
4268    }
4269
4270    final ArrayList<T> l = new ArrayList<>(array.length);
4271    l.addAll(Arrays.asList(array));
4272    return l;
4273  }
4274
4275
4276
4277  /**
4278   * Indicates whether both of the provided objects are {@code null} or both
4279   * are logically equal (using the {@code equals} method).
4280   *
4281   * @param  o1  The first object for which to make the determination.
4282   * @param  o2  The second object for which to make the determination.
4283   *
4284   * @return  {@code true} if both objects are {@code null} or both are
4285   *          logically equal, or {@code false} if only one of the objects is
4286   *          {@code null} or they are not logically equal.
4287   */
4288  public static boolean bothNullOrEqual(@Nullable final Object o1,
4289                                        @Nullable final Object o2)
4290  {
4291    if (o1 == null)
4292    {
4293      return (o2 == null);
4294    }
4295    else if (o2 == null)
4296    {
4297      return false;
4298    }
4299
4300    return o1.equals(o2);
4301  }
4302
4303
4304
4305  /**
4306   * Indicates whether both of the provided strings are {@code null} or both
4307   * are logically equal ignoring differences in capitalization (using the
4308   * {@code equalsIgnoreCase} method).
4309   *
4310   * @param  s1  The first string for which to make the determination.
4311   * @param  s2  The second string for which to make the determination.
4312   *
4313   * @return  {@code true} if both strings are {@code null} or both are
4314   *          logically equal ignoring differences in capitalization, or
4315   *          {@code false} if only one of the objects is {@code null} or they
4316   *          are not logically equal ignoring capitalization.
4317   */
4318  public static boolean bothNullOrEqualIgnoreCase(@Nullable final String s1,
4319                                                  @Nullable final String s2)
4320  {
4321    if (s1 == null)
4322    {
4323      return (s2 == null);
4324    }
4325    else if (s2 == null)
4326    {
4327      return false;
4328    }
4329
4330    return s1.equalsIgnoreCase(s2);
4331  }
4332
4333
4334
4335  /**
4336   * Indicates whether the provided string arrays have the same elements,
4337   * ignoring the order in which they appear and differences in capitalization.
4338   * It is assumed that neither array contains {@code null} strings, and that
4339   * no string appears more than once in each array.
4340   *
4341   * @param  a1  The first array for which to make the determination.
4342   * @param  a2  The second array for which to make the determination.
4343   *
4344   * @return  {@code true} if both arrays have the same set of strings, or
4345   *          {@code false} if not.
4346   */
4347  public static boolean stringsEqualIgnoreCaseOrderIndependent(
4348                             @Nullable final String[] a1,
4349                             @Nullable final String[] a2)
4350  {
4351    if (a1 == null)
4352    {
4353      return (a2 == null);
4354    }
4355    else if (a2 == null)
4356    {
4357      return false;
4358    }
4359
4360    if (a1.length != a2.length)
4361    {
4362      return false;
4363    }
4364
4365    if (a1.length == 1)
4366    {
4367      return (a1[0].equalsIgnoreCase(a2[0]));
4368    }
4369
4370    final HashSet<String> s1 = new HashSet<>(computeMapCapacity(a1.length));
4371    for (final String s : a1)
4372    {
4373      s1.add(toLowerCase(s));
4374    }
4375
4376    final HashSet<String> s2 = new HashSet<>(computeMapCapacity(a2.length));
4377    for (final String s : a2)
4378    {
4379      s2.add(toLowerCase(s));
4380    }
4381
4382    return s1.equals(s2);
4383  }
4384
4385
4386
4387  /**
4388   * Indicates whether the provided arrays have the same elements, ignoring the
4389   * order in which they appear.  It is assumed that neither array contains
4390   * {@code null} elements, and that no element appears more than once in each
4391   * array.
4392   *
4393   * @param  <T>  The type of element contained in the arrays.
4394   *
4395   * @param  a1  The first array for which to make the determination.
4396   * @param  a2  The second array for which to make the determination.
4397   *
4398   * @return  {@code true} if both arrays have the same set of elements, or
4399   *          {@code false} if not.
4400   */
4401  public static <T> boolean arraysEqualOrderIndependent(@Nullable final T[] a1,
4402                                                        @Nullable final T[] a2)
4403  {
4404    if (a1 == null)
4405    {
4406      return (a2 == null);
4407    }
4408    else if (a2 == null)
4409    {
4410      return false;
4411    }
4412
4413    if (a1.length != a2.length)
4414    {
4415      return false;
4416    }
4417
4418    if (a1.length == 1)
4419    {
4420      return (a1[0].equals(a2[0]));
4421    }
4422
4423    final HashSet<T> s1 = new HashSet<>(Arrays.asList(a1));
4424    final HashSet<T> s2 = new HashSet<>(Arrays.asList(a2));
4425    return s1.equals(s2);
4426  }
4427
4428
4429
4430  /**
4431   * Determines the number of bytes in a UTF-8 character that starts with the
4432   * given byte.
4433   *
4434   * @param  b  The byte for which to make the determination.
4435   *
4436   * @return  The number of bytes in a UTF-8 character that starts with the
4437   *          given byte, or -1 if it does not appear to be a valid first byte
4438   *          for a UTF-8 character.
4439   */
4440  public static int numBytesInUTF8CharacterWithFirstByte(final byte b)
4441  {
4442    if ((b & 0x7F) == b)
4443    {
4444      return 1;
4445    }
4446    else if ((b & 0xE0) == 0xC0)
4447    {
4448      return 2;
4449    }
4450    else if ((b & 0xF0) == 0xE0)
4451    {
4452      return 3;
4453    }
4454    else if ((b & 0xF8) == 0xF0)
4455    {
4456      return 4;
4457    }
4458    else
4459    {
4460      return -1;
4461    }
4462  }
4463
4464
4465
4466  /**
4467   * Indicates whether the provided attribute name should be considered a
4468   * sensitive attribute for the purposes of {@code toCode} methods.  If an
4469   * attribute is considered sensitive, then its values will be redacted in the
4470   * output of the {@code toCode} methods.
4471   *
4472   * @param  name  The name for which to make the determination.  It may or may
4473   *               not include attribute options.  It must not be {@code null}.
4474   *
4475   * @return  {@code true} if the specified attribute is one that should be
4476   *          considered sensitive for the
4477   */
4478  public static boolean isSensitiveToCodeAttribute(@NotNull final String name)
4479  {
4480    final String lowerBaseName = Attribute.getBaseName(name).toLowerCase();
4481    return TO_CODE_SENSITIVE_ATTRIBUTE_NAMES.contains(lowerBaseName);
4482  }
4483
4484
4485
4486  /**
4487   * Retrieves a set containing the base names (in all lowercase characters) of
4488   * any attributes that should be considered sensitive for the purposes of the
4489   * {@code toCode} methods.  By default, only the userPassword and
4490   * authPassword attributes and their respective OIDs will be included.
4491   *
4492   * @return  A set containing the base names (in all lowercase characters) of
4493   *          any attributes that should be considered sensitive for the
4494   *          purposes of the {@code toCode} methods.
4495   */
4496  @NotNull()
4497  public static Set<String> getSensitiveToCodeAttributeBaseNames()
4498  {
4499    return TO_CODE_SENSITIVE_ATTRIBUTE_NAMES;
4500  }
4501
4502
4503
4504  /**
4505   * Specifies the names of any attributes that should be considered sensitive
4506   * for the purposes of the {@code toCode} methods.
4507   *
4508   * @param  names  The names of any attributes that should be considered
4509   *                sensitive for the purposes of the {@code toCode} methods.
4510   *                It may be {@code null} or empty if no attributes should be
4511   *                considered sensitive.
4512   */
4513  public static void setSensitiveToCodeAttributes(
4514                          @Nullable final String... names)
4515  {
4516    setSensitiveToCodeAttributes(toList(names));
4517  }
4518
4519
4520
4521  /**
4522   * Specifies the names of any attributes that should be considered sensitive
4523   * for the purposes of the {@code toCode} methods.
4524   *
4525   * @param  names  The names of any attributes that should be considered
4526   *                sensitive for the purposes of the {@code toCode} methods.
4527   *                It may be {@code null} or empty if no attributes should be
4528   *                considered sensitive.
4529   */
4530  public static void setSensitiveToCodeAttributes(
4531                          @Nullable final Collection<String> names)
4532  {
4533    if ((names == null) || names.isEmpty())
4534    {
4535      TO_CODE_SENSITIVE_ATTRIBUTE_NAMES = Collections.emptySet();
4536    }
4537    else
4538    {
4539      final LinkedHashSet<String> nameSet = new LinkedHashSet<>(names.size());
4540      for (final String s : names)
4541      {
4542        nameSet.add(Attribute.getBaseName(s).toLowerCase());
4543      }
4544
4545      TO_CODE_SENSITIVE_ATTRIBUTE_NAMES = Collections.unmodifiableSet(nameSet);
4546    }
4547  }
4548
4549
4550
4551  /**
4552   * Creates a new {@code IOException} with a cause.  The constructor needed to
4553   * do this wasn't available until Java SE 6, so reflection is used to invoke
4554   * this constructor in versions of Java that provide it.  In Java SE 5, the
4555   * provided message will be augmented with information about the cause.
4556   *
4557   * @param  message  The message to use for the exception.  This may be
4558   *                  {@code null} if the message should be generated from the
4559   *                  provided cause.
4560   * @param  cause    The underlying cause for the exception.  It may be
4561   *                  {@code null} if the exception should have only a message.
4562   *
4563   * @return  The {@code IOException} object that was created.
4564   */
4565  @NotNull()
4566  public static IOException createIOExceptionWithCause(
4567                                 @Nullable final String message,
4568                                 @Nullable final Throwable cause)
4569  {
4570    if (cause == null)
4571    {
4572      return new IOException(message);
4573    }
4574    else if (message == null)
4575    {
4576      return new IOException(cause);
4577    }
4578    else
4579    {
4580      return new IOException(message, cause);
4581    }
4582  }
4583
4584
4585
4586  /**
4587   * Converts the provided string (which may include line breaks) into a list
4588   * containing the lines without the line breaks.
4589   *
4590   * @param  s  The string to convert into a list of its representative lines.
4591   *
4592   * @return  A list containing the lines that comprise the given string.
4593   */
4594  @NotNull()
4595  public static List<String> stringToLines(@Nullable final String s)
4596  {
4597    final ArrayList<String> l = new ArrayList<>(10);
4598
4599    if (s == null)
4600    {
4601      return l;
4602    }
4603
4604    final BufferedReader reader = new BufferedReader(new StringReader(s));
4605
4606    try
4607    {
4608      while (true)
4609      {
4610        try
4611        {
4612          final String line = reader.readLine();
4613          if (line == null)
4614          {
4615            return l;
4616          }
4617          else
4618          {
4619            l.add(line);
4620          }
4621        }
4622        catch (final Exception e)
4623        {
4624          Debug.debugException(e);
4625
4626          // This should never happen.  If it does, just return a list
4627          // containing a single item that is the original string.
4628          l.clear();
4629          l.add(s);
4630          return l;
4631        }
4632      }
4633    }
4634    finally
4635    {
4636      try
4637      {
4638        // This is technically not necessary in this case, but it's good form.
4639        reader.close();
4640      }
4641      catch (final Exception e)
4642      {
4643        Debug.debugException(e);
4644        // This should never happen, and there's nothing we need to do even if
4645        // it does.
4646      }
4647    }
4648  }
4649
4650
4651
4652  /**
4653   * Creates a string that is a concatenation of all of the provided lines, with
4654   * a line break (using the end-of-line sequence appropriate for the underlying
4655   * platform) after each line (including the last line).
4656   *
4657   * @param  lines  The lines to include in the string.
4658   *
4659   * @return  The string resulting from concatenating the provided lines with
4660   *          line breaks.
4661   */
4662  @NotNull()
4663  public static String linesToString(@Nullable final CharSequence... lines)
4664  {
4665    if (lines == null)
4666    {
4667      return "";
4668    }
4669
4670    return linesToString(Arrays.asList(lines));
4671  }
4672
4673
4674
4675  /**
4676   * Creates a string that is a concatenation of all of the provided lines, with
4677   * a line break (using the end-of-line sequence appropriate for the underlying
4678   * platform) after each line (including the last line).
4679   *
4680   * @param  lines  The lines to include in the string.
4681   *
4682   * @return  The string resulting from concatenating the provided lines with
4683   *          line breaks.
4684   */
4685  @NotNull()
4686  public static String linesToString(
4687                            @Nullable final List<? extends CharSequence> lines)
4688  {
4689    if (lines == null)
4690    {
4691      return "";
4692    }
4693
4694    final StringBuilder buffer = new StringBuilder();
4695    for (final CharSequence line : lines)
4696    {
4697      buffer.append(line);
4698      buffer.append(EOL);
4699    }
4700
4701    return buffer.toString();
4702  }
4703
4704
4705
4706  /**
4707   * Constructs a {@code File} object from the provided path.
4708   *
4709   * @param  baseDirectory  The base directory to use as the starting point.
4710   *                        It must not be {@code null} and is expected to
4711   *                        represent a directory.
4712   * @param  pathElements   An array of the elements that make up the remainder
4713   *                        of the path to the specified file, in order from
4714   *                        paths closest to the root of the filesystem to
4715   *                        furthest away (that is, the first element should
4716   *                        represent a file or directory immediately below the
4717   *                        base directory, the second is one level below that,
4718   *                        and so on).  It may be {@code null} or empty if the
4719   *                        base directory should be used.
4720   *
4721   * @return  The constructed {@code File} object.
4722   */
4723  @NotNull()
4724  public static File constructPath(@NotNull final File baseDirectory,
4725                                   @Nullable final String... pathElements)
4726  {
4727    Validator.ensureNotNull(baseDirectory);
4728
4729    File f = baseDirectory;
4730    if (pathElements != null)
4731    {
4732      for (final String pathElement : pathElements)
4733      {
4734        f = new File(f, pathElement);
4735      }
4736    }
4737
4738    return f;
4739  }
4740
4741
4742
4743  /**
4744   * Creates a byte array from the provided integer values.  All of the integer
4745   * values must be between 0x00 and 0xFF (0 and 255), inclusive.  Any bits
4746   * set outside of that range will be ignored.
4747   *
4748   * @param  bytes  The values to include in the byte array.
4749   *
4750   * @return  A byte array with the provided set of values.
4751   */
4752  @NotNull()
4753  public static byte[] byteArray(@Nullable final int... bytes)
4754  {
4755    if ((bytes == null) || (bytes.length == 0))
4756    {
4757      return NO_BYTES;
4758    }
4759
4760    final byte[] byteArray = new byte[bytes.length];
4761    for (int i=0; i < bytes.length; i++)
4762    {
4763      byteArray[i] = (byte) (bytes[i] & 0xFF);
4764    }
4765
4766    return byteArray;
4767  }
4768
4769
4770
4771  /**
4772   * Indicates whether the unit tests are currently running in this JVM.
4773   *
4774   * @return  {@code true} if the unit tests are currently running, or
4775   *          {@code false} if not.
4776   */
4777  public static boolean isWithinUnitTest()
4778  {
4779    return IS_WITHIN_UNIT_TESTS;
4780  }
4781
4782
4783
4784  /**
4785   * Throws an {@code Error} or a {@code RuntimeException} based on the provided
4786   * {@code Throwable} object.  This method will always throw something,
4787   * regardless of the provided {@code Throwable} object.
4788   *
4789   * @param  throwable  The {@code Throwable} object to use to create the
4790   *                    exception to throw.
4791   *
4792   * @throws  Error  If the provided {@code Throwable} object is an
4793   *                 {@code Error} instance, then that {@code Error} instance
4794   *                 will be re-thrown.
4795   *
4796   * @throws  RuntimeException  If the provided {@code Throwable} object is a
4797   *                            {@code RuntimeException} instance, then that
4798   *                            {@code RuntimeException} instance will be
4799   *                            re-thrown.  Otherwise, it must be a checked
4800   *                            exception and that checked exception will be
4801   *                            re-thrown as a {@code RuntimeException}.
4802   */
4803  public static void throwErrorOrRuntimeException(
4804                          @NotNull final Throwable throwable)
4805         throws Error, RuntimeException
4806  {
4807    Validator.ensureNotNull(throwable);
4808
4809    if (throwable instanceof Error)
4810    {
4811      throw (Error) throwable;
4812    }
4813    else if (throwable instanceof RuntimeException)
4814    {
4815      throw (RuntimeException) throwable;
4816    }
4817    else
4818    {
4819      throw new RuntimeException(throwable);
4820    }
4821  }
4822
4823
4824
4825  /**
4826   * Re-throws the provided {@code Throwable} instance only if it is an
4827   * {@code Error} or a {@code RuntimeException} instance; otherwise, this
4828   * method will return without taking any action.
4829   *
4830   * @param  throwable  The {@code Throwable} object to examine and potentially
4831   *                    re-throw.
4832   *
4833   * @throws  Error  If the provided {@code Throwable} object is an
4834   *                 {@code Error} instance, then that {@code Error} instance
4835   *                 will be re-thrown.
4836   *
4837   * @throws  RuntimeException  If the provided {@code Throwable} object is a
4838   *                            {@code RuntimeException} instance, then that
4839   *                            {@code RuntimeException} instance will be
4840   *                            re-thrown.
4841   */
4842  public static void rethrowIfErrorOrRuntimeException(
4843                          @NotNull final Throwable throwable)
4844         throws Error, RuntimeException
4845  {
4846    if (throwable instanceof Error)
4847    {
4848      throw (Error) throwable;
4849    }
4850    else if (throwable instanceof RuntimeException)
4851    {
4852      throw (RuntimeException) throwable;
4853    }
4854  }
4855
4856
4857
4858  /**
4859   * Re-throws the provided {@code Throwable} instance only if it is an
4860   * {@code Error}; otherwise, this method will return without taking any
4861   * action.
4862   *
4863   * @param  throwable  The {@code Throwable} object to examine and potentially
4864   *                    re-throw.
4865   *
4866   * @throws  Error  If the provided {@code Throwable} object is an
4867   *                 {@code Error} instance, then that {@code Error} instance
4868   *                 will be re-thrown.
4869   */
4870  public static void rethrowIfError(@NotNull final Throwable throwable)
4871         throws Error
4872  {
4873    if (throwable instanceof Error)
4874    {
4875      throw (Error) throwable;
4876    }
4877  }
4878
4879
4880
4881  /**
4882   * Computes the capacity that should be used for a map or a set with the
4883   * expected number of elements, which can help avoid the need to re-hash or
4884   * re-balance the map if too many items are added.  This method bases its
4885   * computation on the default map load factor of 0.75.
4886   *
4887   * @param  expectedItemCount  The expected maximum number of items that will
4888   *                            be placed in the map or set.  It must be greater
4889   *                            than or equal to zero.
4890   *
4891   * @return  The capacity that should be used for a map or a set with the
4892   *          expected number of elements
4893   */
4894  public static int computeMapCapacity(final int expectedItemCount)
4895  {
4896    switch (expectedItemCount)
4897    {
4898      case 0:
4899        return 0;
4900      case 1:
4901        return 2;
4902      case 2:
4903        return 3;
4904      case 3:
4905        return 5;
4906      case 4:
4907        return 6;
4908      case 5:
4909        return 7;
4910      case 6:
4911        return 9;
4912      case 7:
4913        return 10;
4914      case 8:
4915        return 11;
4916      case 9:
4917        return 13;
4918      case 10:
4919        return 14;
4920      case 11:
4921        return 15;
4922      case 12:
4923        return 17;
4924      case 13:
4925        return 18;
4926      case 14:
4927        return 19;
4928      case 15:
4929        return 21;
4930      case 16:
4931        return 22;
4932      case 17:
4933        return 23;
4934      case 18:
4935        return 25;
4936      case 19:
4937        return 26;
4938      case 20:
4939        return 27;
4940      case 30:
4941        return 41;
4942      case 40:
4943        return 54;
4944      case 50:
4945        return 67;
4946      case 60:
4947        return 81;
4948      case 70:
4949        return 94;
4950      case 80:
4951        return 107;
4952      case 90:
4953        return 121;
4954      case 100:
4955        return 134;
4956      case 110:
4957        return 147;
4958      case 120:
4959        return 161;
4960      case 130:
4961        return 174;
4962      case 140:
4963        return 187;
4964      case 150:
4965        return 201;
4966      case 160:
4967        return 214;
4968      case 170:
4969        return 227;
4970      case 180:
4971        return 241;
4972      case 190:
4973        return 254;
4974      case 200:
4975        return 267;
4976      default:
4977        Validator.ensureTrue((expectedItemCount >= 0),
4978             "StaticUtils.computeMapOrSetCapacity.expectedItemCount must be " +
4979                  "greater than or equal to zero.");
4980
4981        // NOTE:  536,870,911 is Integer.MAX_VALUE/4.  If the value is larger
4982        // than that, then we'll fall back to using floating-point arithmetic
4983        //
4984        if (expectedItemCount > 536_870_911)
4985        {
4986          final int computedCapacity = ((int) (expectedItemCount / 0.75)) + 1;
4987          if (computedCapacity <= expectedItemCount)
4988          {
4989            // This suggests that the expected number of items is so big that
4990            // the computed capacity can't be adequately represented by an
4991            // integer.  In that case, we'll just return the expected item
4992            // count and let the map or set get re-hashed/re-balanced if it
4993            // actually gets anywhere near that size.
4994            return expectedItemCount;
4995          }
4996          else
4997          {
4998            return computedCapacity;
4999          }
5000        }
5001        else
5002        {
5003          return ((expectedItemCount * 4) / 3) + 1;
5004        }
5005    }
5006  }
5007
5008
5009
5010  /**
5011   * Creates an unmodifiable set containing the provided items.  The iteration
5012   * order of the provided items will be preserved.
5013   *
5014   * @param  <T>    The type of item to include in the set.
5015   * @param  items  The items to include in the set.  It must not be
5016   *                {@code null}, but may be empty.
5017   *
5018   * @return  An unmodifiable set containing the provided items.
5019   */
5020  @SafeVarargs()
5021  @SuppressWarnings("varargs")
5022  @NotNull()
5023  public static <T> Set<T> setOf(@NotNull final T... items)
5024  {
5025    return Collections.unmodifiableSet(
5026         new LinkedHashSet<>(Arrays.asList(items)));
5027  }
5028
5029
5030
5031  /**
5032   * Creates a {@code HashSet} containing the provided items.
5033   *
5034   * @param  <T>    The type of item to include in the set.
5035   * @param  items  The items to include in the set.  It must not be
5036   *                {@code null}, but may be empty.
5037   *
5038   * @return  A {@code HashSet} containing the provided items.
5039   */
5040  @SafeVarargs()
5041  @SuppressWarnings("varargs")
5042  @NotNull()
5043  public static <T> HashSet<T> hashSetOf(@NotNull final T... items)
5044  {
5045    return new HashSet<>(Arrays.asList(items));
5046  }
5047
5048
5049
5050  /**
5051   * Creates a {@code LinkedHashSet} containing the provided items.
5052   *
5053   * @param  <T>    The type of item to include in the set.
5054   * @param  items  The items to include in the set.  It must not be
5055   *                {@code null}, but may be empty.
5056   *
5057   * @return  A {@code LinkedHashSet} containing the provided items.
5058   */
5059  @SafeVarargs()
5060  @SuppressWarnings("varargs")
5061  @NotNull()
5062  public static <T> LinkedHashSet<T> linkedHashSetOf(@NotNull final T... items)
5063  {
5064    return new LinkedHashSet<>(Arrays.asList(items));
5065  }
5066
5067
5068
5069  /**
5070   * Creates a {@code TreeSet} containing the provided items.
5071   *
5072   * @param  <T>    The type of item to include in the set.
5073   * @param  items  The items to include in the set.  It must not be
5074   *                {@code null}, but may be empty.
5075   *
5076   * @return  A {@code LinkedHashSet} containing the provided items.
5077   */
5078  @SafeVarargs()
5079  @SuppressWarnings("varargs")
5080  @NotNull()
5081  public static <T> TreeSet<T> treeSetOf(@NotNull final T... items)
5082  {
5083    return new TreeSet<>(Arrays.asList(items));
5084  }
5085
5086
5087
5088  /**
5089   * Creates an unmodifiable map containing the provided items.
5090   *
5091   * @param  <K>    The type for the map keys.
5092   * @param  <V>    The type for the map values.
5093   * @param  key    The only key to include in the map.
5094   * @param  value  The only value to include in the map.
5095   *
5096   * @return  The unmodifiable map that was created.
5097   */
5098  @NotNull()
5099  public static <K,V> Map<K,V> mapOf(@NotNull final K key,
5100                                     @NotNull final V value)
5101  {
5102    return Collections.singletonMap(key, value);
5103  }
5104
5105
5106
5107  /**
5108   * Creates an unmodifiable map containing the provided items.
5109   *
5110   * @param  <K>     The type for the map keys.
5111   * @param  <V>     The type for the map values.
5112   * @param  key1    The first key to include in the map.
5113   * @param  value1  The first value to include in the map.
5114   * @param  key2    The second key to include in the map.
5115   * @param  value2  The second value to include in the map.
5116   *
5117   * @return  The unmodifiable map that was created.
5118   */
5119  @NotNull()
5120  public static <K,V> Map<K,V> mapOf(@NotNull final K key1,
5121                                     @NotNull final V value1,
5122                                     @NotNull final K key2,
5123                                     @NotNull final V value2)
5124  {
5125    final LinkedHashMap<K,V> map = new LinkedHashMap<>(computeMapCapacity(2));
5126
5127    map.put(key1, value1);
5128    map.put(key2, value2);
5129
5130    return Collections.unmodifiableMap(map);
5131  }
5132
5133
5134
5135  /**
5136   * Creates an unmodifiable map containing the provided items.
5137   *
5138   * @param  <K>     The type for the map keys.
5139   * @param  <V>     The type for the map values.
5140   * @param  key1    The first key to include in the map.
5141   * @param  value1  The first value to include in the map.
5142   * @param  key2    The second key to include in the map.
5143   * @param  value2  The second value to include in the map.
5144   * @param  key3    The third key to include in the map.
5145   * @param  value3  The third value to include in the map.
5146   *
5147   * @return  The unmodifiable map that was created.
5148   */
5149  @NotNull()
5150  public static <K,V> Map<K,V> mapOf(@NotNull final K key1,
5151                                     @NotNull final V value1,
5152                                     @NotNull final K key2,
5153                                     @NotNull final V value2,
5154                                     @NotNull final K key3,
5155                                     @NotNull final V value3)
5156  {
5157    final LinkedHashMap<K,V> map = new LinkedHashMap<>(computeMapCapacity(3));
5158
5159    map.put(key1, value1);
5160    map.put(key2, value2);
5161    map.put(key3, value3);
5162
5163    return Collections.unmodifiableMap(map);
5164  }
5165
5166
5167
5168  /**
5169   * Creates an unmodifiable map containing the provided items.
5170   *
5171   * @param  <K>     The type for the map keys.
5172   * @param  <V>     The type for the map values.
5173   * @param  key1    The first key to include in the map.
5174   * @param  value1  The first value to include in the map.
5175   * @param  key2    The second key to include in the map.
5176   * @param  value2  The second value to include in the map.
5177   * @param  key3    The third key to include in the map.
5178   * @param  value3  The third value to include in the map.
5179   * @param  key4    The fourth key to include in the map.
5180   * @param  value4  The fourth value to include in the map.
5181   *
5182   * @return  The unmodifiable map that was created.
5183   */
5184  @NotNull()
5185  public static <K,V> Map<K,V> mapOf(@NotNull final K key1,
5186                                     @NotNull final V value1,
5187                                     @NotNull final K key2,
5188                                     @NotNull final V value2,
5189                                     @NotNull final K key3,
5190                                     @NotNull final V value3,
5191                                     @NotNull final K key4,
5192                                     @NotNull final V value4)
5193  {
5194    final LinkedHashMap<K,V> map = new LinkedHashMap<>(computeMapCapacity(4));
5195
5196    map.put(key1, value1);
5197    map.put(key2, value2);
5198    map.put(key3, value3);
5199    map.put(key4, value4);
5200
5201    return Collections.unmodifiableMap(map);
5202  }
5203
5204
5205
5206  /**
5207   * Creates an unmodifiable map containing the provided items.
5208   *
5209   * @param  <K>     The type for the map keys.
5210   * @param  <V>     The type for the map values.
5211   * @param  key1    The first key to include in the map.
5212   * @param  value1  The first value to include in the map.
5213   * @param  key2    The second key to include in the map.
5214   * @param  value2  The second value to include in the map.
5215   * @param  key3    The third key to include in the map.
5216   * @param  value3  The third value to include in the map.
5217   * @param  key4    The fourth key to include in the map.
5218   * @param  value4  The fourth value to include in the map.
5219   * @param  key5    The fifth key to include in the map.
5220   * @param  value5  The fifth value to include in the map.
5221   *
5222   * @return  The unmodifiable map that was created.
5223   */
5224  @NotNull()
5225  public static <K,V> Map<K,V> mapOf(@NotNull final K key1,
5226                                     @NotNull final V value1,
5227                                     @NotNull final K key2,
5228                                     @NotNull final V value2,
5229                                     @NotNull final K key3,
5230                                     @NotNull final V value3,
5231                                     @NotNull final K key4,
5232                                     @NotNull final V value4,
5233                                     @NotNull final K key5,
5234                                     @NotNull final V value5)
5235  {
5236    final LinkedHashMap<K,V> map = new LinkedHashMap<>(computeMapCapacity(5));
5237
5238    map.put(key1, value1);
5239    map.put(key2, value2);
5240    map.put(key3, value3);
5241    map.put(key4, value4);
5242    map.put(key5, value5);
5243
5244    return Collections.unmodifiableMap(map);
5245  }
5246
5247
5248
5249  /**
5250   * Creates an unmodifiable map containing the provided items.
5251   *
5252   * @param  <K>     The type for the map keys.
5253   * @param  <V>     The type for the map values.
5254   * @param  key1    The first key to include in the map.
5255   * @param  value1  The first value to include in the map.
5256   * @param  key2    The second key to include in the map.
5257   * @param  value2  The second value to include in the map.
5258   * @param  key3    The third key to include in the map.
5259   * @param  value3  The third value to include in the map.
5260   * @param  key4    The fourth key to include in the map.
5261   * @param  value4  The fourth value to include in the map.
5262   * @param  key5    The fifth key to include in the map.
5263   * @param  value5  The fifth value to include in the map.
5264   * @param  key6    The sixth key to include in the map.
5265   * @param  value6  The sixth value to include in the map.
5266   *
5267   * @return  The unmodifiable map that was created.
5268   */
5269  @NotNull()
5270  public static <K,V> Map<K,V> mapOf(@NotNull final K key1,
5271                                     @NotNull final V value1,
5272                                     @NotNull final K key2,
5273                                     @NotNull final V value2,
5274                                     @NotNull final K key3,
5275                                     @NotNull final V value3,
5276                                     @NotNull final K key4,
5277                                     @NotNull final V value4,
5278                                     @NotNull final K key5,
5279                                     @NotNull final V value5,
5280                                     @NotNull final K key6,
5281                                     @NotNull final V value6)
5282  {
5283    final LinkedHashMap<K,V> map = new LinkedHashMap<>(computeMapCapacity(6));
5284
5285    map.put(key1, value1);
5286    map.put(key2, value2);
5287    map.put(key3, value3);
5288    map.put(key4, value4);
5289    map.put(key5, value5);
5290    map.put(key6, value6);
5291
5292    return Collections.unmodifiableMap(map);
5293  }
5294
5295
5296
5297  /**
5298   * Creates an unmodifiable map containing the provided items.
5299   *
5300   * @param  <K>     The type for the map keys.
5301   * @param  <V>     The type for the map values.
5302   * @param  key1    The first key to include in the map.
5303   * @param  value1  The first value to include in the map.
5304   * @param  key2    The second key to include in the map.
5305   * @param  value2  The second value to include in the map.
5306   * @param  key3    The third key to include in the map.
5307   * @param  value3  The third value to include in the map.
5308   * @param  key4    The fourth key to include in the map.
5309   * @param  value4  The fourth value to include in the map.
5310   * @param  key5    The fifth key to include in the map.
5311   * @param  value5  The fifth value to include in the map.
5312   * @param  key6    The sixth key to include in the map.
5313   * @param  value6  The sixth value to include in the map.
5314   * @param  key7    The seventh key to include in the map.
5315   * @param  value7  The seventh value to include in the map.
5316   *
5317   * @return  The unmodifiable map that was created.
5318   */
5319  @NotNull()
5320  public static <K,V> Map<K,V> mapOf(@NotNull final K key1,
5321                                     @NotNull final V value1,
5322                                     @NotNull final K key2,
5323                                     @NotNull final V value2,
5324                                     @NotNull final K key3,
5325                                     @NotNull final V value3,
5326                                     @NotNull final K key4,
5327                                     @NotNull final V value4,
5328                                     @NotNull final K key5,
5329                                     @NotNull final V value5,
5330                                     @NotNull final K key6,
5331                                     @NotNull final V value6,
5332                                     @NotNull final K key7,
5333                                     @NotNull final V value7)
5334  {
5335    final LinkedHashMap<K,V> map = new LinkedHashMap<>(computeMapCapacity(7));
5336
5337    map.put(key1, value1);
5338    map.put(key2, value2);
5339    map.put(key3, value3);
5340    map.put(key4, value4);
5341    map.put(key5, value5);
5342    map.put(key6, value6);
5343    map.put(key7, value7);
5344
5345    return Collections.unmodifiableMap(map);
5346  }
5347
5348
5349
5350  /**
5351   * Creates an unmodifiable map containing the provided items.
5352   *
5353   * @param  <K>     The type for the map keys.
5354   * @param  <V>     The type for the map values.
5355   * @param  key1    The first key to include in the map.
5356   * @param  value1  The first value to include in the map.
5357   * @param  key2    The second key to include in the map.
5358   * @param  value2  The second value to include in the map.
5359   * @param  key3    The third key to include in the map.
5360   * @param  value3  The third value to include in the map.
5361   * @param  key4    The fourth key to include in the map.
5362   * @param  value4  The fourth value to include in the map.
5363   * @param  key5    The fifth key to include in the map.
5364   * @param  value5  The fifth value to include in the map.
5365   * @param  key6    The sixth key to include in the map.
5366   * @param  value6  The sixth value to include in the map.
5367   * @param  key7    The seventh key to include in the map.
5368   * @param  value7  The seventh value to include in the map.
5369   * @param  key8    The eighth key to include in the map.
5370   * @param  value8  The eighth value to include in the map.
5371   *
5372   * @return  The unmodifiable map that was created.
5373   */
5374  @NotNull()
5375  public static <K,V> Map<K,V> mapOf(@NotNull final K key1,
5376                                     @NotNull final V value1,
5377                                     @NotNull final K key2,
5378                                     @NotNull final V value2,
5379                                     @NotNull final K key3,
5380                                     @NotNull final V value3,
5381                                     @NotNull final K key4,
5382                                     @NotNull final V value4,
5383                                     @NotNull final K key5,
5384                                     @NotNull final V value5,
5385                                     @NotNull final K key6,
5386                                     @NotNull final V value6,
5387                                     @NotNull final K key7,
5388                                     @NotNull final V value7,
5389                                     @NotNull final K key8,
5390                                     @NotNull final V value8)
5391  {
5392    final LinkedHashMap<K,V> map = new LinkedHashMap<>(computeMapCapacity(8));
5393
5394    map.put(key1, value1);
5395    map.put(key2, value2);
5396    map.put(key3, value3);
5397    map.put(key4, value4);
5398    map.put(key5, value5);
5399    map.put(key6, value6);
5400    map.put(key7, value7);
5401    map.put(key8, value8);
5402
5403    return Collections.unmodifiableMap(map);
5404  }
5405
5406
5407
5408  /**
5409   * Creates an unmodifiable map containing the provided items.
5410   *
5411   * @param  <K>     The type for the map keys.
5412   * @param  <V>     The type for the map values.
5413   * @param  key1    The first key to include in the map.
5414   * @param  value1  The first value to include in the map.
5415   * @param  key2    The second key to include in the map.
5416   * @param  value2  The second value to include in the map.
5417   * @param  key3    The third key to include in the map.
5418   * @param  value3  The third value to include in the map.
5419   * @param  key4    The fourth key to include in the map.
5420   * @param  value4  The fourth value to include in the map.
5421   * @param  key5    The fifth key to include in the map.
5422   * @param  value5  The fifth value to include in the map.
5423   * @param  key6    The sixth key to include in the map.
5424   * @param  value6  The sixth value to include in the map.
5425   * @param  key7    The seventh key to include in the map.
5426   * @param  value7  The seventh value to include in the map.
5427   * @param  key8    The eighth key to include in the map.
5428   * @param  value8  The eighth value to include in the map.
5429   * @param  key9    The ninth key to include in the map.
5430   * @param  value9  The ninth value to include in the map.
5431   *
5432   * @return  The unmodifiable map that was created.
5433   */
5434  @NotNull()
5435  public static <K,V> Map<K,V> mapOf(@NotNull final K key1,
5436                                     @NotNull final V value1,
5437                                     @NotNull final K key2,
5438                                     @NotNull final V value2,
5439                                     @NotNull final K key3,
5440                                     @NotNull final V value3,
5441                                     @NotNull final K key4,
5442                                     @NotNull final V value4,
5443                                     @NotNull final K key5,
5444                                     @NotNull final V value5,
5445                                     @NotNull final K key6,
5446                                     @NotNull final V value6,
5447                                     @NotNull final K key7,
5448                                     @NotNull final V value7,
5449                                     @NotNull final K key8,
5450                                     @NotNull final V value8,
5451                                     @NotNull final K key9,
5452                                     @NotNull final V value9)
5453  {
5454    final LinkedHashMap<K,V> map = new LinkedHashMap<>(computeMapCapacity(9));
5455
5456    map.put(key1, value1);
5457    map.put(key2, value2);
5458    map.put(key3, value3);
5459    map.put(key4, value4);
5460    map.put(key5, value5);
5461    map.put(key6, value6);
5462    map.put(key7, value7);
5463    map.put(key8, value8);
5464    map.put(key9, value9);
5465
5466    return Collections.unmodifiableMap(map);
5467  }
5468
5469
5470
5471  /**
5472   * Creates an unmodifiable map containing the provided items.
5473   *
5474   * @param  <K>      The type for the map keys.
5475   * @param  <V>      The type for the map values.
5476   * @param  key1     The first key to include in the map.
5477   * @param  value1   The first value to include in the map.
5478   * @param  key2     The second key to include in the map.
5479   * @param  value2   The second value to include in the map.
5480   * @param  key3     The third key to include in the map.
5481   * @param  value3   The third value to include in the map.
5482   * @param  key4     The fourth key to include in the map.
5483   * @param  value4   The fourth value to include in the map.
5484   * @param  key5     The fifth key to include in the map.
5485   * @param  value5   The fifth value to include in the map.
5486   * @param  key6     The sixth key to include in the map.
5487   * @param  value6   The sixth value to include in the map.
5488   * @param  key7     The seventh key to include in the map.
5489   * @param  value7   The seventh value to include in the map.
5490   * @param  key8     The eighth key to include in the map.
5491   * @param  value8   The eighth value to include in the map.
5492   * @param  key9     The ninth key to include in the map.
5493   * @param  value9   The ninth value to include in the map.
5494   * @param  key10    The tenth key to include in the map.
5495   * @param  value10  The tenth value to include in the map.
5496   *
5497   * @return  The unmodifiable map that was created.
5498   */
5499  @NotNull()
5500  public static <K,V> Map<K,V> mapOf(@NotNull final K key1,
5501                                     @NotNull final V value1,
5502                                     @NotNull final K key2,
5503                                     @NotNull final V value2,
5504                                     @NotNull final K key3,
5505                                     @NotNull final V value3,
5506                                     @NotNull final K key4,
5507                                     @NotNull final V value4,
5508                                     @NotNull final K key5,
5509                                     @NotNull final V value5,
5510                                     @NotNull final K key6,
5511                                     @NotNull final V value6,
5512                                     @NotNull final K key7,
5513                                     @NotNull final V value7,
5514                                     @NotNull final K key8,
5515                                     @NotNull final V value8,
5516                                     @NotNull final K key9,
5517                                     @NotNull final V value9,
5518                                     @NotNull final K key10,
5519                                     @NotNull final V value10)
5520  {
5521    final LinkedHashMap<K,V> map = new LinkedHashMap<>(computeMapCapacity(10));
5522
5523    map.put(key1, value1);
5524    map.put(key2, value2);
5525    map.put(key3, value3);
5526    map.put(key4, value4);
5527    map.put(key5, value5);
5528    map.put(key6, value6);
5529    map.put(key7, value7);
5530    map.put(key8, value8);
5531    map.put(key9, value9);
5532    map.put(key10, value10);
5533
5534    return Collections.unmodifiableMap(map);
5535  }
5536
5537
5538
5539  /**
5540   * Creates an unmodifiable map containing the provided items.  The map entries
5541   * must have the same data type for keys and values.
5542   *
5543   * @param  <T>    The type for the map keys and values.
5544   * @param  items  The items to include in the map.  If it is null or empty,
5545   *                the map will be empty.  If it is non-empty, then the number
5546   *                of elements in the array must be a multiple of two.
5547   *                Elements in even-numbered indexes will be the keys for the
5548   *                map entries, while elements in odd-numbered indexes will be
5549   *                the map values.
5550   *
5551   * @return  The unmodifiable map that was created.
5552   */
5553  @SafeVarargs()
5554  @NotNull()
5555  public static <T> Map<T,T> mapOf(@Nullable final T... items)
5556  {
5557    if ((items == null) || (items.length == 0))
5558    {
5559      return Collections.emptyMap();
5560    }
5561
5562    Validator.ensureTrue(((items.length % 2) == 0),
5563         "StaticUtils.mapOf.items must have an even number of elements");
5564
5565    final int numEntries = items.length / 2;
5566    final LinkedHashMap<T,T> map =
5567         new LinkedHashMap<>(computeMapCapacity(numEntries));
5568    for (int i=0; i < items.length; )
5569    {
5570      map.put(items[i++], items[i++]);
5571    }
5572
5573    return Collections.unmodifiableMap(map);
5574  }
5575
5576
5577
5578  /**
5579   * Creates an unmodifiable map containing the provided items.
5580   *
5581   * @param  <K>    The type for the map keys.
5582   * @param  <V>    The type for the map values.
5583   * @param  items  The items to include in the map.
5584   *
5585   * @return  The unmodifiable map that was created.
5586   */
5587  @SafeVarargs()
5588  @NotNull()
5589  public static <K,V> Map<K,V> mapOfObjectPairs(
5590                                    @Nullable final ObjectPair<K,V>... items)
5591  {
5592    if ((items == null) || (items.length == 0))
5593    {
5594      return Collections.emptyMap();
5595    }
5596
5597    final LinkedHashMap<K,V> map = new LinkedHashMap<>(
5598         computeMapCapacity(items.length));
5599    for (final ObjectPair<K,V> item : items)
5600    {
5601      map.put(item.getFirst(), item.getSecond());
5602    }
5603
5604    return Collections.unmodifiableMap(map);
5605  }
5606
5607
5608
5609  /**
5610   * Attempts to determine all addresses associated with the local system,
5611   * including loopback addresses.
5612   *
5613   * @param  nameResolver  The name resolver to use to determine the local host
5614   *                       and loopback addresses.  If this is {@code null},
5615   *                       then the LDAP SDK's default name resolver will be
5616   *                       used.
5617   *
5618   * @return  A set of the local addresses that were identified.
5619   */
5620  @NotNull()
5621  public static Set<InetAddress> getAllLocalAddresses(
5622                                      @Nullable final NameResolver nameResolver)
5623  {
5624    return getAllLocalAddresses(nameResolver, true);
5625  }
5626
5627
5628
5629  /**
5630   * Attempts to determine all addresses associated with the local system,
5631   * optionally including loopback addresses.
5632   *
5633   * @param  nameResolver     The name resolver to use to determine the local
5634   *                          host and loopback addresses.  If this is
5635   *                          {@code null}, then the LDAP SDK's default name
5636   *                          resolver will be used.
5637   * @param  includeLoopback  Indicates whether to include loopback addresses in
5638   *                          the set that is returned.
5639   *
5640   * @return  A set of the local addresses that were identified.
5641   */
5642  @NotNull()
5643  public static Set<InetAddress> getAllLocalAddresses(
5644                                      @Nullable final NameResolver nameResolver,
5645                                      final boolean includeLoopback)
5646  {
5647    final NameResolver resolver;
5648    if (nameResolver == null)
5649    {
5650      resolver = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER;
5651    }
5652    else
5653    {
5654      resolver = nameResolver;
5655    }
5656
5657    final LinkedHashSet<InetAddress> localAddresses =
5658         new LinkedHashSet<>(computeMapCapacity(10));
5659
5660    try
5661    {
5662      final InetAddress localHostAddress = resolver.getLocalHost();
5663      if (includeLoopback || (! localHostAddress.isLoopbackAddress()))
5664      {
5665        localAddresses.add(localHostAddress);
5666      }
5667    }
5668    catch (final Exception e)
5669    {
5670      Debug.debugException(e);
5671    }
5672
5673    try
5674    {
5675      final Enumeration<NetworkInterface> networkInterfaces =
5676           NetworkInterface.getNetworkInterfaces();
5677      while (networkInterfaces.hasMoreElements())
5678      {
5679        final NetworkInterface networkInterface =
5680             networkInterfaces.nextElement();
5681        if (includeLoopback || (! networkInterface.isLoopback()))
5682        {
5683          final Enumeration<InetAddress> interfaceAddresses =
5684               networkInterface.getInetAddresses();
5685          while (interfaceAddresses.hasMoreElements())
5686          {
5687            final InetAddress address = interfaceAddresses.nextElement();
5688            if (includeLoopback || (! address.isLoopbackAddress()))
5689            {
5690              localAddresses.add(address);
5691            }
5692          }
5693        }
5694      }
5695    }
5696    catch (final Exception e)
5697    {
5698      Debug.debugException(e);
5699    }
5700
5701    if (includeLoopback)
5702    {
5703      try
5704      {
5705        localAddresses.add(resolver.getLoopbackAddress());
5706      }
5707      catch (final Exception e)
5708      {
5709        Debug.debugException(e);
5710      }
5711    }
5712
5713    return Collections.unmodifiableSet(localAddresses);
5714  }
5715
5716
5717
5718  /**
5719   * Retrieves the canonical host name for the provided address, if it can be
5720   * resolved to a name.
5721   *
5722   * @param  nameResolver  The name resolver to use to obtain the canonical
5723   *                       host name.  If this is {@code null}, then the LDAP
5724   *                       SDK's default name resolver will be used.
5725   * @param  address       The {@code InetAddress} for which to attempt to
5726   *                       obtain the canonical host name.
5727   *
5728   * @return  The canonical host name for the provided address, or {@code null}
5729   *          if it cannot be obtained (either because the attempt returns
5730   *          {@code null}, which shouldn't happen, or because it matches the
5731   *          IP address).
5732   */
5733  @Nullable()
5734  public static String getCanonicalHostNameIfAvailable(
5735                            @Nullable final NameResolver nameResolver,
5736                            @NotNull final InetAddress address)
5737  {
5738    final NameResolver resolver;
5739    if (nameResolver == null)
5740    {
5741      resolver = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER;
5742    }
5743    else
5744    {
5745      resolver = nameResolver;
5746    }
5747
5748    final String hostAddress = address.getHostAddress();
5749    final String trimmedHostAddress =
5750         trimInterfaceNameFromHostAddress(hostAddress);
5751
5752    final String canonicalHostName = resolver.getCanonicalHostName(address);
5753    if ((canonicalHostName == null) ||
5754         canonicalHostName.equalsIgnoreCase(hostAddress) ||
5755         canonicalHostName.equalsIgnoreCase(trimmedHostAddress))
5756    {
5757      return null;
5758    }
5759
5760    return canonicalHostName;
5761  }
5762
5763
5764
5765  /**
5766   * Retrieves the canonical host names for the provided set of
5767   * {@code InetAddress} objects.  If any of the provided addresses cannot be
5768   * resolved to a canonical host name (in which case the attempt to get the
5769   * canonical host name will return its IP address), it will be excluded from
5770   * the returned set.
5771   *
5772   * @param  nameResolver  The name resolver to use to obtain the canonical
5773   *                       host names.  If this is {@code null}, then the LDAP
5774   *                       SDK's default name resolver will be used.
5775   * @param  addresses     The set of addresses for which to obtain the
5776   *                       canonical host names.
5777   *
5778   * @return  A set of the canonical host names that could be obtained from the
5779   *          provided addresses.
5780   */
5781  @NotNull()
5782  public static Set<String> getAvailableCanonicalHostNames(
5783                     @Nullable final NameResolver nameResolver,
5784                     @NotNull final Collection<InetAddress> addresses)
5785  {
5786    final NameResolver resolver;
5787    if (nameResolver == null)
5788    {
5789      resolver = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER;
5790    }
5791    else
5792    {
5793      resolver = nameResolver;
5794    }
5795
5796    final Set<String> canonicalHostNames =
5797         new LinkedHashSet<>(computeMapCapacity(addresses.size()));
5798    for (final InetAddress address : addresses)
5799    {
5800      final String canonicalHostName =
5801           getCanonicalHostNameIfAvailable(resolver, address);
5802      if (canonicalHostName != null)
5803      {
5804        canonicalHostNames.add(canonicalHostName);
5805      }
5806    }
5807
5808    return Collections.unmodifiableSet(canonicalHostNames);
5809  }
5810
5811
5812
5813  /**
5814   * Retrieves a version of the provided host address with the interface name
5815   * stripped off.  Java sometimes follows an IP address with a percent sign and
5816   * the interface name.  If that interface name is present in the provided
5817   * host address, then this method will trim it off, leaving just the IP
5818   * address.  If the provided host address does not include the interface name,
5819   * then the provided address will be returned as-is.
5820   *
5821   * @param  hostAddress  The host address to be trimmed.
5822   *
5823   * @return  The provided host address without the interface name.
5824   */
5825  @NotNull()
5826  public static String trimInterfaceNameFromHostAddress(
5827                            @NotNull final String hostAddress)
5828  {
5829    final int percentPos = hostAddress.indexOf('%');
5830    if (percentPos > 0)
5831    {
5832      return hostAddress.substring(0, percentPos);
5833    }
5834    else
5835    {
5836      return hostAddress;
5837    }
5838  }
5839
5840
5841
5842  /**
5843   * Indicates whether the provided address is marked as reserved in the IANA
5844   * IPv4 address space registry at
5845   * https://www.iana.org/assignments/ipv4-address-space/ipv4-address-space.txt
5846   * or the IPv6 address space registry at
5847   * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.txt.
5848   *
5849   * @param  address
5850   *             The address for which to make the determination.  It must
5851   *             not be {@code null}, and it must be an IPv4 or IPv6 address.
5852   * @param  includePrivateUseNetworkAddresses
5853   *              Indicates whether to consider addresses in a private-use
5854   *              network address range (including 10.0.0.0/8, 172.16.0.0/12,
5855   *              192.168.0.0/16, and fc00::/7) as reserved addresses.  If this
5856   *              is {@code true}, then this method will return {@code true} for
5857   *              addresses in a private-use network range; if it is
5858   *              {@code false}, then this method will return {@code false} for
5859   *              addresses in those ranges.  This does not have any effect for
5860   *              addresses in other reserved address ranges.
5861   *
5862   * @return  {@code true} if the provided address is in a reserved address
5863   *          range, or {@code false} if not.
5864   */
5865  public static boolean isIANAReservedIPAddress(
5866              @NotNull final InetAddress address,
5867              final boolean includePrivateUseNetworkAddresses)
5868  {
5869    if (address instanceof Inet4Address)
5870    {
5871      return isIANAReservedIPv4Address((Inet4Address) address,
5872           includePrivateUseNetworkAddresses);
5873    }
5874    else if (address instanceof Inet6Address)
5875    {
5876      return isIANAReservedIPv6Address((Inet6Address) address,
5877           includePrivateUseNetworkAddresses);
5878    }
5879    else
5880    {
5881      // It's an unrecognized address type.  We have to assume it's not
5882      // reserved.
5883      return false;
5884    }
5885  }
5886
5887
5888
5889  /**
5890   * Indicates whether the provided address is marked as reserved in the IANA
5891   * IPv4 address space registry at
5892   * https://www.iana.org/assignments/ipv4-address-space/ipv4-address-space.txt.
5893   * This implementation is based on the version of the registry that was
5894   * updated on 2019-12-27.
5895   *
5896   * @param  address
5897   *             The IPv4 address for which to make the determination.  It must
5898   *             not be {@code null}, and it must be an IPv4 address.
5899   * @param  includePrivateUseNetworkAddresses
5900   *              Indicates whether to consider addresses in a private-use
5901   *              network address range as reserved addresses.
5902   *
5903   * @return  {@code true} if the provided address is in a reserved address
5904   *          range, or {@code false} if not.
5905   */
5906  public static boolean isIANAReservedIPv4Address(
5907              @NotNull final Inet4Address address,
5908              final boolean includePrivateUseNetworkAddresses)
5909  {
5910    final byte[] addressBytes = address.getAddress();
5911    final int firstOctet = addressBytes[0] & 0xFF;
5912    final int secondOctet = addressBytes[1] & 0xFF;
5913    final int thirdOctet = addressBytes[2] & 0xFF;
5914
5915    switch (firstOctet)
5916    {
5917      // * Addresses 0.*.*.* are reserved for self-identification.
5918      case 0:
5919
5920      // * Addresses 127.*.*.* are reserved for loopback addresses.
5921      case 127:
5922
5923      // * Addresses 224.*.*.* through 239.*.*.* are reserved for multicast.
5924      case 224:
5925      case 225:
5926      case 226:
5927      case 227:
5928      case 228:
5929      case 229:
5930      case 230:
5931      case 231:
5932      case 232:
5933      case 233:
5934      case 234:
5935      case 235:
5936      case 236:
5937      case 237:
5938      case 238:
5939      case 239:
5940
5941      // * Addresses 240.*.*.* through 255.*.*.* are reserved for future use.
5942      case 240:
5943      case 241:
5944      case 242:
5945      case 243:
5946      case 244:
5947      case 245:
5948      case 246:
5949      case 247:
5950      case 248:
5951      case 249:
5952      case 250:
5953      case 251:
5954      case 252:
5955      case 253:
5956      case 254:
5957      case 255:
5958        return true;
5959
5960      // * Addresses 10.*.*.* are reserved for private-use networks.
5961      case 10:
5962        return includePrivateUseNetworkAddresses;
5963
5964      // * Addresses 100.64.0.0 through 100.127.255.255. are in the shared
5965      //   address space range described in RFC 6598.
5966      case 100:  // First octet 100 -- Partially reserved
5967        return ((secondOctet >= 64) && (secondOctet <= 127));
5968
5969      // * Addresses 169.254.*.* are reserved for link-local addresses.
5970      case 169:
5971        return (secondOctet == 254);
5972
5973      // * Addresses 172.16.0.0 through 172.31.255.255 are reserved for
5974      //   private-use networks.
5975      case 172:
5976        if ((secondOctet >= 16) && (secondOctet <= 31))
5977        {
5978          return includePrivateUseNetworkAddresses;
5979        }
5980        else
5981        {
5982          return false;
5983        }
5984
5985      // * Addresses 192.0.0.* are reserved for IPv4 Special Purpose Address.
5986      // * Addresses 192.0.2.* are reserved for TEST-NET-1.
5987      // * Addresses 192.88.99.* are reserved for 6to4 Relay Anycast.
5988      // * Addresses 192.168.*.* are reserved for private-use networks.
5989      case 192:
5990        if (secondOctet == 0)
5991        {
5992          return ((thirdOctet == 0) || (thirdOctet == 2));
5993        }
5994        else if (secondOctet == 88)
5995        {
5996          return (thirdOctet == 99);
5997        }
5998        else if (secondOctet == 168)
5999        {
6000          return includePrivateUseNetworkAddresses;
6001        }
6002        else
6003        {
6004          return false;
6005        }
6006
6007      // * Addresses 198.18.0.0 through 198.19.255.255 are reserved for Network
6008      //   Interconnect Device Benchmark Testing.
6009      // * Addresses 198.51.100.* are reserved for TEST-NET-2.
6010      case 198:
6011        if ((secondOctet >= 18) && (secondOctet <= 19))
6012        {
6013          return true;
6014        }
6015        else
6016        {
6017          return ((secondOctet == 51) && (thirdOctet == 100));
6018        }
6019
6020      // * Addresses 203.0.113.* are reserved for TEST-NET-3.
6021      case 203:
6022        return ((secondOctet == 0) && (thirdOctet == 113));
6023
6024      // All other addresses are not reserved.
6025      default:
6026        return false;
6027    }
6028  }
6029
6030
6031
6032  /**
6033   * Indicates whether the provided address is marked as reserved in the IANA
6034   * IPv6 address space registry at
6035   * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.txt.
6036   * This implementation is based on the version of the registry that was
6037   * updated on 2019-09-13.
6038   *
6039   * @param  address
6040   *             The IPv4 address for which to make the determination.  It must
6041   *             not be {@code null}, and it must be an IPv6 address.
6042   * @param  includePrivateUseNetworkAddresses
6043   *              Indicates whether to consider addresses in a private-use
6044   *              network address range as reserved addresses.
6045   *
6046   * @return  {@code true} if the provided address is in a reserved address
6047   *          range, or {@code false} if not.
6048   */
6049  public static boolean isIANAReservedIPv6Address(
6050              @NotNull final Inet6Address address,
6051              final boolean includePrivateUseNetworkAddresses)
6052  {
6053    final byte[] addressBytes = address.getAddress();
6054    final int firstOctet = addressBytes[0] & 0xFF;
6055
6056    // Addresses with a first octet between 0x20 and 0x3F are not reserved.
6057    if ((firstOctet >= 0x20) && (firstOctet <= 0x3F))
6058    {
6059      return false;
6060    }
6061
6062    // Addresses with a first octet between 0xFC and 0xFD are reserved for
6063    // private-use networks.
6064    if ((firstOctet >= 0xFC) && (firstOctet <= 0xFD))
6065    {
6066      return includePrivateUseNetworkAddresses;
6067    }
6068
6069    // All other addresses are reserved.
6070    return true;
6071  }
6072
6073
6074
6075  /**
6076   * Reads the bytes that comprise the specified file.
6077   *
6078   * @param  path  The path to the file to be read.
6079   *
6080   * @return  The bytes that comprise the specified file.
6081   *
6082   * @throws  IOException  If a problem occurs while trying to read the file.
6083   */
6084  @NotNull()
6085  public static byte[] readFileBytes(@NotNull final String path)
6086         throws IOException
6087  {
6088    return readFileBytes(new File(path));
6089  }
6090
6091
6092
6093  /**
6094   * Reads the bytes that comprise the specified file.
6095   *
6096   * @param  file  The file to be read.
6097   *
6098   * @return  The bytes that comprise the specified file.
6099   *
6100   * @throws  IOException  If a problem occurs while trying to read the file.
6101   */
6102  @NotNull()
6103  public static byte[] readFileBytes(@NotNull final File file)
6104         throws IOException
6105  {
6106    final ByteStringBuffer buffer = new ByteStringBuffer((int) file.length());
6107    buffer.readFrom(file);
6108    return buffer.toByteArray();
6109  }
6110
6111
6112
6113  /**
6114   * Reads the contents of the specified file as a string.  All line breaks in
6115   * the file will be preserved, with the possible exception of the one on the
6116   * last line.
6117   *
6118   * @param  path                   The path to the file to be read.
6119   * @param  includeFinalLineBreak  Indicates whether the final line break (if
6120   *                                there is one) should be preserved.
6121   *
6122   * @return  The contents of the specified file as a string.
6123   *
6124   * @throws  IOException  If a problem occurs while trying to read the file.
6125   */
6126  @NotNull()
6127  public static String readFileAsString(@NotNull final String path,
6128                                        final boolean includeFinalLineBreak)
6129         throws IOException
6130  {
6131    return readFileAsString(new File(path), includeFinalLineBreak);
6132  }
6133
6134
6135
6136  /**
6137   * Reads the contents of the specified file as a string.  All line breaks in
6138   * the file will be preserved, with the possible exception of the one on the
6139   * last line.
6140   *
6141   * @param  file                   The file to be read.
6142   * @param  includeFinalLineBreak  Indicates whether the final line break (if
6143   *                                there is one) should be preserved.
6144   *
6145   * @return  The contents of the specified file as a string.
6146   *
6147   * @throws  IOException  If a problem occurs while trying to read the file.
6148   */
6149  @NotNull()
6150  public static String readFileAsString(@NotNull final File file,
6151                                        final boolean includeFinalLineBreak)
6152         throws IOException
6153  {
6154    final ByteStringBuffer buffer = new ByteStringBuffer((int) file.length());
6155    buffer.readFrom(file);
6156
6157    if (! includeFinalLineBreak)
6158    {
6159      if (buffer.endsWith(EOL_BYTES_CR_LF))
6160      {
6161        buffer.setLength(buffer.length() - EOL_BYTES_CR_LF.length);
6162      }
6163      else if (buffer.endsWith(EOL_BYTES_LF))
6164      {
6165        buffer.setLength(buffer.length() - EOL_BYTES_LF.length);
6166      }
6167    }
6168
6169    return buffer.toString();
6170  }
6171
6172
6173
6174  /**
6175   * Reads the lines that comprise the specified file.
6176   *
6177   * @param  path  The path to the file to be read.
6178   *
6179   * @return  The lines that comprise the specified file.
6180   *
6181   * @throws  IOException  If a problem occurs while trying to read the file.
6182   */
6183  @NotNull()
6184  public static List<String> readFileLines(@NotNull final String path)
6185         throws IOException
6186  {
6187    return readFileLines(new File(path));
6188  }
6189
6190
6191
6192  /**
6193   * Reads the lines that comprise the specified file.
6194   *
6195   * @param  file  The file to be read.
6196   *
6197   * @return  The lines that comprise the specified file.
6198   *
6199   * @throws  IOException  If a problem occurs while trying to read the file.
6200   */
6201  @NotNull()
6202  public static List<String> readFileLines(@NotNull final File file)
6203         throws IOException
6204  {
6205    try (FileReader fileReader = new FileReader(file);
6206         BufferedReader bufferedReader = new BufferedReader(fileReader))
6207    {
6208      final List<String> lines = new ArrayList<>();
6209      while (true)
6210      {
6211        final String line = bufferedReader.readLine();
6212        if (line == null)
6213        {
6214          return Collections.unmodifiableList(lines);
6215        }
6216
6217        lines.add(line);
6218      }
6219    }
6220  }
6221
6222
6223
6224  /**
6225   * Writes the provided bytes to the specified file.  If the file already
6226   * exists, it will be overwritten.
6227   *
6228   * @param  path   The path to the file to be written.
6229   * @param  bytes  The bytes to be written to the specified file.
6230   *
6231   * @throws  IOException  If a problem is encountered while writing the file.
6232   */
6233  public static void writeFile(@NotNull final String path,
6234                               @NotNull final byte[] bytes)
6235         throws IOException
6236  {
6237    writeFile(new File(path), bytes);
6238  }
6239
6240
6241
6242  /**
6243   * Writes the provided bytes to the specified file.  If the file already
6244   * exists, it will be overwritten.
6245   *
6246   * @param  file   The file to be written.
6247   * @param  bytes  The bytes to be written to the specified file.
6248   *
6249   * @throws  IOException  If a problem is encountered while writing the file.
6250   */
6251  public static void writeFile(@NotNull final File file,
6252                               @NotNull final byte[] bytes)
6253         throws IOException
6254  {
6255    try (FileOutputStream outputStream = new FileOutputStream(file))
6256    {
6257      outputStream.write(bytes);
6258    }
6259  }
6260
6261
6262
6263  /**
6264   * Writes the provided lines to the specified file, with each followed by an
6265   * appropriate end-of-line marker for the current platform.  If the file
6266   * already exists, it will be overwritten.
6267   *
6268   * @param  path   The path to the file to be written.
6269   * @param  lines  The lines to be written to the specified file.
6270   *
6271   * @throws  IOException  If a problem is encountered while writing the file.
6272   */
6273  public static void writeFile(@NotNull final String path,
6274                               @NotNull final CharSequence... lines)
6275         throws IOException
6276  {
6277    writeFile(new File(path), lines);
6278  }
6279
6280
6281
6282  /**
6283   * Writes the provided lines to the specified file, with each followed by an
6284   * appropriate end-of-line marker for the current platform.  If the file
6285   * already exists, it will be overwritten.
6286   *
6287   * @param  file   The file to be written.
6288   * @param  lines  The lines to be written to the specified file.
6289   *
6290   * @throws  IOException  If a problem is encountered while writing the file.
6291   */
6292  public static void writeFile(@NotNull final File file,
6293                               @NotNull final CharSequence... lines)
6294         throws IOException
6295  {
6296    writeFile(file, toList(lines));
6297  }
6298
6299
6300
6301  /**
6302   * Writes the provided lines to the specified file, with each followed by an
6303   * appropriate end-of-line marker for the current platform.  If the file
6304   * already exists, it will be overwritten.
6305   *
6306   * @param  path   The path to the file to be written.
6307   * @param  lines  The lines to be written to the specified file.
6308   *
6309   * @throws  IOException  If a problem is encountered while writing the file.
6310   */
6311  public static void writeFile(@NotNull final String path,
6312                          @Nullable final List<? extends CharSequence> lines)
6313         throws IOException
6314  {
6315    writeFile(new File(path), lines);
6316  }
6317
6318
6319
6320  /**
6321   * Writes the provided lines to the specified file, with each followed by an
6322   * appropriate end-of-line marker for the current platform.  If the file
6323   * already exists, it will be overwritten.
6324   *
6325   * @param  file   The file to be written.
6326   * @param  lines  The lines to be written to the specified file.
6327   *
6328   * @throws  IOException  If a problem is encountered while writing the file.
6329   */
6330  public static void writeFile(@NotNull final File file,
6331                          @Nullable final List<? extends CharSequence> lines)
6332         throws IOException
6333  {
6334    try (PrintWriter writer = new PrintWriter(file))
6335    {
6336      if (lines != null)
6337      {
6338        for (final CharSequence line : lines)
6339        {
6340          writer.println(line);
6341        }
6342      }
6343    }
6344  }
6345
6346
6347
6348  /**
6349   * Retrieves a byte array with the specified number of randomly selected
6350   * bytes.
6351   *
6352   * @param  numBytes  The number of bytes of random data to retrieve.  It must
6353   *                   be greater than or equal to zero.
6354   * @param  secure    Indicates whether to use a cryptographically secure
6355   *                   random number generator.
6356   *
6357   * @return  A byte array with the specified number of randomly selected
6358   *          bytes.
6359   */
6360  @NotNull()
6361  public static byte[] randomBytes(final int numBytes,
6362                                   final boolean secure)
6363  {
6364    final byte[] byteArray = new byte[numBytes];
6365    getThreadLocalRandom(secure).nextBytes(byteArray);
6366    return byteArray;
6367  }
6368
6369
6370
6371  /**
6372   * Retrieves a randomly selected integer between the given upper and lower
6373   * bounds.
6374   *
6375   * @param  lowerBound  The lowest value that may be selected at random.  It
6376   *                     must be less than or equal to the upper bound.
6377   * @param  upperBound  The highest value that may be selected at random.  It
6378   *                     must be greater than or equal to the lower bound.
6379   * @param  secure      Indicates whether to use a cryptographically secure
6380   *                     random number generator.
6381   *
6382   * @return  A randomly selected integer between the given upper and lower
6383   *          bounds.
6384   */
6385  public static int randomInt(final int lowerBound, final int upperBound,
6386                              final boolean secure)
6387  {
6388    // Compute the span of values.  We need to use a long for this, because it's
6389    // possible that this could cause an integer overflow.
6390    final long span = 1L + upperBound - lowerBound;
6391
6392
6393    // Select a random long value between zero and that span.
6394    final long randomLong = getThreadLocalRandom(secure).nextLong();
6395    final long positiveLong = randomLong & 0x7F_FF_FF_FF_FF_FF_FF_FFL;
6396    final long valueWithinSpan = positiveLong % span;
6397    return (int) (lowerBound + valueWithinSpan);
6398  }
6399
6400
6401
6402  /**
6403   * Retrieves a string containing the specified number of randomly selected
6404   * ASCII letters.  It will contain only lowercase letters.
6405   *
6406   * @param  length  The number of letters to include in the string.  It must be
6407   *                 greater than or equal to zero.
6408   * @param  secure  Indicates whether to use a cryptographically secure random
6409   *                 number generator.
6410   *
6411   * @return  The randomly generated alphabetic string.
6412   */
6413  @NotNull()
6414  public static String randomAlphabeticString(final int length,
6415                                              final boolean secure)
6416  {
6417    return randomString(length, LOWERCASE_LETTERS, secure);
6418  }
6419
6420
6421
6422  /**
6423   * Retrieves a string containing the specified number of randomly selected
6424   * ASCII numeric digits.
6425   *
6426   * @param  length  The number of digits to include in the string.  It must be
6427   *                 greater than or equal to zero.
6428   * @param  secure  Indicates whether to use a cryptographically secure random
6429   *                 number generator.
6430   *
6431   * @return  The randomly generated numeric string.
6432   */
6433  @NotNull()
6434  public static String randomNumericString(final int length,
6435                                           final boolean secure)
6436  {
6437    return randomString(length, NUMERIC_DIGITS, secure);
6438  }
6439
6440
6441
6442  /**
6443   * Retrieves a string containing the specified number of randomly selected
6444   * ASCII alphanumeric characters.  It may contain a mix of lowercase letters,
6445   * uppercase letters, and numeric digits.
6446   *
6447   * @param  length  The number of characters to include in the string.  It must
6448   *                 be greater than or equal to zero.
6449   * @param  secure  Indicates whether to use a cryptographically secure random
6450   *                 number generator.
6451   *
6452   * @return  The randomly generated alphanumeric string.
6453   */
6454  @NotNull()
6455  public static String randomAlphanumericString(final int length,
6456                                                final boolean secure)
6457  {
6458    return randomString(length, ALPHANUMERIC_CHARACTERS, secure);
6459  }
6460
6461
6462
6463  /**
6464   * Retrieves a string containing the specified number of randomly selected
6465   * characters from the given set.
6466   *
6467   * @param  length        The number of characters to include in the string.
6468   *                       It must be greater than or equal to zero.
6469   * @param  allowedChars  The set of characters that are allowed to be included
6470   *                       in the string.  It must not be {@code null} or
6471   *                       empty.
6472   * @param  secure        Indicates whether to use a cryptographically secure
6473   *                       random number generator.
6474   *
6475   * @return  The randomly generated string.
6476   */
6477  @NotNull()
6478  public static String randomString(final int length,
6479                                    @NotNull final char[] allowedChars,
6480                                    final boolean secure)
6481  {
6482    final StringBuilder buffer = new StringBuilder(length);
6483
6484    final Random random = getThreadLocalRandom(secure);
6485    for (int i=0; i < length; i++)
6486    {
6487      buffer.append(allowedChars[random.nextInt(allowedChars.length)]);
6488    }
6489
6490    return buffer.toString();
6491  }
6492
6493
6494
6495  /**
6496   * Retrieves a thread-local random number generator.
6497   *
6498   * @param  secure  Indicates whether to retrieve a cryptographically secure
6499   *                 random number generator.
6500   *
6501   * @return  The thread-local random number generator.
6502   */
6503  @NotNull()
6504  private static Random getThreadLocalRandom(final boolean secure)
6505  {
6506    if (secure)
6507    {
6508      return ThreadLocalSecureRandom.get();
6509    }
6510    else
6511    {
6512      return ThreadLocalRandom.get();
6513    }
6514  }
6515}