001/*
002 * Copyright 2007-2021 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2007-2021 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-2021 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 com.unboundid.asn1.ASN1Element;
041import com.unboundid.asn1.ASN1OctetString;
042import com.unboundid.asn1.ASN1Sequence;
043import com.unboundid.ldap.sdk.Control;
044import com.unboundid.ldap.sdk.LDAPException;
045import com.unboundid.ldap.sdk.ResultCode;
046import com.unboundid.util.Debug;
047import com.unboundid.util.NotMutable;
048import com.unboundid.util.NotNull;
049import com.unboundid.util.Nullable;
050import com.unboundid.util.StaticUtils;
051import com.unboundid.util.ThreadSafety;
052import com.unboundid.util.ThreadSafetyLevel;
053
054import static com.unboundid.ldap.sdk.controls.ControlMessages.*;
055
056
057
058/**
059 * This class provides an implementation of the LDAP post-read request control
060 * as defined in <A HREF="http://www.ietf.org/rfc/rfc4527.txt">RFC 4527</A>.  It
061 * may be used to request that the server retrieve a copy of the target entry as
062 * it appeared immediately after processing an add, modify, or modify DN
063 * operation.
064 * <BR><BR>
065 * If this control is included in an add, modify, or modify DN request, then the
066 * corresponding response may include a {@link PostReadResponseControl}
067 * containing a version of the entry as it appeared after applying that change.
068 * Note that this response control will only be included if the operation was
069 * successful, so it will not be provided if the operation failed for some
070 * reason (e.g., if the change would have violated the server schema, or if the
071 * requester did not have sufficient permission to perform that operation).
072 * <BR><BR>
073 * The value of this control should contain a set of requested attributes to
074 * include in the entry that is returned.  The server should treat this set of
075 * requested attributes exactly as it treats the requested attributes from a
076 * {@link com.unboundid.ldap.sdk.SearchRequest}.  As is the case with a search
077 * request, if no attributes are specified, then all user attributes will be
078 * included.
079 * <BR><BR>
080 * <H2>Example</H2>
081 * The following example demonstrates the use of the pre-read and post-read
082 * controls.  It will modify an entry to increment the value of the
083 * {@code test-counter} attribute by one, and will use the pre-read and
084 * post-read controls to determine what the previous and updated values are:
085 * <PRE>
086 * // Create a modify request that we can use to increment the value of a
087 * // custom attribute named "test-counter".
088 * ModifyRequest modifyRequest = new ModifyRequest(
089 *      "uid=test.user,ou=People,dc=example,dc=com",
090 *      new Modification(ModificationType.INCREMENT,
091 *           "test-counter", // The attribute to increment.
092 *           "1")); // The amount by which to increment the value.
093 *
094 * // Update the modify request to add both pre-read and post-read request
095 * // controls to see what the entry value was before and after the change.
096 * // We only care about getting the test-counter attribute.
097 * modifyRequest.setControls(
098 *      new PreReadRequestControl("test-counter"),
099 *      new PostReadRequestControl("test-counter"));
100 *
101 * // Process the modify operation in the server.
102 * LDAPResult modifyResult;
103 * try
104 * {
105 *   modifyResult = connection.modify(modifyRequest);
106 *   // If we got here, then the modification should have been successful.
107 * }
108 * catch (LDAPException le)
109 * {
110 *   // This indicates that the operation did not complete successfully.
111 *   modifyResult = le.toLDAPResult();
112 *   ResultCode resultCode = le.getResultCode();
113 *   String errorMessageFromServer = le.getDiagnosticMessage();
114 * }
115 * LDAPTestUtils.assertResultCodeEquals(modifyResult, ResultCode.SUCCESS);
116 *
117 * // Get the pre-read and post-read response controls from the server and
118 * // retrieve the before and after values for the test-counter attribute.
119 * LDAPTestUtils.assertHasControl(modifyResult,
120 *      PreReadResponseControl.PRE_READ_RESPONSE_OID);
121 * PreReadResponseControl preReadResponse =
122 *      PreReadResponseControl.get(modifyResult);
123 * Integer beforeValue =
124 *      preReadResponse.getEntry().getAttributeValueAsInteger("test-counter");
125 *
126 * LDAPTestUtils.assertHasControl(modifyResult,
127 *      PostReadResponseControl.POST_READ_RESPONSE_OID);
128 * PostReadResponseControl postReadResponse =
129 *      PostReadResponseControl.get(modifyResult);
130 * Integer afterValue =
131 *      postReadResponse.getEntry().getAttributeValueAsInteger("test-counter");
132 * </PRE>
133 */
134@NotMutable()
135@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
136public final class PostReadRequestControl
137       extends Control
138{
139  /**
140   * The OID (1.3.6.1.1.13.2) for the post-read request control.
141   */
142  @NotNull public static final String POST_READ_REQUEST_OID = "1.3.6.1.1.13.2";
143
144
145
146  /**
147   * The set of requested attributes that will be used if none are provided.
148   */
149  @NotNull private static final String[] NO_ATTRIBUTES = StaticUtils.NO_STRINGS;
150
151
152
153  /**
154   * The serial version UID for this serializable class.
155   */
156  private static final long serialVersionUID = -4210061989410209462L;
157
158
159
160  // The set of requested attributes to retrieve from the target entry.
161  @NotNull private final String[] attributes;
162
163
164
165  /**
166   * Creates a new post-read request control that will retrieve the specified
167   * set of attributes from the target entry.  It will be marked critical.
168   *
169   * @param  attributes  The set of attributes to retrieve from the target
170   *                     entry.  It behaves in the same way as the set of
171   *                     requested attributes for a search operation.  If this
172   *                     is empty or {@code null}, then all user attributes
173   *                     will be returned.
174   */
175  public PostReadRequestControl(@Nullable final String... attributes)
176  {
177    this(true, attributes);
178  }
179
180
181
182  /**
183   * Creates a new post-read request control that will retrieve the specified
184   * set of attributes from the target entry.
185   *
186   * @param  isCritical  Indicates whether this control should be marked
187   *                     critical.
188   * @param  attributes  The set of attributes to retrieve from the target
189   *                     entry.  It behaves in the same way as the set of
190   *                     requested attributes for a search operation.  If this
191   *                     is empty or {@code null}, then all user attributes
192   *                     will be returned.
193   */
194  public PostReadRequestControl(final boolean isCritical,
195                                @Nullable final String... attributes)
196  {
197    super(POST_READ_REQUEST_OID, isCritical, encodeValue(attributes));
198
199    if (attributes == null)
200    {
201      this.attributes = NO_ATTRIBUTES;
202    }
203    else
204    {
205      this.attributes = attributes;
206    }
207  }
208
209
210
211  /**
212   * Creates a new post-read request control which is decoded from the provided
213   * generic control.
214   *
215   * @param  control  The generic control to be decoded as a post-read request
216   *                  control.
217   *
218   * @throws  LDAPException  If the provided control cannot be decoded as a
219   *                         post-read request control.
220   */
221  public PostReadRequestControl(@NotNull final Control control)
222         throws LDAPException
223  {
224    super(control);
225
226    final ASN1OctetString value = control.getValue();
227    if (value == null)
228    {
229      throw new LDAPException(ResultCode.DECODING_ERROR,
230                              ERR_POST_READ_REQUEST_NO_VALUE.get());
231    }
232
233    try
234    {
235      final ASN1Element valueElement = ASN1Element.decode(value.getValue());
236      final ASN1Element[] attrElements =
237           ASN1Sequence.decodeAsSequence(valueElement).elements();
238      attributes = new String[attrElements.length];
239      for (int i=0; i < attrElements.length; i++)
240      {
241        attributes[i] =
242             ASN1OctetString.decodeAsOctetString(attrElements[i]).stringValue();
243      }
244    }
245    catch (final Exception e)
246    {
247      Debug.debugException(e);
248      throw new LDAPException(ResultCode.DECODING_ERROR,
249                              ERR_POST_READ_REQUEST_CANNOT_DECODE.get(e), e);
250    }
251  }
252
253
254
255  /**
256   * Encodes the provided information into an octet string that can be used as
257   * the value for this control.
258   *
259   * @param  attributes  The set of attributes to retrieve from the target
260   *                     entry.  It behaves in the same way as the set of
261   *                     requested attributes for a search operation.  If this
262   *                     is empty or {@code null}, then all user attributes
263   *                     will be returned.
264   *
265   * @return  An ASN.1 octet string that can be used as the value for this
266   *          control.
267   */
268  @NotNull()
269  private static ASN1OctetString encodeValue(
270                      @Nullable final String[] attributes)
271  {
272    if ((attributes == null) || (attributes.length == 0))
273    {
274      return new ASN1OctetString(new ASN1Sequence().encode());
275    }
276
277    final ASN1OctetString[] elements = new ASN1OctetString[attributes.length];
278    for (int i=0; i < attributes.length; i++)
279    {
280      elements[i] = new ASN1OctetString(attributes[i]);
281    }
282
283    return new ASN1OctetString(new ASN1Sequence(elements).encode());
284  }
285
286
287
288  /**
289   * Retrieves the set of attributes that will be requested for inclusion in the
290   * entry returned in the response control.
291   *
292   * @return  The set of attributes that will be requested for inclusion in the
293   *          entry returned in the response control, or an empty array if all
294   *          user attributes should be returned.
295   */
296  @NotNull()
297  public String[] getAttributes()
298  {
299    return attributes;
300  }
301
302
303
304  /**
305   * {@inheritDoc}
306   */
307  @Override()
308  @NotNull()
309  public String getControlName()
310  {
311    return INFO_CONTROL_NAME_POST_READ_REQUEST.get();
312  }
313
314
315
316  /**
317   * {@inheritDoc}
318   */
319  @Override()
320  public void toString(@NotNull final StringBuilder buffer)
321  {
322    buffer.append("PostReadRequestControl(attributes={");
323    for (int i=0; i < attributes.length; i++)
324    {
325      if (i > 0)
326      {
327        buffer.append(", ");
328      }
329      buffer.append('\'');
330      buffer.append(attributes[i]);
331      buffer.append('\'');
332    }
333    buffer.append("}, isCritical=");
334    buffer.append(isCritical());
335    buffer.append(')');
336  }
337}