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