mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Yuriy Movchan
29.57.2022 a9bbf17ba3b41d3940efaeb98caf4da2ef344f23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2006-2009 Sun Microsystems, Inc.
 * Portions Copyright 2011-2015 ForgeRock AS.
 */
package org.opends.server.util;
 
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
 
import org.opends.server.api.DirectoryThread;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.server.schema.GeneralizedTimeSyntax;
 
/**
 * This class provides an application-wide timing service. It provides
 * the ability to retrieve the current time in various different formats
 * and resolutions.
 */
@org.opends.server.types.PublicAPI(
    stability = org.opends.server.types.StabilityLevel.UNCOMMITTED,
    mayInstantiate = false,
    mayExtend = false,
    mayInvoke = true)
public final class TimeThread
{
 
  /**
   * Timer job.
   */
  private static final class TimeInfo implements Runnable
  {
 
    /** The calendar holding the current time. */
    private GregorianCalendar calendar;
 
    /** The date for this time thread. */
    private Date date;
 
    /** The timestamp for this time thread in the generalized time format. */
    private String generalizedTime;
 
    /** The timestamp for this time thread in GMT. */
    private String gmtTimestamp;
 
    /** The date formatter that will be used to obtain the GMT timestamp. */
    private final SimpleDateFormat gmtTimestampFormatter;
 
    /** The current time in HHmm form as an integer. */
    private int hourAndMinute;
 
    /** The timestamp for this time thread in the local time zone. */
    private String localTimestamp;
 
    /** The date formatter that will be used to obtain the local timestamp. */
    private final SimpleDateFormat localTimestampFormatter;
 
    /** The current time in nanoseconds. */
    private volatile long nanoTime;
 
    /** The current time in milliseconds since the epoch. */
    private volatile long time;
 
    /**
     * A set of arbitrary formatters that should be maintained by this time
     * thread.
     */
    private final List<SimpleDateFormat> userDefinedFormatters;
 
    /**
     * A set of arbitrary formatted times, mapped from format string to the
     * corresponding formatted time representation.
     */
    private final Map<String, String> userDefinedTimeStrings;
 
 
 
    /**
     * Create a new job with the specified delay.
     */
    public TimeInfo()
    {
      userDefinedFormatters = new CopyOnWriteArrayList<>();
      userDefinedTimeStrings = new ConcurrentHashMap<>();
 
      TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
 
      gmtTimestampFormatter = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
      gmtTimestampFormatter.setTimeZone(utcTimeZone);
 
      localTimestampFormatter =
          new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z");
 
      // Populate initial values.
      run();
    }
 
 
 
    /** {@inheritDoc} */
    @Override
    public void run()
    {
      try
      {
        calendar = new GregorianCalendar();
        date = calendar.getTime();
        time = date.getTime();
        nanoTime = System.nanoTime();
        generalizedTime = GeneralizedTimeSyntax.format(date);
        localTimestamp = localTimestampFormatter.format(date);
        gmtTimestamp = gmtTimestampFormatter.format(date);
        hourAndMinute =
            calendar.get(Calendar.HOUR_OF_DAY) * 100
                + calendar.get(Calendar.MINUTE);
 
        for (SimpleDateFormat format : userDefinedFormatters)
        {
          userDefinedTimeStrings.put(format.toPattern(), format.format(date));
        }
      }
      catch (Exception e)
      {
        logger.traceException(e);
      }
    }
  }
 
  /**
   * Thread factory used by the scheduled execution service.
   */
  private static final class TimeThreadFactory implements
      ThreadFactory
  {
 
    /** {@inheritDoc} */
    @Override
    public Thread newThread(Runnable r)
    {
      Thread t = new DirectoryThread(r, "Time Thread");
      t.setDaemon(true);
      return t;
    }
 
  }
 
 
 
  /** The singleton instance. */
  private static TimeThread INSTANCE = new TimeThread();
 
