001/*
002 * Copyright 2016-2023 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2016-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) 2016-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.args;
037
038
039
040import java.text.ParseException;
041import java.text.SimpleDateFormat;
042import java.util.ArrayList;
043import java.util.Date;
044import java.util.Collections;
045import java.util.Iterator;
046import java.util.List;
047
048import com.unboundid.util.Debug;
049import com.unboundid.util.Mutable;
050import com.unboundid.util.NotNull;
051import com.unboundid.util.Nullable;
052import com.unboundid.util.ObjectPair;
053import com.unboundid.util.StaticUtils;
054import com.unboundid.util.ThreadSafety;
055import com.unboundid.util.ThreadSafetyLevel;
056
057import static com.unboundid.util.args.ArgsMessages.*;
058
059
060
061/**
062 * This class defines an argument that is intended to hold one or more
063 * timestamp values.  Values may be provided in any of the following formats:
064 * <UL>
065 *   <LI>Any valid generalized time format.</LI>
066 *   <LI>A local time zone timestamp in the format YYYYMMDDhhmmss.uuu</LI>
067 *   <LI>A local time zone timestamp in the format YYYYMMDDhhmmss</LI>
068 *   <LI>A local time zone timestamp in the format YYYYMMDDhhmm</LI>
069 * </UL>
070 */
071@Mutable()
072@ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE)
073public final class TimestampArgument
074       extends Argument
075{
076  /**
077   * The serial version UID for this serializable class.
078   */
079  private static final long serialVersionUID = -4842934851103696096L;
080
081
082
083  // The argument value validators that have been registered for this argument.
084  @NotNull private final List<ArgumentValueValidator> validators;
085
086  // The list of default values for this argument.
087  @Nullable private final List<Date> defaultValues;
088
089  // The set of values assigned to this argument.
090  @NotNull private final List<ObjectPair<Date,String>> values;
091
092
093
094  /**
095   * Creates a new timestamp argument with the provided information.  It will
096   * not be required, will permit at most one occurrence, will use a default
097   * placeholder, and will not have a default value.
098   *
099   * @param  shortIdentifier   The short identifier for this argument.  It may
100   *                           not be {@code null} if the long identifier is
101   *                           {@code null}.
102   * @param  longIdentifier    The long identifier for this argument.  It may
103   *                           not be {@code null} if the short identifier is
104   *                           {@code null}.
105   * @param  description       A human-readable description for this argument.
106   *                           It must not be {@code null}.
107   *
108   * @throws  ArgumentException  If there is a problem with the definition of
109   *                             this argument.
110   */
111  public TimestampArgument(@Nullable final Character shortIdentifier,
112                           @Nullable final String longIdentifier,
113                           @NotNull final String description)
114         throws ArgumentException
115  {
116    this(shortIdentifier, longIdentifier, false, 1, null, description);
117  }
118
119
120
121  /**
122   * Creates a new timestamp argument with the provided information.  It will
123   * not have a default value.
124   *
125   * @param  shortIdentifier   The short identifier for this argument.  It may
126   *                           not be {@code null} if the long identifier is
127   *                           {@code null}.
128   * @param  longIdentifier    The long identifier for this argument.  It may
129   *                           not be {@code null} if the short identifier is
130   *                           {@code null}.
131   * @param  isRequired        Indicates whether this argument is required to
132   *                           be provided.
133   * @param  maxOccurrences    The maximum number of times this argument may be
134   *                           provided on the command line.  A value less than
135   *                           or equal to zero indicates that it may be present
136   *                           any number of times.
137   * @param  valuePlaceholder  A placeholder to display in usage information to
138   *                           indicate that a value must be provided.  It may
139   *                           be {@code null} if a default placeholder should
140   *                           be used.
141   * @param  description       A human-readable description for this argument.
142   *                           It must not be {@code null}.
143   *
144   * @throws  ArgumentException  If there is a problem with the definition of
145   *                             this argument.
146   */
147  public TimestampArgument(@Nullable final Character shortIdentifier,
148                           @Nullable final String longIdentifier,
149                           final boolean isRequired, final int maxOccurrences,
150                           @Nullable final String valuePlaceholder,
151                           @NotNull final String description)
152         throws ArgumentException
153  {
154    this(shortIdentifier, longIdentifier, isRequired,  maxOccurrences,
155         valuePlaceholder, description, (List<Date>) null);
156  }
157
158
159
160  /**
161   * Creates a new timestamp argument with the provided information.
162   *
163   * @param  shortIdentifier   The short identifier for this argument.  It may
164   *                           not be {@code null} if the long identifier is
165   *                           {@code null}.
166   * @param  longIdentifier    The long identifier for this argument.  It may
167   *                           not be {@code null} if the short identifier is
168   *                           {@code null}.
169   * @param  isRequired        Indicates whether this argument is required to
170   *                           be provided.
171   * @param  maxOccurrences    The maximum number of times this argument may be
172   *                           provided on the command line.  A value less than
173   *                           or equal to zero indicates that it may be present
174   *                           any number of times.
175   * @param  valuePlaceholder  A placeholder to display in usage information to
176   *                           indicate that a value must be provided.  It may
177   *                           be {@code null} if a default placeholder should
178   *                           be used.
179   * @param  description       A human-readable description for this argument.
180   *                           It must not be {@code null}.
181   * @param  defaultValue      The default value to use for this argument if no
182   *                           values were provided.
183   *
184   * @throws  ArgumentException  If there is a problem with the definition of
185   *                             this argument.
186   */
187  public TimestampArgument(@Nullable final Character shortIdentifier,
188                           @Nullable final String longIdentifier,
189                           final boolean isRequired, final int maxOccurrences,
190                           @Nullable final String valuePlaceholder,
191                           @NotNull final String description,
192                           @Nullable final Date defaultValue)
193         throws ArgumentException
194  {
195    this(shortIdentifier, longIdentifier, isRequired, maxOccurrences,
196         valuePlaceholder, description,
197         ((defaultValue == null)
198              ? null
199              : Collections.singletonList(defaultValue)));
200  }
201
202
203
204  /**
205   * Creates a new timestamp argument with the provided information.
206   *
207   * @param  shortIdentifier   The short identifier for this argument.  It may
208   *                           not be {@code null} if the long identifier is
209   *                           {@code null}.
210   * @param  longIdentifier    The long identifier for this argument.  It may
211   *                           not be {@code null} if the short identifier is
212   *                           {@code null}.
213   * @param  isRequired        Indicates whether this argument is required to
214   *                           be provided.
215   * @param  maxOccurrences    The maximum number of times this argument may be
216   *                           provided on the command line.  A value less than
217   *                           or equal to zero indicates that it may be present
218   *                           any number of times.
219   * @param  valuePlaceholder  A placeholder to display in usage information to
220   *                           indicate that a value must be provided.  It may
221   *                           be {@code null} if a default placeholder should
222   *                           be used.
223   * @param  description       A human-readable description for this argument.
224   *                           It must not be {@code null}.
225   * @param  defaultValues     The set of default values to use for this
226   *                           argument if no values were provided.
227   *
228   * @throws  ArgumentException  If there is a problem with the definition of
229   *                             this argument.
230   */
231  public TimestampArgument(@Nullable final Character shortIdentifier,
232                           @Nullable final String longIdentifier,
233                           final boolean isRequired, final int maxOccurrences,
234                           @Nullable final String valuePlaceholder,
235                           @NotNull final String description,
236                           @Nullable final List<Date> defaultValues)
237         throws ArgumentException
238  {
239    super(shortIdentifier, longIdentifier, isRequired,  maxOccurrences,
240         (valuePlaceholder == null)
241              ? INFO_PLACEHOLDER_TIMESTAMP.get()
242              : valuePlaceholder,
243         description);
244
245    if ((defaultValues == null) || defaultValues.isEmpty())
246    {
247      this.defaultValues = null;
248    }
249    else
250    {
251      this.defaultValues = Collections.unmodifiableList(defaultValues);
252    }
253
254    values = new ArrayList<>(5);
255    validators = new ArrayList<>(5);
256  }
257
258
259
260  /**
261   * Creates a new timestamp argument that is a "clean" copy of the provided
262   * source argument.
263   *
264   * @param  source  The source argument to use for this argument.
265   */
266  private TimestampArgument(@NotNull final TimestampArgument source)
267  {
268    super(source);
269
270    defaultValues = source.defaultValues;
271    values        = new ArrayList<>(5);
272    validators    = new ArrayList<>(source.validators);
273  }
274
275
276
277  /**
278   * Retrieves the list of default values for this argument, which will be used
279   * if no values were provided.
280   *
281   * @return   The list of default values for this argument, or {@code null} if
282   *           there are no default values.
283   */
284  @Nullable()
285  public List<Date> getDefaultValues()
286  {
287    return defaultValues;
288  }
289
290
291
292  /**
293   * Updates this argument to ensure that the provided validator will be invoked
294   * for any values provided to this argument.  This validator will be invoked
295   * after all other validation has been performed for this argument.
296   *
297   * @param  validator  The argument value validator to be invoked.  It must not
298   *                    be {@code null}.
299   */
300  public void addValueValidator(@NotNull final ArgumentValueValidator validator)
301  {
302    validators.add(validator);
303  }
304
305
306
307  /**
308   * {@inheritDoc}
309   */
310  @Override()
311  protected void addValue(@NotNull final String valueString)
312            throws ArgumentException
313  {
314    final Date d;
315    try
316    {
317      d = parseTimestamp(valueString);
318    }
319    catch (final Exception e)
320    {
321      Debug.debugException(e);
322      throw new ArgumentException(
323           ERR_TIMESTAMP_VALUE_NOT_TIMESTAMP.get(valueString,
324                getIdentifierString()),
325           e);
326    }
327
328
329    if (values.size() >= getMaxOccurrences())
330    {
331      throw new ArgumentException(ERR_ARG_MAX_OCCURRENCES_EXCEEDED.get(
332                                       getIdentifierString()));
333    }
334
335    for (final ArgumentValueValidator v : validators)
336    {
337      v.validateArgumentValue(this, valueString);
338    }
339
340    values.add(new ObjectPair<>(d, valueString));
341  }
342
343
344
345  /**
346   * Parses the provided string as a timestamp using one of the supported
347   * formats.
348   *
349   * @param  s  The string to parse as a timestamp.  It must not be
350   *            {@code null}.
351   *
352   * @return  The {@code Date} object parsed from the provided timestamp.
353   *
354   * @throws  ParseException  If the provided string cannot be parsed as a
355   *                          timestamp.
356   */
357  @NotNull()
358  public static Date parseTimestamp(@NotNull final String s)
359         throws ParseException
360  {
361    // First, try to parse the value as a generalized time.
362    try
363    {
364      return StaticUtils.decodeGeneralizedTime(s);
365    }
366    catch (final Exception e)
367    {
368      // This is fine.  It just means the value isn't in the generalized time
369      // format.
370    }
371
372
373    // See if the length of the string matches one of the supported local
374    // formats.  If so, get a format string that we can use to parse the value.
375    final String dateFormatString;
376    switch (s.length())
377    {
378      case 18:
379        dateFormatString = "yyyyMMddHHmmss.SSS";
380        break;
381      case 14:
382        dateFormatString = "yyyyMMddHHmmss";
383        break;
384      case 12:
385        dateFormatString = "yyyyMMddHHmm";
386        break;
387      default:
388        throw new ParseException(ERR_TIMESTAMP_PARSE_ERROR.get(s), 0);
389    }
390
391
392    // Create a date formatter that will use the selected format string to parse
393    // the timestamp.
394    final SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
395    dateFormat.setLenient(false);
396    return dateFormat.parse(s);
397  }
398
399
400
401  /**
402   * Retrieves the value for this argument, or the default value if none was
403   * provided.  If there are multiple values, then the first will be returned.
404   *
405   * @return  The value for this argument, or the default value if none was
406   *          provided, or {@code null} if there is no value and no default
407   *          value.
408   */
409  @Nullable()
410  public Date getValue()
411  {
412    if (values.isEmpty())
413    {
414      if ((defaultValues == null) || defaultValues.isEmpty())
415      {
416        return null;
417      }
418      else
419      {
420        return defaultValues.get(0);
421      }
422    }
423    else
424    {
425      return values.get(0).getFirst();
426    }
427  }
428
429
430
431  /**
432   * Retrieves the set of values for this argument.
433   *
434   * @return  The set of values for this argument.
435   */
436  @NotNull()
437  public List<Date> getValues()
438  {
439    if (values.isEmpty() && (defaultValues != null))
440    {
441      return defaultValues;
442    }
443
444    final ArrayList<Date> dateList = new ArrayList<>(values.size());
445    for (final ObjectPair<Date,String> p : values)
446    {
447      dateList.add(p.getFirst());
448    }
449
450    return Collections.unmodifiableList(dateList);
451  }
452
453
454
455  /**
456   * Retrieves a string representation of the value for this argument, or a
457   * string representation of the default value if none was provided.  If there
458   * are multiple values, then the first will be returned.
459   *
460   * @return  The string representation of the value for this argument, or the
461   *          string representation of the default value if none was provided,
462   *          or {@code null} if there is no value and no default value.
463   */
464  @Nullable()
465  public String getStringValue()
466  {
467    if (! values.isEmpty())
468    {
469      return values.get(0).getSecond();
470    }
471
472    if ((defaultValues != null) && (! defaultValues.isEmpty()))
473    {
474      return StaticUtils.encodeGeneralizedTime(defaultValues.get(0));
475    }
476
477    return null;
478  }
479
480
481
482  /**
483   * {@inheritDoc}
484   */
485  @Override()
486  @NotNull()
487  public List<String> getValueStringRepresentations(final boolean useDefault)
488  {
489    if (! values.isEmpty())
490    {
491      final ArrayList<String> valueStrings = new ArrayList<>(values.size());
492      for (final ObjectPair<Date,String> p : values)
493      {
494        valueStrings.add(p.getSecond());
495      }
496
497      return Collections.unmodifiableList(valueStrings);
498    }
499
500    if (useDefault && (defaultValues != null) && (! defaultValues.isEmpty()))
501    {
502      final ArrayList<String> valueStrings =
503           new ArrayList<>(defaultValues.size());
504      for (final Date d : defaultValues)
505      {
506        valueStrings.add(StaticUtils.encodeGeneralizedTime(d));
507      }
508
509      return Collections.unmodifiableList(valueStrings);
510    }
511
512    return Collections.emptyList();
513  }
514
515
516
517  /**
518   * {@inheritDoc}
519   */
520  @Override()
521  protected boolean hasDefaultValue()
522  {
523    return ((defaultValues != null) && (! defaultValues.isEmpty()));
524  }
525
526
527
528  /**
529   * {@inheritDoc}
530   */
531  @Override()
532  @NotNull()
533  public String getDataTypeName()
534  {
535    return INFO_TIMESTAMP_TYPE_NAME.get();
536  }
537
538
539
540  /**
541   * {@inheritDoc}
542   */
543  @Override()
544  @NotNull()
545  public String getValueConstraints()
546  {
547    return INFO_TIMESTAMP_CONSTRAINTS.get();
548  }
549
550
551
552  /**
553   * {@inheritDoc}
554   */
555  @Override()
556  protected void reset()
557  {
558    super.reset();
559    values.clear();
560  }
561
562
563
564  /**
565   * {@inheritDoc}
566   */
567  @Override()
568  @NotNull()
569  public TimestampArgument getCleanCopy()
570  {
571    return new TimestampArgument(this);
572  }
573
574
575
576  /**
577   * {@inheritDoc}
578   */
579  @Override()
580  protected void addToCommandLine(@NotNull final List<String> argStrings)
581  {
582    for (final ObjectPair<Date,String> p : values)
583    {
584      argStrings.add(getIdentifierString());
585      if (isSensitive())
586      {
587        argStrings.add("***REDACTED***");
588      }
589      else
590      {
591        argStrings.add(p.getSecond());
592      }
593    }
594  }
595
596
597
598  /**
599   * {@inheritDoc}
600   */
601  @Override()
602  public void toString(@NotNull final StringBuilder buffer)
603  {
604    buffer.append("TimestampArgument(");
605    appendBasicToStringInfo(buffer);
606
607    if ((defaultValues != null) && (! defaultValues.isEmpty()))
608    {
609      if (defaultValues.size() == 1)
610      {
611        buffer.append(", defaultValue='");
612        buffer.append(StaticUtils.encodeGeneralizedTime(defaultValues.get(0)));
613      }
614      else
615      {
616        buffer.append(", defaultValues={");
617
618        final Iterator<Date> iterator = defaultValues.iterator();
619        while (iterator.hasNext())
620        {
621          buffer.append('\'');
622          buffer.append(StaticUtils.encodeGeneralizedTime(iterator.next()));
623          buffer.append('\'');
624
625          if (iterator.hasNext())
626          {
627            buffer.append(", ");
628          }
629        }
630
631        buffer.append('}');
632      }
633    }
634
635    buffer.append(')');
636  }
637}