001/*
002 * Copyright 2008-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2008-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) 2008-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.Date;
044import java.util.Iterator;
045import java.util.List;
046
047import com.unboundid.asn1.ASN1Element;
048import com.unboundid.asn1.ASN1Enumerated;
049import com.unboundid.asn1.ASN1OctetString;
050import com.unboundid.asn1.ASN1Sequence;
051import com.unboundid.ldap.sdk.Control;
052import com.unboundid.ldap.sdk.ExtendedResult;
053import com.unboundid.ldap.sdk.LDAPException;
054import com.unboundid.ldap.sdk.ResultCode;
055import com.unboundid.util.Debug;
056import com.unboundid.util.NotMutable;
057import com.unboundid.util.NotNull;
058import com.unboundid.util.Nullable;
059import com.unboundid.util.StaticUtils;
060import com.unboundid.util.ThreadSafety;
061import com.unboundid.util.ThreadSafetyLevel;
062
063import static com.unboundid.ldap.sdk.unboundidds.extensions.ExtOpMessages.*;
064
065
066
067/**
068 * This class provides an implementation of an extended result that holds
069 * information about the response returned from a
070 * {@link GetSubtreeAccessibilityExtendedRequest}.
071 * <BR>
072 * <BLOCKQUOTE>
073 *   <B>NOTE:</B>  This class, and other classes within the
074 *   {@code com.unboundid.ldap.sdk.unboundidds} package structure, are only
075 *   supported for use against Ping Identity, UnboundID, and
076 *   Nokia/Alcatel-Lucent 8661 server products.  These classes provide support
077 *   for proprietary functionality or for external specifications that are not
078 *   considered stable or mature enough to be guaranteed to work in an
079 *   interoperable way with other types of LDAP servers.
080 * </BLOCKQUOTE>
081 * <BR>
082 * It has an OID of 1.3.6.1.4.1.30221.1.6.21, and successful responses will have
083 * a value with the following encoding:
084 * <BR><BR>
085 * <PRE>
086 *   GetSubtreeAccessibilityResultValue ::= SEQUENCE OF SEQUENCE {
087 *        subtreeBaseDN            [0] LDAPDN,
088 *        subtreeAccessibility     [1] ENUMERATED {
089 *             accessible                 (0),
090 *             read-only-bind-allowed     (1),
091 *             read-only-bind-denied      (2),
092 *             hidden                     (3),
093 *             ... },
094 *        bypassUserDN             [2] LDAPDN OPTIONAL,
095 *        effectiveTime            [3] OCTET STRING,
096 *        ... }
097 * </PRE>
098 */
099@NotMutable()
100@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
101public final class GetSubtreeAccessibilityExtendedResult
102       extends ExtendedResult
103{
104  /**
105   * The OID (1.3.6.1.4.1.30221.1.6.21) for the get subtree accessibility
106   * extended result.
107   */
108  @NotNull public static final String GET_SUBTREE_ACCESSIBILITY_RESULT_OID =
109       "1.3.6.1.4.1.30221.1.6.21";
110
111
112
113  /**
114   * The BER type for the element that holds the base DN for a subtree
115   * accessibility restriction.
116   */
117  private static final byte TYPE_BASE_DN = (byte) 0x80;
118
119
120
121  /**
122   * The BER type for the element that holds the accessibility state for a
123   * subtree accessibility restriction.
124   */
125  private static final byte TYPE_STATE = (byte) 0x81;
126
127
128
129  /**
130   * The BER type for the element that holds the bypass user DN for a subtree
131   * accessibility restriction.
132   */
133  private static final byte TYPE_BYPASS_USER = (byte) 0x82;
134
135
136
137  /**
138   * The BER type for the element that holds the effective time for a subtree
139   * accessibility restriction.
140   */
141  private static final byte TYPE_EFFECTIVE_TIME = (byte) 0x83;
142
143
144
145  /**
146   * The serial version UID for this serializable class.
147   */
148  private static final long serialVersionUID = -3163306122775326749L;
149
150
151
152  // A list of the subtree accessibility restrictions defined in the server.
153  @Nullable private final List<SubtreeAccessibilityRestriction>
154       accessibilityRestrictions;
155
156
157
158  /**
159   * Creates a new get subtree accessibility extended result from the provided
160   * generic extended result.
161   *
162   * @param  extendedResult  The generic extended result to be decoded.
163   *
164   * @throws  LDAPException  If a problem occurs while attempting to decode the
165   *                         provided extended result as a get connection ID
166   *                         result.
167   */
168  public GetSubtreeAccessibilityExtendedResult(
169              @NotNull final ExtendedResult extendedResult)
170         throws LDAPException
171  {
172    super(extendedResult);
173
174    final ASN1OctetString value = extendedResult.getValue();
175    if (value == null)
176    {
177      accessibilityRestrictions = null;
178      return;
179    }
180
181    try
182    {
183      final ASN1Element[] restrictionElements =
184           ASN1Sequence.decodeAsSequence(value.getValue()).elements();
185      final ArrayList<SubtreeAccessibilityRestriction> restrictionList =
186           new ArrayList<>(restrictionElements.length);
187
188      for (final ASN1Element e : restrictionElements)
189      {
190        String baseDN = null;
191        SubtreeAccessibilityState state = null;
192        String bypassDN = null;
193        Date effectiveTime = null;
194
195        for (final ASN1Element re : ASN1Sequence.decodeAsSequence(e).elements())
196        {
197          switch (re.getType())
198          {
199            case TYPE_BASE_DN:
200              baseDN = ASN1OctetString.decodeAsOctetString(re).stringValue();
201              break;
202            case TYPE_STATE:
203              state = SubtreeAccessibilityState.valueOf(
204                   ASN1Enumerated.decodeAsEnumerated(re).intValue());
205              if (state == null)
206              {
207                throw new LDAPException(ResultCode.DECODING_ERROR,
208                     ERR_GET_SUBTREE_ACCESSIBILITY_RESULT_UNEXPECTED_STATE.get(
209                          ASN1Enumerated.decodeAsEnumerated(re).intValue()));
210              }
211              break;
212            case TYPE_BYPASS_USER:
213              bypassDN = ASN1OctetString.decodeAsOctetString(re).stringValue();
214              break;
215            case TYPE_EFFECTIVE_TIME:
216              effectiveTime = StaticUtils.decodeGeneralizedTime(
217                   ASN1OctetString.decodeAsOctetString(re).stringValue());
218              break;
219            default:
220              throw new LDAPException(ResultCode.DECODING_ERROR,
221                   ERR_GET_SUBTREE_ACCESSIBILITY_RESULT_UNEXPECTED_TYPE.get(
222                        StaticUtils.toHex(re.getType())));
223          }
224        }
225
226        if (baseDN == null)
227        {
228          throw new LDAPException(ResultCode.DECODING_ERROR,
229               ERR_GET_SUBTREE_ACCESSIBILITY_RESULT_MISSING_BASE.get());
230        }
231
232        if (state == null)
233        {
234          throw new LDAPException(ResultCode.DECODING_ERROR,
235               ERR_GET_SUBTREE_ACCESSIBILITY_RESULT_MISSING_STATE.get());
236        }
237
238        if (effectiveTime == null)
239        {
240          throw new LDAPException(ResultCode.DECODING_ERROR,
241               ERR_GET_SUBTREE_ACCESSIBILITY_RESULT_MISSING_TIME.get());
242        }
243
244        restrictionList.add(new SubtreeAccessibilityRestriction(baseDN, state,
245             bypassDN, effectiveTime));
246      }
247
248      accessibilityRestrictions = Collections.unmodifiableList(restrictionList);
249    }
250    catch (final LDAPException le)
251    {
252      Debug.debugException(le);
253      throw le;
254    }
255    catch (final Exception e)
256    {
257      Debug.debugException(e);
258      throw new LDAPException(ResultCode.DECODING_ERROR,
259           ERR_GET_SUBTREE_ACCESSIBILITY_RESULT_DECODE_ERROR.get(
260                StaticUtils.getExceptionMessage(e)),
261           e);
262    }
263  }
264
265
266
267  /**
268   * Creates a new get subtree accessibility extended result with the provided
269   * information.
270   *
271   * @param  messageID          The message ID for the LDAP message that is
272   *                            associated with this LDAP result.
273   * @param  resultCode         The result code from the response.
274   * @param  diagnosticMessage  The diagnostic message from the response, if
275   *                            available.
276   * @param  matchedDN          The matched DN from the response, if available.
277   * @param  referralURLs       The set of referral URLs from the response, if
278   *                            available.
279   * @param  restrictions       The set of subtree accessibility restrictions
280   *                            to include in the response.  It may be
281   *                            {@code null} if this represents an error
282   *                            response, or it may be empty if there are no
283   *                            subtree accessibility restrictions defined in
284   *                            the server.
285   * @param  responseControls   The set of controls from the response, if
286   *                            available.
287   */
288  public GetSubtreeAccessibilityExtendedResult(final int messageID,
289       @NotNull final ResultCode resultCode,
290       @Nullable final String diagnosticMessage,
291       @Nullable final String matchedDN,
292       @Nullable final String[] referralURLs,
293       @Nullable final Collection<SubtreeAccessibilityRestriction> restrictions,
294       @Nullable final Control... responseControls)
295  {
296    super(messageID, resultCode, diagnosticMessage, matchedDN, referralURLs,
297          null, encodeValue(restrictions), responseControls);
298
299    if (restrictions == null)
300    {
301      accessibilityRestrictions = null;
302    }
303    else
304    {
305      accessibilityRestrictions = Collections.unmodifiableList(
306           new ArrayList<>(restrictions));
307    }
308  }
309
310
311
312  /**
313   * Encodes the value for this extended result using the provided information.
314   *
315   * @param  restrictions  The set of subtree accessibility restrictions to
316   *                       include in the response.  It may be {@code null} if
317   *                       this represents an error response, or it may be empty
318   *                       if there are no subtree accessibility restrictions
319   *                       defined in the server.
320   *
321   * @return  An ASN.1 octet string containing the properly-encoded value, or
322   *          {@code null} if there should be no value.
323   */
324  @Nullable()
325  private static ASN1OctetString encodeValue(
326       @Nullable final Collection<SubtreeAccessibilityRestriction> restrictions)
327  {
328    if (restrictions == null)
329    {
330      return null;
331    }
332
333    final ArrayList<ASN1Element> elements =
334         new ArrayList<>(restrictions.size());
335    for (final SubtreeAccessibilityRestriction r : restrictions)
336    {
337      final ArrayList<ASN1Element> restrictionElements = new ArrayList<>(4);
338      restrictionElements.add(new ASN1OctetString(TYPE_BASE_DN,
339           r.getSubtreeBaseDN()));
340      restrictionElements.add(new ASN1Enumerated(TYPE_STATE,
341           r.getAccessibilityState().intValue()));
342
343      if (r.getBypassUserDN() != null)
344      {
345        restrictionElements.add(new ASN1OctetString(TYPE_BYPASS_USER,
346             r.getBypassUserDN()));
347      }
348
349      restrictionElements.add(new ASN1OctetString(TYPE_EFFECTIVE_TIME,
350           StaticUtils.encodeGeneralizedTime(r.getEffectiveTime())));
351
352      elements.add(new ASN1Sequence(restrictionElements));
353    }
354
355    return new ASN1OctetString(new ASN1Sequence(elements).encode());
356  }
357
358
359
360  /**
361   * Retrieves a list of the subtree accessibility restrictions defined in the
362   * server.
363   *
364   * @return  A list of the subtree accessibility restrictions defined in the
365   *          server, an empty list if there are no restrictions defined, or
366   *          {@code null} if no restriction data was included in the response
367   *          from the server (e.g., because it was an error response).
368   */
369  @Nullable()
370  public List<SubtreeAccessibilityRestriction> getAccessibilityRestrictions()
371  {
372    return accessibilityRestrictions;
373  }
374
375
376
377  /**
378   * {@inheritDoc}
379   */
380  @Override()
381  @NotNull()
382  public String getExtendedResultName()
383  {
384    return INFO_EXTENDED_RESULT_NAME_GET_SUBTREE_ACCESSIBILITY.get();
385  }
386
387
388
389  /**
390   * {@inheritDoc}
391   */
392  @Override()
393  public void toString(@NotNull final StringBuilder buffer)
394  {
395    buffer.append("GetSubtreeAccessibilityExtendedResult(resultCode=");
396    buffer.append(getResultCode());
397
398    final int messageID = getMessageID();
399    if (messageID >= 0)
400    {
401      buffer.append(", messageID=");
402      buffer.append(messageID);
403    }
404
405    final String diagnosticMessage = getDiagnosticMessage();
406    if (diagnosticMessage != null)
407    {
408      buffer.append(", diagnosticMessage='");
409      buffer.append(diagnosticMessage);
410      buffer.append('\'');
411    }
412
413    final String matchedDN = getMatchedDN();
414    if (matchedDN != null)
415    {
416      buffer.append(", matchedDN='");
417      buffer.append(matchedDN);
418      buffer.append('\'');
419    }
420
421    final String[] referralURLs = getReferralURLs();
422    if ((referralURLs != null) && (referralURLs.length > 0))
423    {
424      buffer.append(", referralURLs={ '");
425      for (int i=0; i < referralURLs.length; i++)
426      {
427        if (i > 0)
428        {
429          buffer.append("', '");
430        }
431        buffer.append(referralURLs[i]);
432      }
433
434      buffer.append("' }");
435    }
436
437    if (accessibilityRestrictions != null)
438    {
439      buffer.append(", accessibilityRestrictions={");
440
441      final Iterator<SubtreeAccessibilityRestriction> iterator =
442           accessibilityRestrictions.iterator();
443      while (iterator.hasNext())
444      {
445        iterator.next().toString(buffer);
446        if (iterator.hasNext())
447        {
448          buffer.append(", ");
449        }
450      }
451
452      buffer.append('}');
453    }
454
455    final Control[] controls = getResponseControls();
456    if (controls.length > 0)
457    {
458      buffer.append(", controls={");
459      for (int i=0; i < controls.length; i++)
460      {
461        if (i > 0)
462        {
463          buffer.append(", ");
464        }
465
466        buffer.append(controls[i]);
467      }
468      buffer.append('}');
469    }
470
471    buffer.append(')');
472  }
473}