001/*
002 * Copyright 2009-2020 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2009-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) 2009-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;
037
038
039
040import java.io.Serializable;
041import java.util.ArrayList;
042
043import com.unboundid.asn1.ASN1OctetString;
044import com.unboundid.asn1.ASN1StreamReader;
045import com.unboundid.asn1.ASN1StreamReaderSequence;
046import com.unboundid.ldap.protocol.LDAPResponse;
047import com.unboundid.util.Debug;
048import com.unboundid.util.Extensible;
049import com.unboundid.util.NotMutable;
050import com.unboundid.util.StaticUtils;
051import com.unboundid.util.ThreadSafety;
052import com.unboundid.util.ThreadSafetyLevel;
053
054import static com.unboundid.ldap.sdk.LDAPMessages.*;
055
056
057
058/**
059 * This class provides a data structure for holding information about an LDAP
060 * intermediate response, which provides the ability for the directory server to
061 * return multiple messages in response to operations that would not otherwise
062 * support it.  Intermediate response messages will only be returned by the
063 * server if the client does something to explicitly indicate that it is able
064 * to accept them (e.g., by requesting an extended operation that may return
065 * intermediate response messages, or by including a control in a request that
066 * may cause the request to return intermediate response messages).
067 * Intermediate response messages may include one or both of the following:
068 * <UL>
069 *   <LI>Response OID -- An optional OID that can be used to identify the type
070 *       of intermediate response.</LI>
071 *   <LI>Value -- An optional element that provides the encoded value for this
072 *       intermediate response.  If a value is provided, then the encoding for
073 *       the value depends on the type of intermediate response.</LI>
074 * </UL>
075 * When requesting an operation which may return intermediate response messages,
076 * an {@link IntermediateResponseListener} must be provided for the associated
077 * request.  If an intermediate response message is returned for a request that
078 * does not have a registered {@code IntermediateResponseListener}, then it will
079 * be silently discarded.
080 */
081@Extensible()
082@NotMutable()
083@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
084public class IntermediateResponse
085       implements Serializable, LDAPResponse
086{
087  /**
088   * The BER type for the intermediate response OID element.
089   */
090  protected static final byte TYPE_INTERMEDIATE_RESPONSE_OID = (byte) 0x80;
091
092
093
094  /**
095   * The BER type for the intermediate response value element.
096   */
097  protected static final byte TYPE_INTERMEDIATE_RESPONSE_VALUE = (byte) 0x81;
098
099
100
101  /**
102   * An empty set of controls that will be used if no controls are provided.
103   */
104  private static final Control[] NO_CONTROLS = new Control[0];
105
106
107
108  /**
109   * The serial version UID for this serializable class.
110   */
111  private static final long serialVersionUID = 218434694212935869L;
112
113
114
115  // The encoded value for this intermediate response, if available.
116  private final ASN1OctetString value;
117
118  // The set of controls for this intermediate response.
119  private final Control[] controls;
120
121  // The message ID for this intermediate response.
122  private final int messageID;
123
124  // The OID for this extended request.
125  private final String oid;
126
127
128
129  /**
130   * Creates a new intermediate response with the provided information.
131   *
132   * @param  oid    The OID for this intermediate response.  It may be
133   *                {@code null} if there is no OID.
134   * @param  value  The value for this intermediate response.  It may be
135   *                {@code null} if there is no value.
136   */
137  public IntermediateResponse(final String oid, final ASN1OctetString value)
138  {
139    this(-1, oid, value, NO_CONTROLS);
140  }
141
142
143
144  /**
145   * Creates a new intermediate response with the provided information.
146   *
147   * @param  messageID  The message ID for the LDAP message containing this
148   *                    intermediate response.
149   * @param  oid        The OID for this intermediate response.  It may be
150   *                    {@code null} if there is no OID.
151   * @param  value      The value for this intermediate response.  It may be
152   *                    {@code null} if there is no value.
153   */
154  public IntermediateResponse(final int messageID, final String oid,
155                              final ASN1OctetString value)
156  {
157    this(messageID, oid, value, NO_CONTROLS);
158  }
159
160
161
162  /**
163   * Creates a new intermediate response with the provided information.
164   *
165   * @param  oid       The OID for this intermediate response.  It may be
166   *                   {@code null} if there is no OID.
167   * @param  value     The value for this intermediate response.  It may be
168   *                   {@code null} if there is no value.
169   * @param  controls  The set of controls for this intermediate response.
170   */
171  public IntermediateResponse(final String oid, final ASN1OctetString value,
172                              final Control[] controls)
173  {
174    this(-1, oid, value, controls);
175  }
176
177
178
179  /**
180   * Creates a new intermediate response with the provided information.
181   *
182   * @param  messageID  The message ID for the LDAP message containing this
183   *                    intermediate response.
184   * @param  oid        The OID for this intermediate response.  It may be
185   *                    {@code null} if there is no OID.
186   * @param  value      The value for this intermediate response.  It may be
187   *                    {@code null} if there is no value.
188   * @param  controls   The set of controls for this intermediate response.
189   */
190  public IntermediateResponse(final int messageID, final String oid,
191                              final ASN1OctetString value,
192                              final Control[] controls)
193  {
194    this.messageID = messageID;
195    this.oid       = oid;
196    this.value     = value;
197
198    if (controls == null)
199    {
200      this.controls = NO_CONTROLS;
201    }
202    else
203    {
204      this.controls = controls;
205    }
206  }
207
208
209
210  /**
211   * Creates a new intermediate response with the information from the provided
212   * intermediate response.
213   *
214   * @param  intermediateResponse  The intermediate response that should be used
215   *                               to create this new intermediate response.
216   */
217  protected IntermediateResponse(
218                 final IntermediateResponse intermediateResponse)
219  {
220    messageID = intermediateResponse.messageID;
221    oid       = intermediateResponse.oid;
222    value     = intermediateResponse.value;
223    controls  = intermediateResponse.controls;
224  }
225
226
227
228  /**
229   * Creates a new intermediate response object with the provided message ID and
230   * with the protocol op and controls read from the given ASN.1 stream reader.
231   *
232   * @param  messageID        The LDAP message ID for the LDAP message that is
233   *                          associated with this intermediate response.
234   * @param  messageSequence  The ASN.1 stream reader sequence used in the
235   *                          course of reading the LDAP message elements.
236   * @param  reader           The ASN.1 stream reader from which to read the
237   *                          protocol op and controls.
238   *
239   * @return  The decoded intermediate response.
240   *
241   * @throws  LDAPException  If a problem occurs while reading or decoding data
242   *                         from the ASN.1 stream reader.
243   */
244  static IntermediateResponse readFrom(final int messageID,
245              final ASN1StreamReaderSequence messageSequence,
246              final ASN1StreamReader reader)
247         throws LDAPException
248  {
249    try
250    {
251      String oid = null;
252      ASN1OctetString value = null;
253
254      final ASN1StreamReaderSequence opSequence = reader.beginSequence();
255      while (opSequence.hasMoreElements())
256      {
257        final byte type = (byte) reader.peek();
258        switch (type)
259        {
260          case TYPE_INTERMEDIATE_RESPONSE_OID:
261            oid = reader.readString();
262            break;
263          case TYPE_INTERMEDIATE_RESPONSE_VALUE:
264            value = new ASN1OctetString(type, reader.readBytes());
265            break;
266          default:
267            throw new LDAPException(ResultCode.DECODING_ERROR,
268                 ERR_INTERMEDIATE_RESPONSE_INVALID_ELEMENT.get(
269                      StaticUtils.toHex(type)));
270        }
271      }
272
273      final Control[] controls;
274      if (messageSequence.hasMoreElements())
275      {
276        final ArrayList<Control> controlList = new ArrayList<>(1);
277        final ASN1StreamReaderSequence controlSequence = reader.beginSequence();
278        while (controlSequence.hasMoreElements())
279        {
280          controlList.add(Control.readFrom(reader));
281        }
282
283        controls = new Control[controlList.size()];
284        controlList.toArray(controls);
285      }
286      else
287      {
288        controls = NO_CONTROLS;
289      }
290
291      return new IntermediateResponse(messageID, oid, value, controls);
292    }
293    catch (final LDAPException le)
294    {
295      Debug.debugException(le);
296      throw le;
297    }
298    catch (final Exception e)
299    {
300      Debug.debugException(e);
301      throw new LDAPException(ResultCode.DECODING_ERROR,
302           ERR_INTERMEDIATE_RESPONSE_CANNOT_DECODE.get(
303                StaticUtils.getExceptionMessage(e)),
304           e);
305    }
306  }
307
308
309
310  /**
311   * {@inheritDoc}
312   */
313  @Override()
314  public int getMessageID()
315  {
316    return messageID;
317  }
318
319
320
321  /**
322   * Retrieves the OID for this intermediate response, if any.
323   *
324   * @return  The OID for this intermediate response, or {@code null} if there
325   *          is no OID for this response.
326   */
327  public final String getOID()
328  {
329    return oid;
330  }
331
332
333
334  /**
335   * Retrieves the encoded value for this intermediate response, if any.
336   *
337   * @return  The encoded value for this intermediate response, or {@code null}
338   *          if there is no value for this response.
339   */
340  public final ASN1OctetString getValue()
341  {
342    return value;
343  }
344
345
346
347  /**
348   * Retrieves the set of controls returned with this intermediate response.
349   * Individual response controls of a specific type may be retrieved and
350   * decoded using the {@code get} method in the response control class.
351   *
352   * @return  The set of controls returned with this intermediate response.
353   */
354  public final Control[] getControls()
355  {
356    return controls;
357  }
358
359
360
361  /**
362   * Retrieves the control with the specified OID.  If there is more than one
363   * control with the given OID, then the first will be returned.
364   *
365   * @param  oid  The OID of the control to retrieve.
366   *
367   * @return  The control with the requested OID, or {@code null} if there is no
368   *          such control for this intermediate response.
369   */
370  public final Control getControl(final String oid)
371  {
372    for (final Control c : controls)
373    {
374      if (c.getOID().equals(oid))
375      {
376        return c;
377      }
378    }
379
380    return null;
381  }
382
383
384
385  /**
386   * Retrieves the user-friendly name for the intermediate response, if
387   * available.  If no user-friendly name has been defined, but a response OID
388   * is available, then that will be returned.  If neither a user-friendly name
389   * nor a response OID are available, then {@code null} will be returned.
390   *
391   * @return  The user-friendly name for this intermediate response, the
392   *          response OID if a user-friendly name is not available but a
393   *          response OID is, or {@code null} if neither a user-friendly name
394   *          nor a response OID are available.
395   */
396  public String getIntermediateResponseName()
397  {
398    // By default, we will return the OID (which may be null).  Subclasses
399    // should override this to provide the user-friendly name.
400    return oid;
401  }
402
403
404
405  /**
406   * Retrieves a human-readable string representation for the contents of the
407   * value for this intermediate response, if appropriate.  If one is provided,
408   * then it should be a relatively compact single-line representation of the
409   * most important elements of the value.
410   *
411   * @return  A human-readable string representation for the contents of the
412   *          value for this intermediate response, or {@code null} if there is
413   *          no value or no string representation is available.
414   */
415  public String valueToString()
416  {
417    return null;
418  }
419
420
421
422  /**
423   * Retrieves a string representation of this intermediate response.
424   *
425   * @return  A string representation of this intermediate response.
426   */
427  @Override()
428  public final String toString()
429  {
430    final StringBuilder buffer = new StringBuilder();
431    toString(buffer);
432    return buffer.toString();
433  }
434
435
436
437  /**
438   * Appends a string representation of this intermediate response to the
439   * provided buffer.
440   *
441   * @param  buffer  The buffer to which the string representation should be
442   *                 appended.
443   */
444  @Override()
445  public void toString(final StringBuilder buffer)
446  {
447    buffer.append("IntermediateResponse(");
448
449    boolean added = false;
450
451    if (messageID >= 0)
452    {
453      buffer.append("messageID=");
454      buffer.append(messageID);
455      added = true;
456    }
457
458    if (oid != null)
459    {
460      if (added)
461      {
462        buffer.append(", ");
463      }
464
465      buffer.append("oid='");
466      buffer.append(oid);
467      buffer.append('\'');
468      added = true;
469    }
470
471    if (controls.length > 0)
472    {
473      if (added)
474      {
475        buffer.append(", ");
476      }
477
478      buffer.append("controls={");
479      for (int i=0; i < controls.length; i++)
480      {
481        if (i > 0)
482        {
483          buffer.append(", ");
484        }
485
486        buffer.append(controls[i]);
487      }
488      buffer.append('}');
489    }
490
491    buffer.append(')');
492  }
493}