001/*
002 * Copyright 2017-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2017-2024 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) 2017-2024 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.asn1;
037
038
039
040import com.unboundid.util.Debug;
041import com.unboundid.util.NotMutable;
042import com.unboundid.util.NotNull;
043import com.unboundid.util.Nullable;
044import com.unboundid.util.StaticUtils;
045import com.unboundid.util.ThreadSafety;
046import com.unboundid.util.ThreadSafetyLevel;
047
048import static com.unboundid.asn1.ASN1Messages.*;
049
050
051
052/**
053 * This class provides an ASN.1 numeric string element that can hold any
054 * empty or non-empty string comprised only of the ASCII numeric digits '0'
055 * through '9' and the ASCII space.
056 */
057@NotMutable()
058@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
059public final class ASN1NumericString
060       extends ASN1Element
061{
062  /**
063   * The serial version UID for this serializable class.
064   */
065  private static final long serialVersionUID = -3972798266250943461L;
066
067
068
069  // The string value for this element.
070  @NotNull private final String stringValue;
071
072
073
074  /**
075   * Creates a new ASN.1 numeric string element with the default BER type and
076   * the provided value.
077   *
078   * @param  stringValue  The string value to use for this element.  It may be
079   *                      {@code null} or empty if the value should be empty.
080   *                      It must only contain ASCII digit and space characters.
081   *
082   * @throws  ASN1Exception  If the provided string does not represent a valid
083   *                         numeric string.
084   */
085  public ASN1NumericString(@Nullable final String stringValue)
086         throws ASN1Exception
087  {
088    this(ASN1Constants.UNIVERSAL_NUMERIC_STRING_TYPE, stringValue);
089  }
090
091
092
093  /**
094   * Creates a new ASN.1 numeric string element with the specified BER type
095   * and the provided value.
096   *
097   * @param  type         The BER type for this element.
098   * @param  stringValue  The string value to use for this element.  It may be
099   *                      {@code null} or empty if the value should be empty.
100   *                      It must only contain ASCII digit and space characters.
101   *
102   * @throws  ASN1Exception  If the provided string does not represent a valid
103   *                         numeric string.
104   */
105  public ASN1NumericString(final byte type,
106                           @Nullable final String stringValue)
107         throws ASN1Exception
108  {
109    this(type, stringValue, StaticUtils.getBytes(stringValue));
110  }
111
112
113
114  /**
115   * Creates a new ASN.1 numeric string element with the specified BER type
116   * and the provided value.
117   *
118   * @param  type          The BER type for this element.
119   * @param  stringValue   The string value to use for this element.  It may be
120   *                       {@code null} or empty if the value should be empty.
121   *                       It must only contain ASCII digit and space
122   *                       characters.
123   * @param  encodedValue  The bytes that comprise the encoded element value.
124   *
125   * @throws  ASN1Exception  If the provided string does not represent a valid
126   *                         numeric string.
127   */
128  private ASN1NumericString(final byte type,
129                            @Nullable final String stringValue,
130                            @NotNull final byte[] encodedValue)
131          throws ASN1Exception
132  {
133    super(type, encodedValue);
134
135    if (stringValue == null)
136    {
137      this.stringValue = "";
138    }
139    else
140    {
141      this.stringValue = stringValue;
142      for (final char c : stringValue.toCharArray())
143      {
144        if ((c >= '0') && (c <= '9'))
145        {
146          // ASCII digits are allowed in numeric strings.
147        }
148        else if (c == ' ')
149        {
150          // The space is allowed in numeric strings.
151        }
152        else
153        {
154          throw new ASN1Exception(
155               ERR_NUMERIC_STRING_DECODE_VALUE_NOT_NUMERIC.get());
156        }
157      }
158    }
159  }
160
161
162
163  /**
164   * Retrieves the string value for this element.
165   *
166   * @return  The string value for this element.
167   */
168  @NotNull()
169  public String stringValue()
170  {
171    return stringValue;
172  }
173
174
175
176  /**
177   * Decodes the contents of the provided byte array as a numeric string
178   * element.
179   *
180   * @param  elementBytes  The byte array to decode as an ASN.1 numeric string
181   *                       element.
182   *
183   * @return  The decoded ASN.1 numeric string element.
184   *
185   * @throws  ASN1Exception  If the provided array cannot be decoded as a
186   *                         numeric string element.
187   */
188  @NotNull()
189  public static ASN1NumericString decodeAsNumericString(
190                                       @NotNull final byte[] elementBytes)
191         throws ASN1Exception
192  {
193    try
194    {
195      int valueStartPos = 2;
196      int length = (elementBytes[1] & 0x7F);
197      if (length != elementBytes[1])
198      {
199        final int numLengthBytes = length;
200
201        length = 0;
202        for (int i=0; i < numLengthBytes; i++)
203        {
204          length <<= 8;
205          length |= (elementBytes[valueStartPos++] & 0xFF);
206        }
207      }
208
209      if ((elementBytes.length - valueStartPos) != length)
210      {
211        throw new ASN1Exception(ERR_ELEMENT_LENGTH_MISMATCH.get(length,
212                                     (elementBytes.length - valueStartPos)));
213      }
214
215      final byte[] elementValue = new byte[length];
216      System.arraycopy(elementBytes, valueStartPos, elementValue, 0, length);
217
218      return new ASN1NumericString(elementBytes[0],
219           StaticUtils.toUTF8String(elementValue), elementValue);
220    }
221    catch (final ASN1Exception ae)
222    {
223      Debug.debugException(ae);
224      throw ae;
225    }
226    catch (final Exception e)
227    {
228      Debug.debugException(e);
229      throw new ASN1Exception(ERR_ELEMENT_DECODE_EXCEPTION.get(e), e);
230    }
231  }
232
233
234
235  /**
236   * Decodes the provided ASN.1 element as a numeric string element.
237   *
238   * @param  element  The ASN.1 element to be decoded.
239   *
240   * @return  The decoded ASN.1 numeric string element.
241   *
242   * @throws  ASN1Exception  If the provided element cannot be decoded as a
243   *                         numeric string element.
244   */
245  @NotNull()
246  public static ASN1NumericString decodeAsNumericString(
247                                       @NotNull final ASN1Element element)
248         throws ASN1Exception
249  {
250    final byte[] elementValue = element.getValue();
251    return new ASN1NumericString(element.getType(),
252         StaticUtils.toUTF8String(elementValue), elementValue);
253  }
254
255
256
257  /**
258   * {@inheritDoc}
259   */
260  @Override()
261  public void toString(@NotNull final StringBuilder buffer)
262  {
263    buffer.append(stringValue);
264  }
265}