001/*
002 * Copyright 2014-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2014-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) 2014-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.controls;
037
038
039
040import java.util.ArrayList;
041import java.util.Collection;
042import java.util.Collections;
043import java.util.Iterator;
044import java.util.LinkedHashSet;
045import java.util.List;
046import java.util.Set;
047
048import com.unboundid.asn1.ASN1Element;
049import com.unboundid.asn1.ASN1OctetString;
050import com.unboundid.asn1.ASN1Sequence;
051import com.unboundid.asn1.ASN1Set;
052import com.unboundid.ldap.sdk.Control;
053import com.unboundid.ldap.sdk.DecodeableControl;
054import com.unboundid.ldap.sdk.ExtendedResult;
055import com.unboundid.ldap.sdk.JSONControlDecodeHelper;
056import com.unboundid.ldap.sdk.LDAPException;
057import com.unboundid.ldap.sdk.LDAPResult;
058import com.unboundid.ldap.sdk.ResultCode;
059import com.unboundid.ldap.sdk.SearchResultEntry;
060import com.unboundid.util.Debug;
061import com.unboundid.util.NotMutable;
062import com.unboundid.util.NotNull;
063import com.unboundid.util.Nullable;
064import com.unboundid.util.StaticUtils;
065import com.unboundid.util.ThreadSafety;
066import com.unboundid.util.ThreadSafetyLevel;
067import com.unboundid.util.Validator;
068import com.unboundid.util.json.JSONArray;
069import com.unboundid.util.json.JSONField;
070import com.unboundid.util.json.JSONObject;
071import com.unboundid.util.json.JSONString;
072import com.unboundid.util.json.JSONValue;
073
074import static com.unboundid.ldap.sdk.unboundidds.controls.ControlMessages.*;
075
076
077
078/**
079 * This class provides a response control that may be used to provide the
080 * backend set ID(s) for any relevant backend sets accessed during the course
081 * of processing an operation.  It may be returned in response to a request
082 * containing either the get backend set ID request control or the route to
083 * backend set request control.  For add, simple bind, compare, delete,
084 * modify, and modify DN operations, the LDAP result message for the operation
085 * may contain zero or one get backend set ID response control.  For extended
086 * operations, the extended result message may contain zero, one, or multiple
087 * get backend set ID response controls.  For search operations, each search
088 * result entry may contain zero or one get backend set ID response control,
089 * while the search result done message will not contain any such control.  See
090 * the {@link GetBackendSetIDRequestControl} class documentation for a more
091 * complete description of the usage for these controls.
092 * <BR>
093 * <BLOCKQUOTE>
094 *   <B>NOTE:</B>  This class, and other classes within the
095 *   {@code com.unboundid.ldap.sdk.unboundidds} package structure, are only
096 *   supported for use against Ping Identity, UnboundID, and
097 *   Nokia/Alcatel-Lucent 8661 server products.  These classes provide support
098 *   for proprietary functionality or for external specifications that are not
099 *   considered stable or mature enough to be guaranteed to work in an
100 *   interoperable way with other types of LDAP servers.
101 * </BLOCKQUOTE>
102 * <BR>
103 * The get backend set ID response control has an OID of
104 * "1.3.6.1.4.1.30221.2.5.34", a criticality of false, and a value with the
105 * following encoding:
106 * <PRE>
107 *   GET_BACKEND_SET_ID_RESPONSE_VALUE ::= SEQUENCE {
108 *     entryBalancingRequestProcessorID     OCTET STRING,
109 *     backendSetIDs                        SET SIZE (1..MAX) OF OCTET STRING,
110 *     ... }
111 * </PRE>
112 *
113 * @see  GetBackendSetIDRequestControl
114 * @see  RouteToBackendSetRequestControl
115 */
116@NotMutable()
117@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
118public final class GetBackendSetIDResponseControl
119       extends Control
120       implements DecodeableControl
121{
122  /**
123   * The OID (1.3.6.1.4.1.30221.2.5.34) for the get backend set ID response
124   * control.
125   */
126  @NotNull public static final  String GET_BACKEND_SET_ID_RESPONSE_OID =
127       "1.3.6.1.4.1.30221.2.5.34";
128
129
130
131  /**
132   * The name of the field used to specify backend set IDs in the JSON
133   * representation of this control.
134   */
135  @NotNull private static final String JSON_FIELD_BACKEND_SET_IDS =
136       "backend-set-ids";
137
138
139
140  /**
141   * The name of the field used to specify the ID of the entry-balancing request
142   * processor in the JSON representation of this control.
143   */
144  @NotNull private static final String JSON_FIELD_REQUEST_PROCESSOR_ID =
145       "request-processor-id";
146
147
148
149  /**
150   * The serial version UID for this serializable class.
151   */
152  private static final long serialVersionUID = 117359364981309726L;
153
154
155
156  // The backend set IDs for backend sets used during processing.
157  @NotNull private final Set<String> backendSetIDs;
158
159  // The identifier for the entry-balancing request processor with which the
160  // backend set IDs are associated.
161  @NotNull private final String entryBalancingRequestProcessorID;
162
163
164
165  /**
166   * Creates a new empty control instance that is intended to be used only for
167   * decoding controls via the {@code DecodeableControl} interface.
168   */
169  GetBackendSetIDResponseControl()
170  {
171    entryBalancingRequestProcessorID = null;
172    backendSetIDs = null;
173  }
174
175
176
177  /**
178   * Creates a new get backend set ID response control with the provided
179   * information.
180   *
181   * @param  entryBalancingRequestProcessorID  The identifier for the
182   *                                           entry-balancing request processor
183   *                                           with which the backend set IDs
184   *                                           are associated.  It must not be
185   *                                           {@code null}.
186   * @param  backendSetID                      The backend set ID for the
187   *                                           backend set used during
188   *                                           processing.  It must not be
189   *                                           {@code null}.
190   */
191  public GetBackendSetIDResponseControl(
192              @NotNull final String entryBalancingRequestProcessorID,
193              @NotNull final String backendSetID)
194  {
195    this(entryBalancingRequestProcessorID,
196         Collections.singletonList(backendSetID));
197  }
198
199
200
201  /**
202   * Creates a new get backend set ID response control with the provided
203   * information.
204   *
205   * @param  entryBalancingRequestProcessorID  The identifier for the
206   *                                           entry-balancing request processor
207   *                                           with which the backend set IDs
208   *                                           are associated.  It must not be
209   *                                           {@code null}.
210   * @param  backendSetIDs                     The backend set IDs for backend
211   *                                           sets used during processing.  It
212   *                                           must not be {@code null} or
213   *                                           empty.
214   */
215  public GetBackendSetIDResponseControl(
216              @NotNull final String entryBalancingRequestProcessorID,
217              @NotNull final Collection<String> backendSetIDs)
218  {
219    super(GET_BACKEND_SET_ID_RESPONSE_OID, false,
220         encodeValue(entryBalancingRequestProcessorID, backendSetIDs));
221
222    this.entryBalancingRequestProcessorID = entryBalancingRequestProcessorID;
223    this.backendSetIDs =
224         Collections.unmodifiableSet(new LinkedHashSet<>(backendSetIDs));
225  }
226
227
228
229  /**
230   * Creates a new get backend set ID response control decoded from the given
231   * generic control contents.
232   *
233   * @param  oid         The OID for the control.
234   * @param  isCritical  Indicates whether this control should be marked
235   *                     critical.
236   * @param  value       The encoded value for the control.
237   *
238   * @throws LDAPException  If a problem occurs while attempting to decode the
239   *                        generic control as a get backend set ID response
240   *                        control.
241   */
242  public GetBackendSetIDResponseControl(@NotNull final String oid,
243                                        final boolean isCritical,
244                                        @Nullable final ASN1OctetString value)
245       throws LDAPException
246  {
247    super(oid, isCritical, value);
248
249    if (value == null)
250    {
251      throw new LDAPException(ResultCode.DECODING_ERROR,
252           ERR_GET_BACKEND_SET_ID_RESPONSE_MISSING_VALUE.get());
253    }
254
255    try
256    {
257      final ASN1Element[] elements =
258           ASN1Sequence.decodeAsSequence(value.getValue()).elements();
259      entryBalancingRequestProcessorID =
260           ASN1OctetString.decodeAsOctetString(elements[0]).stringValue();
261
262      final ASN1Element[] backendSetIDElements =
263           ASN1Set.decodeAsSet(elements[1]).elements();
264      final LinkedHashSet<String> setIDs = new LinkedHashSet<>(
265           StaticUtils.computeMapCapacity(backendSetIDElements.length));
266      for (final ASN1Element e : backendSetIDElements)
267      {
268        setIDs.add(ASN1OctetString.decodeAsOctetString(e).stringValue());
269      }
270      backendSetIDs = Collections.unmodifiableSet(setIDs);
271    }
272    catch (final Exception e)
273    {
274      Debug.debugException(e);
275      throw new LDAPException(ResultCode.DECODING_ERROR,
276           ERR_GET_BACKEND_SET_ID_RESPONSE_CANNOT_DECODE.get(
277                StaticUtils.getExceptionMessage(e)),
278           e);
279    }
280  }
281
282
283
284  /**
285   * Encodes the provided information into an octet string suitable for use as
286   * the value of this control.
287   *
288   * @param  entryBalancingRequestProcessorID  The identifier for the
289   *                                           entry-balancing request processor
290   *                                           with which the backend set IDs
291   *                                           are associated.  It must not be
292   *                                           {@code null}.
293   * @param  backendSetIDs                     The backend set IDs for backend
294   *                                           sets used during processing.  It
295   *                                           must not be {@code null} or
296   *                                           empty.
297   *
298   * @return  The encoded representation of the control value.
299   */
300  @NotNull()
301  private static ASN1OctetString encodeValue(
302                      @NotNull final String entryBalancingRequestProcessorID,
303                      @NotNull final Collection<String> backendSetIDs)
304  {
305    Validator.ensureNotNull(entryBalancingRequestProcessorID);
306    Validator.ensureNotNull(backendSetIDs);
307    Validator.ensureFalse(backendSetIDs.isEmpty());
308
309    final ArrayList<ASN1Element> backendSetIDElements =
310         new ArrayList<>(backendSetIDs.size());
311    for (final String s : backendSetIDs)
312    {
313      backendSetIDElements.add(new ASN1OctetString(s));
314    }
315
316    final ASN1Sequence valueSequence = new ASN1Sequence(
317         new ASN1OctetString(entryBalancingRequestProcessorID),
318         new ASN1Set(backendSetIDElements));
319    return new ASN1OctetString(valueSequence.encode());
320  }
321
322
323
324  /**
325   * {@inheritDoc}
326   */
327  @Override()
328  @NotNull()
329  public GetBackendSetIDResponseControl decodeControl(@NotNull final String oid,
330              final boolean isCritical,
331              @Nullable final ASN1OctetString value)
332         throws LDAPException
333  {
334    return new GetBackendSetIDResponseControl(oid, isCritical, value);
335  }
336
337
338
339  /**
340   * Retrieves the identifier for the entry-balancing request processor with
341   * which the backend sets IDs are associated.
342   *
343   * @return  The identifier for the entry-balancing request processor with
344   *          which the backend set IDs are associated.
345   */
346  @NotNull()
347  public String getEntryBalancingRequestProcessorID()
348  {
349    return entryBalancingRequestProcessorID;
350  }
351
352
353
354  /**
355   * Retrieves the backend set IDs for the backend sets used during processing.
356   *
357   * @return  The backend set IDs for the backend sets used during processing.
358   */
359  @NotNull()
360  public Set<String> getBackendSetIDs()
361  {
362    return backendSetIDs;
363  }
364
365
366
367  /**
368   * Extracts a get backend set ID response control from the provided result.
369   *
370   * @param  result  The result from which to retrieve the get backend set ID
371   *                 response control.
372   *
373   * @return  The get backend set ID response control contained in the provided
374   *          result, or {@code null} if the result did not contain a get
375   *          backend set ID response control.
376   *
377   * @throws  LDAPException  If a problem is encountered while attempting to
378   *                         decode the get backend set ID response control
379   *                         contained in the provided result.
380   */
381  @Nullable()
382  public static GetBackendSetIDResponseControl get(
383                     @NotNull final LDAPResult result)
384         throws LDAPException
385  {
386    final Control c =
387         result.getResponseControl(GET_BACKEND_SET_ID_RESPONSE_OID);
388    if (c == null)
389    {
390      return null;
391    }
392
393    if (c instanceof GetBackendSetIDResponseControl)
394    {
395      return (GetBackendSetIDResponseControl) c;
396    }
397    else
398    {
399      return new GetBackendSetIDResponseControl(c.getOID(), c.isCritical(),
400           c.getValue());
401    }
402  }
403
404
405
406  /**
407   * Extracts a get backend set ID response control from the provided search
408   * result entry.
409   *
410   * @param  entry  The entry from which to retrieve the get backend set ID
411   *                response control.
412   *
413   * @return  The get backend set ID response control contained in the provided
414   *          entry, or {@code null} if the entry did not contain a get backend
415   *          set ID response control.
416   *
417   * @throws  LDAPException  If a problem is encountered while attempting to
418   *                         decode the get backend set ID response control
419   *                         contained in the provided result.
420   */
421  @Nullable()
422  public static GetBackendSetIDResponseControl get(
423                     @NotNull final SearchResultEntry entry)
424         throws LDAPException
425  {
426    final Control c = entry.getControl(GET_BACKEND_SET_ID_RESPONSE_OID);
427    if (c == null)
428    {
429      return null;
430    }
431
432    if (c instanceof GetBackendSetIDResponseControl)
433    {
434      return (GetBackendSetIDResponseControl) c;
435    }
436    else
437    {
438      return new GetBackendSetIDResponseControl(c.getOID(), c.isCritical(),
439           c.getValue());
440    }
441  }
442
443
444
445  /**
446   * Extracts any get backend set ID response controls from the provided
447   * extended result.
448   *
449   * @param  result  The extended result from which to retrieve the get backend
450   *                 set ID response control(s).
451   *
452   * @return  A list of get backend set ID response controls contained in the
453   *          provided extended result, or an empty list if the result did not
454   *          contain a get any backend set ID response controls.
455   *
456   * @throws  LDAPException  If a problem is encountered while attempting to
457   *                         decode the any backend set ID response control
458   *                         contained in the provided result.
459   */
460  @NotNull()
461  public static List<GetBackendSetIDResponseControl> get(
462                     @NotNull final ExtendedResult result)
463         throws LDAPException
464  {
465    final Control[] controls = result.getResponseControls();
466    if (controls.length == 0)
467    {
468      return Collections.emptyList();
469    }
470
471    final ArrayList<GetBackendSetIDResponseControl> decodedControls =
472         new ArrayList<>(controls.length);
473    for (final Control c : controls)
474    {
475      if (c instanceof GetBackendSetIDResponseControl)
476      {
477        decodedControls.add((GetBackendSetIDResponseControl) c);
478      }
479      else if (c.getOID().equals(GET_BACKEND_SET_ID_RESPONSE_OID))
480      {
481        decodedControls.add(new GetBackendSetIDResponseControl(c.getOID(),
482             c.isCritical(), c.getValue()));
483      }
484    }
485
486    return Collections.unmodifiableList(decodedControls);
487  }
488
489
490
491  /**
492   * {@inheritDoc}
493   */
494  @Override()
495  @NotNull()
496  public String getControlName()
497  {
498    return INFO_CONTROL_NAME_GET_BACKEND_SET_ID_RESPONSE.get();
499  }
500
501
502
503  /**
504   * Retrieves a representation of this get backend set ID response control as a
505   * JSON object.  The JSON object uses the following fields:
506   * <UL>
507   *   <LI>
508   *     {@code oid} -- A mandatory string field whose value is the object
509   *     identifier for this control.  For the get backend set ID response
510   *     control, the OID is "1.3.6.1.4.1.30221.2.5.34".
511   *   </LI>
512   *   <LI>
513   *     {@code control-name} -- An optional string field whose value is a
514   *     human-readable name for this control.  This field is only intended for
515   *     descriptive purposes, and when decoding a control, the {@code oid}
516   *     field should be used to identify the type of control.
517   *   </LI>
518   *   <LI>
519   *     {@code criticality} -- A mandatory Boolean field used to indicate
520   *     whether this control is considered critical.
521   *   </LI>
522   *   <LI>
523   *     {@code value-base64} -- An optional string field whose value is a
524   *     base64-encoded representation of the raw value for this get backend set
525   *     ID response control.  Exactly one of the {@code value-base64} and
526   *     {@code value-json} fields must be present.
527   *   </LI>
528   *   <LI>
529   *     {@code value-json} -- An optional JSON object field whose value is a
530   *     user-friendly representation of the value for this get backend set ID
531   *     response control.  Exactly one of the {@code value-base64} and
532   *     {@code value-json} fields must be present, and if the
533   *     {@code value-json} field is used, then it will use the following
534   *     fields:
535   *     <UL>
536   *       <LI>
537   *         {@code request-processor-id} -- A string field whose value is the
538   *         name of the entry-balancing request processor with which the
539   *         control is associated.
540   *       </LI>
541   *       <LI>
542   *         {@code backend-set-ids} -- An array field whose values are the
543   *         string identifiers for the backend sets in which processing was
544   *         performed for the associated entry.
545   *       </LI>
546   *     </UL>
547   *   </LI>
548   * </UL>
549   *
550   * @return  A JSON object that contains a representation of this control.
551   */
552  @Override()
553  @NotNull()
554  public JSONObject toJSONControl()
555  {
556    final List<JSONValue> backendSetIDValues = new ArrayList<>();
557    for (final String backendSetID : backendSetIDs)
558    {
559      backendSetIDValues.add(new JSONString(backendSetID));
560    }
561
562    return new JSONObject(
563         new JSONField(JSONControlDecodeHelper.JSON_FIELD_OID,
564              GET_BACKEND_SET_ID_RESPONSE_OID),
565         new JSONField(JSONControlDecodeHelper.JSON_FIELD_CONTROL_NAME,
566              INFO_CONTROL_NAME_GET_BACKEND_SET_ID_RESPONSE.get()),
567         new JSONField(JSONControlDecodeHelper.JSON_FIELD_CRITICALITY,
568              isCritical()),
569         new JSONField(JSONControlDecodeHelper.JSON_FIELD_VALUE_JSON,
570              new JSONObject(
571                   new JSONField("request-processor-id",
572                        entryBalancingRequestProcessorID),
573                   new JSONField("backend-set-ids",
574                        new JSONArray(backendSetIDValues)))));
575  }
576
577
578
579  /**
580   * Attempts to decode the provided object as a JSON representation of a get
581   * backend set ID response control.
582   *
583   * @param  controlObject  The JSON object to be decoded.  It must not be
584   *                        {@code null}.
585   * @param  strict         Indicates whether to use strict mode when decoding
586   *                        the provided JSON object.  If this is {@code true},
587   *                        then this method will throw an exception if the
588   *                        provided JSON object contains any unrecognized
589   *                        fields.  If this is {@code false}, then unrecognized
590   *                        fields will be ignored.
591   *
592   * @return  The get backend set ID response control that was decoded from
593   *          the provided JSON object.
594   *
595   * @throws  LDAPException  If the provided JSON object cannot be parsed as a
596   *                         valid get backend set ID response control.
597   */
598  @NotNull()
599  public static GetBackendSetIDResponseControl decodeJSONControl(
600              @NotNull final JSONObject controlObject,
601              final boolean strict)
602         throws LDAPException
603  {
604    final JSONControlDecodeHelper jsonControl = new JSONControlDecodeHelper(
605         controlObject, strict, true, true);
606
607    final ASN1OctetString rawValue = jsonControl.getRawValue();
608    if (rawValue != null)
609    {
610      return new GetBackendSetIDResponseControl(jsonControl.getOID(),
611           jsonControl.getCriticality(), rawValue);
612    }
613
614
615    final JSONObject valueObject = jsonControl.getValueObject();
616
617    final String requestProcessorID =
618         valueObject.getFieldAsString(JSON_FIELD_REQUEST_PROCESSOR_ID);
619    if (requestProcessorID == null)
620    {
621      throw new LDAPException(ResultCode.DECODING_ERROR,
622           ERR_GET_BACKEND_SET_ID_RESPONSE_JSON_MISSING_FIELD.get(
623                controlObject.toSingleLineString(),
624                JSON_FIELD_REQUEST_PROCESSOR_ID));
625    }
626
627    final List<JSONValue> backendSetIDValues =
628         valueObject.getFieldAsArray(JSON_FIELD_BACKEND_SET_IDS);
629    if (backendSetIDValues == null)
630    {
631      throw new LDAPException(ResultCode.DECODING_ERROR,
632           ERR_GET_BACKEND_SET_ID_RESPONSE_JSON_MISSING_FIELD.get(
633                controlObject.toSingleLineString(),
634                JSON_FIELD_BACKEND_SET_IDS));
635    }
636
637    final List<String> backendSetIDs =
638         new ArrayList<>(backendSetIDValues.size());
639    for (final JSONValue v : backendSetIDValues)
640    {
641      if (v instanceof JSONString)
642      {
643        backendSetIDs.add(((JSONString) v).stringValue());
644      }
645      else
646      {
647        throw new LDAPException(ResultCode.DECODING_ERROR,
648             ERR_GET_BACKEND_SET_ID_RESPONSE_JSON_BACKEND_SET_ID_NOT_STRING.get(
649                  controlObject.getFields(), JSON_FIELD_BACKEND_SET_IDS));
650      }
651    }
652
653
654    if (strict)
655    {
656      final List<String> unrecognizedFields =
657           JSONControlDecodeHelper.getControlObjectUnexpectedFields(
658                valueObject, JSON_FIELD_REQUEST_PROCESSOR_ID,
659                JSON_FIELD_BACKEND_SET_IDS);
660      if (! unrecognizedFields.isEmpty())
661      {
662        throw new LDAPException(ResultCode.DECODING_ERROR,
663             ERR_GET_BACKEND_SET_ID_RESPONSE_JSON_UNRECOGNIZED_FIELD.get(
664                  controlObject.toSingleLineString(),
665                  unrecognizedFields.get(0)));
666      }
667    }
668
669
670    return new GetBackendSetIDResponseControl(requestProcessorID,
671         backendSetIDs);
672  }
673
674
675
676  /**
677   * {@inheritDoc}
678   */
679  @Override()
680  public void toString(@NotNull final StringBuilder buffer)
681  {
682    buffer.append("GetBackendSetIDResponseControl(" +
683         "entryBalancingRequestProcessorID='");
684    buffer.append(entryBalancingRequestProcessorID);
685    buffer.append("', backendSetIDs={");
686
687    final Iterator<String> iterator = backendSetIDs.iterator();
688    while (iterator.hasNext())
689    {
690      buffer.append('\'');
691      buffer.append(iterator.next());
692      buffer.append('\'');
693
694      if (iterator.hasNext())
695      {
696        buffer.append(", ");
697      }
698    }
699
700    buffer.append("})");
701  }
702}