001/*
002 * Copyright 2008-2020 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2008-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) 2008-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.text.ParseException;
041import java.util.ArrayList;
042import java.util.Collections;
043import java.util.Date;
044import java.util.Iterator;
045import java.util.LinkedHashMap;
046import java.util.Map;
047import java.util.NoSuchElementException;
048
049import com.unboundid.asn1.ASN1Element;
050import com.unboundid.asn1.ASN1OctetString;
051import com.unboundid.asn1.ASN1Sequence;
052import com.unboundid.ldap.sdk.Control;
053import com.unboundid.ldap.sdk.ExtendedResult;
054import com.unboundid.ldap.sdk.LDAPException;
055import com.unboundid.ldap.sdk.ResultCode;
056import com.unboundid.util.Debug;
057import com.unboundid.util.NotMutable;
058import com.unboundid.util.NotNull;
059import com.unboundid.util.Nullable;
060import com.unboundid.util.StaticUtils;
061import com.unboundid.util.ThreadSafety;
062import com.unboundid.util.ThreadSafetyLevel;
063
064import static com.unboundid.ldap.sdk.unboundidds.extensions.ExtOpMessages.*;
065
066
067
068/**
069 * This class implements a data structure for storing the information from an
070 * extended result for the password policy state extended request as used in the
071 * Ping Identity, UnboundID, or Nokia/Alcatel-Lucent 8661 Directory Server.  It
072 * is able to decode a generic extended result to obtain the user DN and
073 * operations.  See the documentation in the
074 * {@link PasswordPolicyStateExtendedRequest} class for an example that
075 * demonstrates the use of the password policy state extended operation.
076 * <BR>
077 * <BLOCKQUOTE>
078 *   <B>NOTE:</B>  This class, and other classes within the
079 *   {@code com.unboundid.ldap.sdk.unboundidds} package structure, are only
080 *   supported for use against Ping Identity, UnboundID, and
081 *   Nokia/Alcatel-Lucent 8661 server products.  These classes provide support
082 *   for proprietary functionality or for external specifications that are not
083 *   considered stable or mature enough to be guaranteed to work in an
084 *   interoperable way with other types of LDAP servers.
085 * </BLOCKQUOTE>
086 * <BR>
087 * This extended result does not have an OID.  If the request was processed
088 * successfully, then the result will have a value that has the same encoding as
089 * the request, which was described in the class-level documentation for the
090 * {@link PasswordPolicyStateExtendedRequest} class.
091 */
092@NotMutable()
093@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
094public final class PasswordPolicyStateExtendedResult
095       extends ExtendedResult
096{
097  /**
098   * The serial version UID for this serializable class.
099   */
100  private static final long serialVersionUID = 7140468768443263344L;
101
102
103
104  // A map containing all of the response operations, indexed by operation type.
105  @NotNull private final Map<Integer,PasswordPolicyStateOperation> operations;
106
107  // The user DN from the response.
108  @Nullable private final String userDN;
109
110
111
112  /**
113   * Creates a new password policy state extended result from the provided
114   * extended result.
115   *
116   * @param  extendedResult  The extended result to be decoded as a password
117   *                         policy state extended result.  It must not be
118   *                         {@code null}.
119   *
120   * @throws  LDAPException  If the provided extended result cannot be decoded
121   *                         as a password policy state extended result.
122   */
123  public PasswordPolicyStateExtendedResult(
124              @NotNull final ExtendedResult extendedResult)
125         throws LDAPException
126  {
127    super(extendedResult);
128
129    final ASN1OctetString value = extendedResult.getValue();
130    if (value == null)
131    {
132      userDN = null;
133      operations = Collections.emptyMap();
134      return;
135    }
136
137    final ASN1Element[] elements;
138    try
139    {
140      final ASN1Element valueElement = ASN1Element.decode(value.getValue());
141      elements = ASN1Sequence.decodeAsSequence(valueElement).elements();
142    }
143    catch (final Exception e)
144    {
145      Debug.debugException(e);
146      throw new LDAPException(ResultCode.DECODING_ERROR,
147                              ERR_PWP_STATE_RESPONSE_VALUE_NOT_SEQUENCE.get(e),
148                              e);
149    }
150
151    if ((elements.length < 1) || (elements.length > 2))
152    {
153      throw new LDAPException(ResultCode.DECODING_ERROR,
154                              ERR_PWP_STATE_RESPONSE_INVALID_ELEMENT_COUNT.get(
155                                   elements.length));
156    }
157
158    userDN = ASN1OctetString.decodeAsOctetString(elements[0]).stringValue();
159
160    final LinkedHashMap<Integer,PasswordPolicyStateOperation> ops =
161         new LinkedHashMap<>(StaticUtils.computeMapCapacity(20));
162    if (elements.length == 2)
163    {
164      try
165      {
166        final ASN1Element[] opElements =
167             ASN1Sequence.decodeAsSequence(elements[1]).elements();
168        for (final ASN1Element e : opElements)
169        {
170          final PasswordPolicyStateOperation op =
171               PasswordPolicyStateOperation.decode(e);
172          ops.put(op.getOperationType(), op);
173        }
174      }
175      catch (final Exception e)
176      {
177        Debug.debugException(e);
178        throw new LDAPException(ResultCode.DECODING_ERROR,
179                                ERR_PWP_STATE_RESPONSE_CANNOT_DECODE_OPS.get(e),
180                                e);
181      }
182    }
183
184    operations = Collections.unmodifiableMap(ops);
185  }
186
187
188
189  /**
190   * Creates a new password policy state extended result with the provided
191   * information.
192   * @param  messageID          The message ID for the LDAP message that is
193   *                            associated with this LDAP result.
194   * @param  resultCode         The result code from the response.
195   * @param  diagnosticMessage  The diagnostic message from the response, if
196   *                            available.
197   * @param  matchedDN          The matched DN from the response, if available.
198   * @param  referralURLs       The set of referral URLs from the response, if
199   *                            available.
200   * @param  userDN             The user DN from the response.
201   * @param  operations         The set of operations from the response, mapped
202   *                            from operation type to the corresponding
203   *                            operation data.
204   * @param  responseControls   The set of controls from the response, if
205   *                            available.
206   */
207  public PasswordPolicyStateExtendedResult(final int messageID,
208              @NotNull final ResultCode resultCode,
209              @Nullable final String diagnosticMessage,
210              @Nullable final String matchedDN,
211              @Nullable final String[] referralURLs,
212              @Nullable final String userDN,
213              @Nullable final PasswordPolicyStateOperation[] operations,
214              @Nullable final Control[] responseControls)
215  {
216    super(messageID, resultCode, diagnosticMessage, matchedDN, referralURLs,
217          null, encodeValue(userDN, operations), responseControls);
218
219    this.userDN = userDN;
220
221    if ((operations == null) || (operations.length == 0))
222    {
223      this.operations = Collections.emptyMap();
224    }
225    else
226    {
227      final LinkedHashMap<Integer,PasswordPolicyStateOperation> ops =
228           new LinkedHashMap<>(StaticUtils.computeMapCapacity(
229                operations.length));
230      for (final PasswordPolicyStateOperation o : operations)
231      {
232        ops.put(o.getOperationType(), o);
233      }
234      this.operations = Collections.unmodifiableMap(ops);
235    }
236  }
237
238
239
240  /**
241   * Encodes the provided information into a suitable value for this control.
242   *
243   * @param  userDN             The user DN from the response.
244   * @param  operations         The set of operations from the response, mapped
245   *                            from operation type to the corresponding
246   *                            operation data.
247   *
248   * @return  An ASN.1 octet string containing the appropriately-encoded value
249   *          for this control, or {@code null} if there should not be a value.
250   */
251  @Nullable()
252  private static ASN1OctetString encodeValue(@Nullable final String userDN,
253       @Nullable final PasswordPolicyStateOperation[] operations)
254  {
255    if ((userDN == null) && ((operations == null) || (operations.length == 0)))
256    {
257      return null;
258    }
259
260    final ArrayList<ASN1Element> elements = new ArrayList<>(2);
261    elements.add(new ASN1OctetString(userDN));
262
263    if ((operations != null) && (operations.length > 0))
264    {
265      final ASN1Element[] opElements = new ASN1Element[operations.length];
266      for (int i=0; i < operations.length; i++)
267      {
268        opElements[i] = operations[i].encode();
269      }
270
271      elements.add(new ASN1Sequence(opElements));
272    }
273
274    return new ASN1OctetString(new ASN1Sequence(elements).encode());
275  }
276
277
278
279  /**
280   * Retrieves the user DN included in the response.
281   *
282   * @return  The user DN included in the response, or {@code null} if the user
283   *          DN is not available (e.g., if this is an error response).
284   */
285  @Nullable()
286  public String getUserDN()
287  {
288    return userDN;
289  }
290
291
292
293  /**
294   * Retrieves the set of password policy operations included in the response.
295   *
296   * @return  The set of password policy operations included in the response.
297   */
298  @NotNull()
299  public Iterable<PasswordPolicyStateOperation> getOperations()
300  {
301    return operations.values();
302  }
303
304
305
306  /**
307   * Retrieves the specified password policy state operation from the response.
308   *
309   * @param  opType  The operation type for the password policy state operation
310   *                 to retrieve.
311   *
312   * @return  The requested password policy state operation, or {@code null} if
313   *          no such operation was included in the response.
314   */
315  @Nullable()
316  public PasswordPolicyStateOperation getOperation(final int opType)
317  {
318    return operations.get(opType);
319  }
320
321
322
323  /**
324   * Retrieves the value for the specified password policy state operation as a
325   * string.
326   *
327   * @param  opType  The operation type for the password policy state operation
328   *                 to retrieve.
329   *
330   * @return  The string value of the requested password policy state operation,
331   *          or {@code null} if the specified operation was not included in the
332   *          response or did not have any values.
333   */
334  @Nullable()
335  public String getStringValue(final int opType)
336  {
337    final PasswordPolicyStateOperation op = operations.get(opType);
338    if (op == null)
339    {
340      return null;
341    }
342
343    return op.getStringValue();
344  }
345
346
347
348  /**
349   * Retrieves the set of string values for the specified password policy state
350   * operation.
351   *
352   * @param  opType  The operation type for the password policy state operation
353   *                 to retrieve.
354   *
355   * @return  The set of string values for the requested password policy state
356   *          operation, or {@code null} if the specified operation was not
357   *          included in the response.
358   */
359  @Nullable()
360  public String[] getStringValues(final int opType)
361  {
362    final PasswordPolicyStateOperation op = operations.get(opType);
363    if (op == null)
364    {
365      return null;
366    }
367
368    return op.getStringValues();
369  }
370
371
372
373  /**
374   * Retrieves the value of the specified password policy state operation as a
375   * boolean.
376   *
377   * @param  opType  The operation type for the password policy state operation
378   *                 to retrieve.
379   *
380   * @return  The boolean value of the requested password policy state
381   *          operation.
382   *
383   * @throws  NoSuchElementException  If the specified operation was not
384   *                                  included in the response.
385   *
386   * @throws  IllegalStateException  If the specified password policy state
387   *                                 operation does not have exactly one value,
388   *                                 or if the value cannot be parsed as a
389   *                                 boolean value.
390   */
391  public boolean getBooleanValue(final int opType)
392         throws NoSuchElementException, IllegalStateException
393  {
394    final PasswordPolicyStateOperation op = operations.get(opType);
395    if (op == null)
396    {
397      throw new NoSuchElementException(
398                     ERR_PWP_STATE_RESPONSE_NO_SUCH_OPERATION.get());
399    }
400
401    return op.getBooleanValue();
402  }
403
404
405
406  /**
407   * Retrieves the value of the specified password policy state operation as an
408   * integer.
409   *
410   * @param  opType  The operation type for the password policy state operation
411   *                 to retrieve.
412   *
413   * @return  The integer value of the requested password policy state
414   *          operation.
415   *
416   * @throws  NoSuchElementException  If the specified operation was not
417   *                                  included in the response.
418   *
419   * @throws  IllegalStateException  If the value of the specified password
420   *                                 policy state operation cannot be parsed as
421   *                                 an integer value.
422   */
423  public int getIntValue(final int opType)
424         throws NoSuchElementException, IllegalStateException
425  {
426    final PasswordPolicyStateOperation op = operations.get(opType);
427    if (op == null)
428    {
429      throw new NoSuchElementException(
430                     ERR_PWP_STATE_RESPONSE_NO_SUCH_OPERATION.get());
431    }
432
433    return op.getIntValue();
434  }
435
436
437
438  /**
439   * Retrieves the value for the specified password policy state operation as a
440   * {@code Date} in generalized time format.
441   *
442   * @param  opType  The operation type for the password policy state operation
443   *                 to retrieve.
444   *
445   * @return  The value of the requested password policy state operation as a
446   *          {@code Date}, or {@code null} if the specified operation was not
447   *          included in the response or did not have any values.
448   *
449   * @throws  ParseException  If the value cannot be parsed as a date in
450   *                          generalized time format.
451   */
452  @Nullable()
453  public Date getGeneralizedTimeValue(final int opType)
454         throws ParseException
455  {
456    final PasswordPolicyStateOperation op = operations.get(opType);
457    if (op == null)
458    {
459      return null;
460    }
461
462    return op.getGeneralizedTimeValue();
463  }
464
465
466
467  /**
468   * Retrieves the set of values for the specified password policy state
469   * operation as {@code Date}s in generalized time format.
470   *
471   * @param  opType  The operation type for the password policy state operation
472   *                 to retrieve.
473   *
474   * @return  The set of values of the requested password policy state operation
475   *          as {@code Date}s.
476   *
477   * @throws  ParseException  If any of the values cannot be parsed as a date in
478   *                          generalized time format.
479   */
480  @Nullable()
481  public Date[] getGeneralizedTimeValues(final int opType)
482         throws ParseException
483  {
484    final PasswordPolicyStateOperation op = operations.get(opType);
485    if (op == null)
486    {
487      return null;
488    }
489
490    return op.getGeneralizedTimeValues();
491  }
492
493
494
495  /**
496   * {@inheritDoc}
497   */
498  @Override()
499  @NotNull()
500  public String getExtendedResultName()
501  {
502    return INFO_EXTENDED_RESULT_NAME_PW_POLICY_STATE.get();
503  }
504
505
506
507  /**
508   * Appends a string representation of this extended result to the provided
509   * buffer.
510   *
511   * @param  buffer  The buffer to which a string representation of this
512   *                 extended result will be appended.
513   */
514  @Override()
515  public void toString(@NotNull final StringBuilder buffer)
516  {
517    buffer.append("PasswordPolicyStateExtendedResult(resultCode=");
518    buffer.append(getResultCode());
519
520    final int messageID = getMessageID();
521    if (messageID >= 0)
522    {
523      buffer.append(", messageID=");
524      buffer.append(messageID);
525    }
526
527    buffer.append(", userDN='");
528    buffer.append(userDN);
529    buffer.append("', operations={");
530
531    final Iterator<PasswordPolicyStateOperation> iterator =
532         operations.values().iterator();
533    while (iterator.hasNext())
534    {
535      iterator.next().toString(buffer);
536      if (iterator.hasNext())
537      {
538        buffer.append(", ");
539      }
540    }
541    buffer.append('}');
542
543    final String diagnosticMessage = getDiagnosticMessage();
544    if (diagnosticMessage != null)
545    {
546      buffer.append(", diagnosticMessage='");
547      buffer.append(diagnosticMessage);
548      buffer.append('\'');
549    }
550
551    final String matchedDN = getMatchedDN();
552    if (matchedDN != null)
553    {
554      buffer.append(", matchedDN='");
555      buffer.append(matchedDN);
556      buffer.append('\'');
557    }
558
559    final String[] referralURLs = getReferralURLs();
560    if (referralURLs.length > 0)
561    {
562      buffer.append(", referralURLs={");
563      for (int i=0; i < referralURLs.length; i++)
564      {
565        if (i > 0)
566        {
567          buffer.append(", ");
568        }
569
570        buffer.append('\'');
571        buffer.append(referralURLs[i]);
572        buffer.append('\'');
573      }
574      buffer.append('}');
575    }
576
577    final Control[] responseControls = getResponseControls();
578    if (responseControls.length > 0)
579    {
580      buffer.append(", responseControls={");
581      for (int i=0; i < responseControls.length; i++)
582      {
583        if (i > 0)
584        {
585          buffer.append(", ");
586        }
587
588        buffer.append(responseControls[i]);
589      }
590      buffer.append('}');
591    }
592
593    buffer.append(')');
594  }
595}