001/*
002 * Copyright 2015-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2015-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) 2015-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.ldap.sdk.unboundidds.extensions;
037
038
039
040import java.util.ArrayList;
041import java.util.Collection;
042import java.util.Collections;
043import java.util.Iterator;
044import java.util.List;
045
046import com.unboundid.asn1.ASN1Boolean;
047import com.unboundid.asn1.ASN1Element;
048import com.unboundid.asn1.ASN1OctetString;
049import com.unboundid.asn1.ASN1Sequence;
050import com.unboundid.ldap.sdk.Control;
051import com.unboundid.ldap.sdk.ExtendedResult;
052import com.unboundid.ldap.sdk.LDAPException;
053import com.unboundid.ldap.sdk.ResultCode;
054import com.unboundid.util.Debug;
055import com.unboundid.util.NotMutable;
056import com.unboundid.util.NotNull;
057import com.unboundid.util.Nullable;
058import com.unboundid.util.StaticUtils;
059import com.unboundid.util.ThreadSafety;
060import com.unboundid.util.ThreadSafetyLevel;
061
062import static com.unboundid.ldap.sdk.unboundidds.extensions.ExtOpMessages.*;
063
064
065
066/**
067 * This class provides an implementation of an extended result that may be used
068 * to provide information about which one-time password delivery mechanisms are
069 * supported for a user.
070 * <BR>
071 * <BLOCKQUOTE>
072 *   <B>NOTE:</B>  This class, and other classes within the
073 *   {@code com.unboundid.ldap.sdk.unboundidds} package structure, are only
074 *   supported for use against Ping Identity, UnboundID, and
075 *   Nokia/Alcatel-Lucent 8661 server products.  These classes provide support
076 *   for proprietary functionality or for external specifications that are not
077 *   considered stable or mature enough to be guaranteed to work in an
078 *   interoperable way with other types of LDAP servers.
079 * </BLOCKQUOTE>
080 * <BR>
081 * If the request was processed successfully, then the extended result will have
082 * an OID of 1.3.6.1.4.1.30221.2.6.48 and a value with the following encoding:
083 * <BR><BR>
084 * <PRE>
085 *   GetSupportedOTPDeliveryMechanismsResult ::= SEQUENCE OF SEQUENCE {
086 *        deliveryMechanism     [0] OCTET STRING,
087 *        isSupported           [1] BOOLEAN OPTIONAL,
088 *        recipientID           [2] OCTET STRING OPTIONAL,
089 *        ... }
090 * </PRE>
091 *
092 * @see  GetSupportedOTPDeliveryMechanismsExtendedRequest
093 */
094@NotMutable()
095@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
096public final class GetSupportedOTPDeliveryMechanismsExtendedResult
097       extends ExtendedResult
098{
099  /**
100   * The OID (1.3.6.1.4.1.30221.2.6.48) for the get supported one-time password
101   * delivery mechanisms extended result.
102   */
103  @NotNull public static final String
104       GET_SUPPORTED_OTP_DELIVERY_MECHANISMS_RESULT_OID =
105            "1.3.6.1.4.1.30221.2.6.48";
106
107
108
109  /**
110   * The BER type for the delivery mechanism element.
111   */
112  private static final byte TYPE_DELIVERY_MECHANISM = (byte) 0x80;
113
114
115
116  /**
117   * The BER type for the is supported element.
118   */
119  private static final byte TYPE_IS_SUPPORTED = (byte) 0x81;
120
121
122
123  /**
124   * The BER type for the recipient ID element.
125   */
126  private static final byte TYPE_RECIPIENT_ID = (byte) 0x82;
127
128
129
130  /**
131   * The serial version UID for this serializable class.
132   */
133  private static final long serialVersionUID = -1811121368502797059L;
134
135
136
137  // The list of supported delivery mechanism information for this result.
138  @NotNull private final List<SupportedOTPDeliveryMechanismInfo>
139       deliveryMechanismInfo;
140
141
142
143  /**
144   * Decodes the provided extended result as a get supported OTP delivery
145   * mechanisms result.
146   *
147   * @param  result  The extended result to decode as a get supported OTP
148   *                 delivery mechanisms result.
149   *
150   * @throws  LDAPException  If the provided extended result cannot be decoded
151   *                         as a get supported OTP delivery mechanisms result.
152   */
153  public GetSupportedOTPDeliveryMechanismsExtendedResult(
154              @NotNull final ExtendedResult result)
155         throws LDAPException
156  {
157    super(result);
158
159    final ASN1OctetString value = result.getValue();
160    if (value == null)
161    {
162      deliveryMechanismInfo = Collections.emptyList();
163    }
164    else
165    {
166      try
167      {
168        final ASN1Element[] elements =
169             ASN1Sequence.decodeAsSequence(value.getValue()).elements();
170        final ArrayList<SupportedOTPDeliveryMechanismInfo> mechInfo =
171             new ArrayList<>(elements.length);
172        for (final ASN1Element e : elements)
173        {
174          final ASN1Element[] infoElements =
175               ASN1Sequence.decodeAsSequence(e).elements();
176          final String name = ASN1OctetString.decodeAsOctetString(
177               infoElements[0]).stringValue();
178
179          Boolean isSupported = null;
180          String recipientID = null;
181          for (int i=1; i < infoElements.length; i++)
182          {
183            switch (infoElements[i].getType())
184            {
185              case TYPE_IS_SUPPORTED:
186                isSupported = ASN1Boolean.decodeAsBoolean(
187                     infoElements[i]).booleanValue();
188                break;
189
190              case TYPE_RECIPIENT_ID:
191                recipientID = ASN1OctetString.decodeAsOctetString(
192                     infoElements[i]).stringValue();
193                break;
194
195              default:
196                throw new LDAPException(ResultCode.DECODING_ERROR,
197                     ERR_GET_SUPPORTED_OTP_MECH_RESULT_UNKNOWN_ELEMENT.get(
198                          StaticUtils.toHex(infoElements[i].getType())));
199            }
200          }
201
202          mechInfo.add(new SupportedOTPDeliveryMechanismInfo(name, isSupported,
203               recipientID));
204        }
205
206        deliveryMechanismInfo = Collections.unmodifiableList(mechInfo);
207      }
208      catch (final LDAPException le)
209      {
210        Debug.debugException(le);
211        throw le;
212      }
213      catch (final Exception e)
214      {
215        Debug.debugException(e);
216        throw new LDAPException(ResultCode.DECODING_ERROR,
217             ERR_GET_SUPPORTED_OTP_MECH_RESULT_CANNOT_DECODE.get(
218                  StaticUtils.getExceptionMessage(e)),
219             e);
220      }
221    }
222  }
223
224
225
226  /**
227   * Creates a new get supported OTP delivery mechanisms extended result object
228   * with the provided information.
229   *
230   * @param  messageID              The message ID for the LDAP message that is
231   *                                associated with this LDAP result.
232   * @param  resultCode             The result code from the response.  It must
233   *                                not be {@code null}.
234   * @param  diagnosticMessage      The diagnostic message from the response, if
235   *                                available.
236   * @param  matchedDN              The matched DN from the response, if
237   *                                available.
238   * @param  referralURLs           The set of referral URLs from the response,
239   *                                if available.
240   * @param  deliveryMechanismInfo  The set of supported delivery mechanism info
241   *                                for the result, if appropriate.  It should
242   *                                be {@code null} or empty for non-success
243   *                                results.
244   * @param  controls               The set of controls for the response.  It
245   *                                may be {@code null} or empty if no controls
246   *                                are needed.
247   */
248  public GetSupportedOTPDeliveryMechanismsExtendedResult(final int messageID,
249       @NotNull final ResultCode resultCode,
250       @Nullable final String diagnosticMessage,
251       @Nullable final String matchedDN,
252       @Nullable final String[] referralURLs,
253       @Nullable final Collection<SupportedOTPDeliveryMechanismInfo>
254            deliveryMechanismInfo,
255       @Nullable final Control... controls)
256  {
257    super(messageID, resultCode, diagnosticMessage, matchedDN, referralURLs,
258         (resultCode == ResultCode.SUCCESS ?
259              GET_SUPPORTED_OTP_DELIVERY_MECHANISMS_RESULT_OID : null),
260         encodeValue(resultCode, deliveryMechanismInfo), controls);
261
262    if ((deliveryMechanismInfo == null) || deliveryMechanismInfo.isEmpty())
263    {
264      this.deliveryMechanismInfo = Collections.emptyList();
265    }
266    else
267    {
268      this.deliveryMechanismInfo = Collections.unmodifiableList(
269           new ArrayList<>(deliveryMechanismInfo));
270    }
271  }
272
273
274
275  /**
276   * Encodes the provided information into an appropriate format for the value
277   * of this extended operation.
278   *
279   * @param  resultCode             The result code from the response.  It must
280   *                                not be {@code null}.
281   * @param  deliveryMechanismInfo  The set of supported delivery mechanism info
282   *                                for the result, if appropriate.  It should
283   *                                be {@code null} or empty for non-success
284   *                                results.
285   *
286   * @return  The ASN.1 octet string containing the encoded value.
287   */
288  @Nullable()
289  private static ASN1OctetString encodeValue(
290               @NotNull final ResultCode resultCode,
291               @Nullable final Collection<SupportedOTPDeliveryMechanismInfo>
292                    deliveryMechanismInfo)
293
294  {
295    if (resultCode != ResultCode.SUCCESS)
296    {
297      return null;
298    }
299
300    if ((deliveryMechanismInfo == null) || deliveryMechanismInfo.isEmpty())
301    {
302      return new ASN1OctetString(new ASN1Sequence().encode());
303    }
304
305    final ArrayList<ASN1Element> elements =
306         new ArrayList<>(deliveryMechanismInfo.size());
307    for (final SupportedOTPDeliveryMechanismInfo i : deliveryMechanismInfo)
308    {
309      final ArrayList<ASN1Element> infoElements = new ArrayList<>(3);
310      infoElements.add(new ASN1OctetString(TYPE_DELIVERY_MECHANISM,
311           i.getDeliveryMechanism()));
312
313      if (i.isSupported() != null)
314      {
315        infoElements.add(new ASN1Boolean(TYPE_IS_SUPPORTED, i.isSupported()));
316      }
317
318      if (i.getRecipientID() != null)
319      {
320        infoElements.add(new ASN1OctetString(TYPE_RECIPIENT_ID,
321             i.getRecipientID()));
322      }
323
324      elements.add(new ASN1Sequence(infoElements));
325    }
326
327    return new ASN1OctetString(new ASN1Sequence(elements).encode());
328  }
329
330
331
332  /**
333   * Retrieves a list containing information about the OTP delivery mechanisms
334   * supported by the server and which are available for use by the target user,
335   * if available.  Note that it is possible for the same OTP delivery mechanism
336   * to appear in the list multiple times if that mechanism is supported for the
337   * user with multiple recipient IDs (e.g., if the server provides an "Email"
338   * delivery mechanism and a user has multiple email addresses, then the list
339   * may include a separate "Email" delivery mechanism info object for each
340   * of the user's email addresses).
341   *
342   * @return  A list containing information about the OTP delivery mechanisms
343   *          supported by the server and which are available for the target
344   *          user, or an empty list if the server doesn't support any OTP
345   *          delivery mechanisms or if the request was not processed
346   *          successfully.
347   */
348  @NotNull()
349  public List<SupportedOTPDeliveryMechanismInfo> getDeliveryMechanismInfo()
350  {
351    return deliveryMechanismInfo;
352  }
353
354
355
356  /**
357   * {@inheritDoc}
358   */
359  @Override()
360  @NotNull()
361  public String getExtendedResultName()
362  {
363    return INFO_GET_SUPPORTED_OTP_MECH_RES_NAME.get();
364  }
365
366
367
368  /**
369   * Appends a string representation of this extended result to the provided
370   * buffer.
371   *
372   * @param  buffer  The buffer to which a string representation of this
373   *                 extended result will be appended.
374   */
375  @Override()
376  public void toString(@NotNull final StringBuilder buffer)
377  {
378    buffer.append("GetSupportedOTPDeliveryMechanismsExtendedResult(" +
379         "resultCode=");
380    buffer.append(getResultCode());
381
382    final int messageID = getMessageID();
383    if (messageID >= 0)
384    {
385      buffer.append(", messageID=");
386      buffer.append(messageID);
387    }
388
389    buffer.append("mechanismInfo={");
390    final Iterator<SupportedOTPDeliveryMechanismInfo> mechIterator =
391         deliveryMechanismInfo.iterator();
392    while (mechIterator.hasNext())
393    {
394      mechIterator.next().toString(buffer);
395      if (mechIterator.hasNext())
396      {
397        buffer.append(", ");
398      }
399    }
400    buffer.append('}');
401
402    final String diagnosticMessage = getDiagnosticMessage();
403    if (diagnosticMessage != null)
404    {
405      buffer.append(", diagnosticMessage='");
406      buffer.append(diagnosticMessage);
407      buffer.append('\'');
408    }
409
410    final String matchedDN = getMatchedDN();
411    if (matchedDN != null)
412    {
413      buffer.append(", matchedDN='");
414      buffer.append(matchedDN);
415      buffer.append('\'');
416    }
417
418    final String[] referralURLs = getReferralURLs();
419    if (referralURLs.length > 0)
420    {
421      buffer.append(", referralURLs={");
422      for (int i=0; i < referralURLs.length; i++)
423      {
424        if (i > 0)
425        {
426          buffer.append(", ");
427        }
428
429        buffer.append('\'');
430        buffer.append(referralURLs[i]);
431        buffer.append('\'');
432      }
433      buffer.append('}');
434    }
435
436    final Control[] responseControls = getResponseControls();
437    if (responseControls.length > 0)
438    {
439      buffer.append(", responseControls={");
440      for (int i=0; i < responseControls.length; i++)
441      {
442        if (i > 0)
443        {
444          buffer.append(", ");
445        }
446
447        buffer.append(responseControls[i]);
448      }
449      buffer.append('}');
450    }
451
452    buffer.append(')');
453  }
454}