001/*
002 * Copyright 2007-2022 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2007-2022 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) 2007-2022 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.controls;
037
038
039
040import java.util.ArrayList;
041import java.util.Collection;
042
043import com.unboundid.asn1.ASN1Element;
044import com.unboundid.asn1.ASN1Exception;
045import com.unboundid.asn1.ASN1OctetString;
046import com.unboundid.asn1.ASN1Sequence;
047import com.unboundid.ldap.sdk.Attribute;
048import com.unboundid.ldap.sdk.Control;
049import com.unboundid.ldap.sdk.DecodeableControl;
050import com.unboundid.ldap.sdk.LDAPException;
051import com.unboundid.ldap.sdk.LDAPResult;
052import com.unboundid.ldap.sdk.ReadOnlyEntry;
053import com.unboundid.ldap.sdk.ResultCode;
054import com.unboundid.util.Debug;
055import com.unboundid.util.NotMutable;
056import com.unboundid.util.NotNull;
057import com.unboundid.util.Nullable;
058import com.unboundid.util.ThreadSafety;
059import com.unboundid.util.ThreadSafetyLevel;
060import com.unboundid.util.Validator;
061
062import static com.unboundid.ldap.sdk.controls.ControlMessages.*;
063
064
065
066/**
067 * This class provides an implementation of the LDAP pre-read response control
068 * as defined in <A HREF="http://www.ietf.org/rfc/rfc4527.txt">RFC 4527</A>.  It
069 * may be used to return a copy of the target entry immediately before
070 * processing a delete, modify, or modify DN operation.
071 * <BR><BR>
072 * If the corresponding delete, modify, or modify DN request included the
073 * {@link PreReadRequestControl} and the operation was successful, then the
074 * response for that operation should include the pre-read response control with
075 * a read-only copy of the entry as it appeared immediately before processing
076 * the request.  If the operation was not successful, then the pre-read response
077 * control will not be returned.
078 */
079@NotMutable()
080@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
081public final class PreReadResponseControl
082       extends Control
083       implements DecodeableControl
084{
085  /**
086   * The OID (1.3.6.1.1.13.1) for the pre-read response control.
087   */
088  @NotNull public static final String PRE_READ_RESPONSE_OID = "1.3.6.1.1.13.1";
089
090
091
092  /**
093   * The serial version UID for this serializable class.
094   */
095  private static final long serialVersionUID = -4719875382095056686L;
096
097
098
099  // The entry returned in the response control.
100  @NotNull private final ReadOnlyEntry entry;
101
102
103
104  /**
105   * Creates a new empty control instance that is intended to be used only for
106   * decoding controls via the {@code DecodeableControl} interface.
107   */
108  PreReadResponseControl()
109  {
110    entry = null;
111  }
112
113
114
115  /**
116   * Creates a new pre-read response control including the provided entry.
117   *
118   * @param  entry  The entry to include in this pre-read response control.  It
119   *                must not be {@code null}.
120   */
121  public PreReadResponseControl(@NotNull final ReadOnlyEntry entry)
122  {
123    super(PRE_READ_RESPONSE_OID, false, encodeValue(entry));
124
125    this.entry = entry;
126  }
127
128
129
130  /**
131   * Creates a new pre-read response control with the provided information.
132   *
133   * @param  oid         The OID for the control.
134   * @param  isCritical  Indicates whether the control should be marked
135   *                     critical.
136   * @param  value       The encoded value for the control.  This may be
137   *                     {@code null} if no value was provided.
138   *
139   * @throws  LDAPException  If the provided control cannot be decoded as a
140   *                         pre-read response control.
141   */
142  public PreReadResponseControl(@NotNull final String oid,
143                                final boolean isCritical,
144                                @Nullable final ASN1OctetString value)
145         throws LDAPException
146  {
147    super(oid, isCritical, value);
148
149    if (value == null)
150    {
151      throw new LDAPException(ResultCode.DECODING_ERROR,
152                              ERR_PRE_READ_RESPONSE_NO_VALUE.get());
153    }
154
155    final ASN1Sequence entrySequence;
156    try
157    {
158      final ASN1Element entryElement = ASN1Element.decode(value.getValue());
159      entrySequence = ASN1Sequence.decodeAsSequence(entryElement);
160    }
161    catch (final ASN1Exception ae)
162    {
163      Debug.debugException(ae);
164      throw new LDAPException(ResultCode.DECODING_ERROR,
165                              ERR_PRE_READ_RESPONSE_VALUE_NOT_SEQUENCE.get(ae),
166                              ae);
167    }
168
169    final ASN1Element[] entryElements = entrySequence.elements();
170    if (entryElements.length != 2)
171    {
172      throw new LDAPException(ResultCode.DECODING_ERROR,
173                              ERR_PRE_READ_RESPONSE_INVALID_ELEMENT_COUNT.get(
174                                   entryElements.length));
175    }
176
177    final String dn =
178         ASN1OctetString.decodeAsOctetString(entryElements[0]).stringValue();
179
180    final ASN1Sequence attrSequence;
181    try
182    {
183      attrSequence = ASN1Sequence.decodeAsSequence(entryElements[1]);
184    }
185    catch (final ASN1Exception ae)
186    {
187      Debug.debugException(ae);
188      throw new LDAPException(ResultCode.DECODING_ERROR,
189                     ERR_PRE_READ_RESPONSE_ATTRIBUTES_NOT_SEQUENCE.get(ae), ae);
190    }
191
192    final ASN1Element[] attrElements = attrSequence.elements();
193    final Attribute[] attrs = new Attribute[attrElements.length];
194    for (int i=0; i < attrElements.length; i++)
195    {
196      try
197      {
198        attrs[i] =
199             Attribute.decode(ASN1Sequence.decodeAsSequence(attrElements[i]));
200      }
201      catch (final ASN1Exception ae)
202      {
203        Debug.debugException(ae);
204        throw new LDAPException(ResultCode.DECODING_ERROR,
205                       ERR_PRE_READ_RESPONSE_ATTR_NOT_SEQUENCE.get(ae), ae);
206      }
207    }
208
209    entry = new ReadOnlyEntry(dn, attrs);
210  }
211
212
213
214  /**
215   * {@inheritDoc}
216   */
217  @Override()
218  @NotNull()
219  public PreReadResponseControl decodeControl(@NotNull final String oid,
220                                     final boolean isCritical,
221                                     @Nullable final ASN1OctetString value)
222         throws LDAPException
223  {
224    return new PreReadResponseControl(oid, isCritical, value);
225  }
226
227
228
229  /**
230   * Extracts a pre-read response control from the provided result.
231   *
232   * @param  result  The result from which to retrieve the pre-read response
233   *                 control.
234   *
235   * @return  The pre-read response control contained in the provided result, or
236   *          {@code null} if the result did not contain a pre-read response
237   *          control.
238   *
239   * @throws  LDAPException  If a problem is encountered while attempting to
240   *                         decode the pre-read response control contained in
241   *                         the provided result.
242   */
243  @Nullable()
244  public static PreReadResponseControl get(@NotNull final LDAPResult result)
245         throws LDAPException
246  {
247    final Control c = result.getResponseControl(PRE_READ_RESPONSE_OID);
248    if (c == null)
249    {
250      return null;
251    }
252
253    if (c instanceof PreReadResponseControl)
254    {
255      return (PreReadResponseControl) c;
256    }
257    else
258    {
259      return new PreReadResponseControl(c.getOID(), c.isCritical(),
260           c.getValue());
261    }
262  }
263
264
265
266  /**
267   * Encodes the provided information into an octet string that can be used as
268   * the value for this control.
269   *
270   * @param  entry  The entry to include in this pre-read response control.  It
271   *                must not be {@code null}.
272   *
273   * @return  An ASN.1 octet string that can be used as the value for this
274   *          control.
275   */
276  @NotNull()
277  private static ASN1OctetString encodeValue(@NotNull final ReadOnlyEntry entry)
278  {
279    Validator.ensureNotNull(entry);
280
281    final Collection<Attribute> attrs = entry.getAttributes();
282    final ArrayList<ASN1Element> attrElements = new ArrayList<>(attrs.size());
283    for (final Attribute a : attrs)
284    {
285      attrElements.add(a.encode());
286    }
287
288    final ASN1Element[] entryElements =
289    {
290      new ASN1OctetString(entry.getDN()),
291      new ASN1Sequence(attrElements)
292    };
293
294    return new ASN1OctetString(new ASN1Sequence(entryElements).encode());
295  }
296
297
298
299  /**
300   * Retrieves a read-only copy of the entry returned by this post-read response
301   * control.
302   *
303   * @return  A read-only copy of the entry returned by this post-read response
304   *          control.
305   */
306  @NotNull()
307  public ReadOnlyEntry getEntry()
308  {
309    return entry;
310  }
311
312
313
314  /**
315   * {@inheritDoc}
316   */
317  @Override()
318  @NotNull()
319  public String getControlName()
320  {
321    return INFO_CONTROL_NAME_PRE_READ_RESPONSE.get();
322  }
323
324
325
326  /**
327   * {@inheritDoc}
328   */
329  @Override()
330  public void toString(@NotNull final StringBuilder buffer)
331  {
332    buffer.append("PreReadResponseControl(entry=");
333    entry.toString(buffer);
334    buffer.append(", isCritical=");
335    buffer.append(isCritical());
336    buffer.append(')');
337  }
338}