  /** The tracer object for the debug logger. */
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
 
 
  /**
   * Retrieves a <CODE>Calendar</CODE> containing the time at the last
   * update.
   *
   * @return A <CODE>Calendar</CODE> containing the time at the last
   *         update.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static Calendar getCalendar() throws IllegalStateException
  {
    checkState();
    return INSTANCE.timeInfo.calendar;
  }
 
 
 
  /**
   * Retrieves a <CODE>Date</CODE> containing the time at the last
   * update.
   *
   * @return A <CODE>Date</CODE> containing the time at the last update.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static Date getDate() throws IllegalStateException
  {
    checkState();
    return INSTANCE.timeInfo.date;
  }
 
 
 
  /**
   * Retrieves a string containing a normalized representation of the
   * current time in a generalized time format. The timestamp will look
   * like "20050101000000.000Z".
   *
   * @return A string containing a normalized representation of the
   *         current time in a generalized time format.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static String getGeneralizedTime() throws IllegalStateException
  {
    checkState();
    return INSTANCE.timeInfo.generalizedTime;
  }
 
 
 
  /**
   * Retrieves a string containing the current time in GMT. The
   * timestamp will look like "20050101000000Z".
   *
   * @return A string containing the current time in GMT.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static String getGMTTime() throws IllegalStateException
  {
    checkState();
    return INSTANCE.timeInfo.gmtTimestamp;
  }
 
 
 
  /**
   * Retrieves an integer containing the time in HHmm format at the last
   * update. It will be calculated as "(hourOfDay*100) + minuteOfHour".
   *
   * @return An integer containing the time in HHmm format at the last
   *         update.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static int getHourAndMinute() throws IllegalStateException
  {
    checkState();
    return INSTANCE.timeInfo.hourAndMinute;
  }
 
 
 
  /**
   * Retrieves a string containing the current time in the local time
   * zone. The timestamp format will look like
   * "01/Jan/2005:00:00:00 -0600".
   *
   * @return A string containing the current time in the local time
   *         zone.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static String getLocalTime() throws IllegalStateException
  {
    checkState();
    return INSTANCE.timeInfo.localTimestamp;
  }
 
 
 
  /**
   * Retrieves the time in nanoseconds from the most precise available system
   * timer. The value returned represents nanoseconds since some fixed but
   * arbitrary time.
   *
   * @return The time in nanoseconds from some fixed but arbitrary time.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static long getNanoTime() throws IllegalStateException
  {
    checkState();
    return INSTANCE.timeInfo.nanoTime;
  }
 
 
 
  /**
   * Retrieves the time in milliseconds since the epoch at the last
   * update.
   *
   * @return The time in milliseconds since the epoch at the last
   *         update.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static long getTime() throws IllegalStateException
  {
    checkState();
    return INSTANCE.timeInfo.time;
  }
 
 
 
  /**
   * Retrieves the current time formatted using the given format string.
   * <p>
   * The first time this method is used with a given format string, it
   * will be used to create a formatter that will generate the time
   * string. That formatter will then be put into a list so that it will
   * be maintained automatically for future use.
   *
   * @param formatString
   *          The string that defines the format of the time string to
   *          retrieve.
   * @return The formatted time string.
   * @throws IllegalArgumentException
   *           If the provided format string is invalid.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static String getUserDefinedTime(String formatString)
      throws IllegalArgumentException, IllegalStateException
  {
    checkState();
 
    String timeString =
        INSTANCE.timeInfo.userDefinedTimeStrings.get(formatString);
 
    if (timeString == null)
    {
      SimpleDateFormat formatter = new SimpleDateFormat(formatString);
      timeString = formatter.format(INSTANCE.timeInfo.date);
      INSTANCE.timeInfo.userDefinedTimeStrings.put(formatString,
          timeString);
      INSTANCE.timeInfo.userDefinedFormatters.add(formatter);
    }
 
    return timeString;
  }
 
 
 
  /**
   * Removes the user-defined time formatter from this time thread so
   * that it will no longer be maintained. This is a safe operation
   * because if the same format string is used for multiple purposes
   * then it will be added back the next time a time is requested with
   * the given format.
   *
   * @param formatString
   *          The format string for the date formatter to remove.
   * @throws IllegalStateException
   *           If the time service has not been started.
   */
  public static void removeUserDefinedFormatter(String formatString)
    throws IllegalStateException
  {
    checkState();
 
    INSTANCE.timeInfo.userDefinedFormatters.remove(new SimpleDateFormat(
        formatString));
    INSTANCE.timeInfo.userDefinedTimeStrings.remove(formatString);
  }
 
 
 
  /**
   * Starts the time service if it has not already been started.
   */
  public static void start()
  {
    if (INSTANCE == null)
    {
      INSTANCE = new TimeThread();
    }
  }
 
 
 
  /**
   * Stops the time service if it has not already been stopped.
   */
  public static void stop()
  {
    if (INSTANCE != null)
    {
      INSTANCE.scheduler.shutdown();
      INSTANCE = null;
    }
  }
 
 
 
  /** Ensures that the time service has been started. */
  private static void checkState() throws IllegalStateException
  {
    if (INSTANCE == null)
    {
      throw new IllegalStateException("Time service not started");
    }
  }
 
 
 
  /** The scheduler. */
  private final ScheduledExecutorService scheduler =
      Executors.newSingleThreadScheduledExecutor(new TimeThreadFactory());
 
  /** The current time information. */
  private final TimeInfo timeInfo = new TimeInfo();
 
 
 
  /**
   * Creates a new instance of this time service and starts it.
   */
  private TimeThread()
  {
    this.scheduler.scheduleWithFixedDelay(timeInfo, 0, 200,
        TimeUnit.MILLISECONDS);
  }
}