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