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.extensions;
037
038
039
040import com.unboundid.asn1.ASN1Element;
041import com.unboundid.asn1.ASN1Integer;
042import com.unboundid.asn1.ASN1OctetString;
043import com.unboundid.asn1.ASN1Sequence;
044import com.unboundid.ldap.sdk.AsyncRequestID;
045import com.unboundid.ldap.sdk.Control;
046import com.unboundid.ldap.sdk.ExtendedRequest;
047import com.unboundid.ldap.sdk.ExtendedResult;
048import com.unboundid.ldap.sdk.LDAPConnection;
049import com.unboundid.ldap.sdk.LDAPException;
050import com.unboundid.ldap.sdk.ResultCode;
051import com.unboundid.util.Debug;
052import com.unboundid.util.NotMutable;
053import com.unboundid.util.NotNull;
054import com.unboundid.util.Nullable;
055import com.unboundid.util.ThreadSafety;
056import com.unboundid.util.ThreadSafetyLevel;
057
058import static com.unboundid.ldap.sdk.extensions.ExtOpMessages.*;
059
060
061
062/**
063 * This class provides an implementation of the LDAP cancel extended request as
064 * defined in <A HREF="http://www.ietf.org/rfc/rfc3909.txt">RFC 3909</A>.  It
065 * may be used to request that the server interrupt processing on another
066 * operation in progress on the same connection.  It behaves much like the
067 * abandon operation, with the exception that both the cancel request and the
068 * operation that is canceled will receive responses, whereas an abandon request
069 * never returns a response, and the operation that is abandoned will also not
070 * receive a response if the abandon is successful.
071 * <BR><BR>
072 * <H2>Example</H2>
073 * The following example initiates an asynchronous modify operation and then
074 * attempts to cancel it:
075 * <PRE>
076 * Modification mod = new Modification(ModificationType.REPLACE,
077 *      "description", "This is the new description.");
078 * ModifyRequest modifyRequest =
079 *      new ModifyRequest("dc=example,dc=com", mod);
080 *
081 * AsyncRequestID asyncRequestID =
082 *      connection.asyncModify(modifyRequest, myAsyncResultListener);
083 *
084 * // Assume that we've waited a reasonable amount of time but the modify
085 * // hasn't completed yet so we'll try to cancel it.
086 *
087 * ExtendedResult cancelResult;
088 * try
089 * {
090 *   cancelResult = connection.processExtendedOperation(
091 *        new CancelExtendedRequest(asyncRequestID));
092 *   // This doesn't necessarily mean that the operation was successful, since
093 *   // some kinds of extended operations (like cancel) return non-success
094 *   // results under normal conditions.
095 * }
096 * catch (LDAPException le)
097 * {
098 *   // For an extended operation, this generally means that a problem was
099 *   // encountered while trying to send the request or read the result.
100 *   cancelResult = new ExtendedResult(le);
101 * }
102 *
103 * switch (cancelResult.getResultCode().intValue())
104 * {
105 *   case ResultCode.CANCELED_INT_VALUE:
106 *     // The modify operation was successfully canceled.
107 *     break;
108 *   case ResultCode.CANNOT_CANCEL_INT_VALUE:
109 *     // This indicates that the server isn't capable of canceling that
110 *     // type of operation.  This probably won't happen for  this kind of
111 *     // modify operation, but it could happen for other kinds of operations.
112 *     break;
113 *   case ResultCode.TOO_LATE_INT_VALUE:
114 *     // This indicates that the cancel request was received too late and the
115 *     // server is intending to process the operation.
116 *     break;
117 *   case ResultCode.NO_SUCH_OPERATION_INT_VALUE:
118 *     // This indicates that the server doesn't know anything about the
119 *     // operation, most likely because it has already completed.
120 *     break;
121 *   default:
122 *     // This suggests that the operation failed for some other reason.
123 *     break;
124 * }
125 * </PRE>
126 */
127@NotMutable()
128@ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE)
129public final class CancelExtendedRequest
130       extends ExtendedRequest
131{
132  /**
133   * The OID (1.3.6.1.1.8) for the cancel extended request.
134   */
135  @NotNull public static final String CANCEL_REQUEST_OID = "1.3.6.1.1.8";
136
137
138
139  /**
140   * The serial version UID for this serializable class.
141   */
142  private static final long serialVersionUID = -7170687636394194183L;
143
144
145
146  // The message ID of the request to cancel.
147  private final int targetMessageID;
148
149
150
151  /**
152   * Creates a new cancel extended request that will cancel the request with the
153   * specified async request ID.
154   *
155   * @param  requestID  The async request ID of the request to cancel.  It must
156   *                    not be {@code null}.
157   */
158  public CancelExtendedRequest(@NotNull final AsyncRequestID requestID)
159  {
160    this(requestID.getMessageID(), null);
161  }
162
163
164
165  /**
166   * Creates a new cancel extended request that will cancel the request with the
167   * specified message ID.
168   *
169   * @param  targetMessageID  The message ID of the request to cancel.
170   */
171  public CancelExtendedRequest(final int targetMessageID)
172  {
173    this(targetMessageID, null);
174  }
175
176
177
178  /**
179   * Creates a new cancel extended request that will cancel the request with the
180   * specified request ID.
181   *
182   * @param  requestID  The async request ID of the request to cancel.  It must
183   *                    not be {@code null}.
184   * @param  controls   The set of controls to include in the request.
185   */
186  public CancelExtendedRequest(@NotNull final AsyncRequestID requestID,
187                               @Nullable final Control[] controls)
188  {
189    this(requestID.getMessageID(), controls);
190  }
191
192
193
194  /**
195   * Creates a new cancel extended request that will cancel the request with the
196   * specified message ID.
197   *
198   * @param  targetMessageID  The message ID of the request to cancel.
199   * @param  controls         The set of controls to include in the request.
200   */
201  public CancelExtendedRequest(final int targetMessageID,
202                               @Nullable final Control[] controls)
203  {
204    super(CANCEL_REQUEST_OID, encodeValue(targetMessageID), controls);
205
206    this.targetMessageID = targetMessageID;
207  }
208
209
210
211  /**
212   * Creates a new cancel extended request from the provided generic extended
213   * request.
214   *
215   * @param  extendedRequest  The generic extended request to use to create this
216   *                          cancel extended request.
217   *
218   * @throws  LDAPException  If a problem occurs while decoding the request.
219   */
220  public CancelExtendedRequest(@NotNull final ExtendedRequest extendedRequest)
221         throws LDAPException
222  {
223    super(extendedRequest);
224
225    final ASN1OctetString value = extendedRequest.getValue();
226    if (value == null)
227    {
228      throw new LDAPException(ResultCode.DECODING_ERROR,
229                              ERR_CANCEL_REQUEST_NO_VALUE.get());
230    }
231
232    try
233    {
234      final ASN1Element valueElement = ASN1Element.decode(value.getValue());
235      final ASN1Element[] elements =
236           ASN1Sequence.decodeAsSequence(valueElement).elements();
237      targetMessageID = ASN1Integer.decodeAsInteger(elements[0]).intValue();
238    }
239    catch (final Exception e)
240    {
241      Debug.debugException(e);
242      throw new LDAPException(ResultCode.DECODING_ERROR,
243                              ERR_CANCEL_REQUEST_CANNOT_DECODE.get(e), e);
244    }
245  }
246
247
248
249  /**
250   * Generates a properly-encoded request value for this cancel extended
251   * request.
252   *
253   * @param  targetMessageID  The message ID of the request to cancel.
254   *
255   * @return  An ASN.1 octet string containing the encoded request value.
256   */
257  @NotNull()
258  private static ASN1OctetString encodeValue(final int targetMessageID)
259  {
260    final ASN1Element[] sequenceValues =
261    {
262      new ASN1Integer(targetMessageID)
263    };
264
265    return new ASN1OctetString(new ASN1Sequence(sequenceValues).encode());
266  }
267
268
269
270  /**
271   * {@inheritDoc}
272   */
273  @Override()
274  @NotNull()
275  protected ExtendedResult process(@NotNull final LDAPConnection connection,
276                                   final int depth)
277            throws LDAPException
278  {
279    if (connection.synchronousMode())
280    {
281      throw new LDAPException(ResultCode.NOT_SUPPORTED,
282           ERR_CANCEL_NOT_SUPPORTED_IN_SYNCHRONOUS_MODE.get());
283    }
284
285    return super.process(connection, depth);
286  }
287
288
289
290  /**
291   * Retrieves the message ID of the request to cancel.
292   *
293   * @return  The message ID of the request to cancel.
294   */
295  public int getTargetMessageID()
296  {
297    return targetMessageID;
298  }
299
300
301
302  /**
303   * {@inheritDoc}
304   */
305  @Override()
306  @NotNull()
307  public CancelExtendedRequest duplicate()
308  {
309    return duplicate(getControls());
310  }
311
312
313
314  /**
315   * {@inheritDoc}
316   */
317  @Override()
318  @NotNull()
319  public CancelExtendedRequest duplicate(@Nullable final Control[] controls)
320  {
321    final CancelExtendedRequest cancelRequest =
322         new CancelExtendedRequest(targetMessageID, controls);
323    cancelRequest.setResponseTimeoutMillis(getResponseTimeoutMillis(null));
324    return cancelRequest;
325  }
326
327
328
329  /**
330   * {@inheritDoc}
331   */
332  @Override()
333  @NotNull()
334  public String getExtendedRequestName()
335  {
336    return INFO_EXTENDED_REQUEST_NAME_CANCEL.get();
337  }
338
339
340
341  /**
342   * {@inheritDoc}
343   */
344  @Override()
345  public void toString(@NotNull final StringBuilder buffer)
346  {
347    buffer.append("CancelExtendedRequest(targetMessageID=");
348    buffer.append(targetMessageID);
349
350    final Control[] controls = getControls();
351    if (controls.length > 0)
352    {
353      buffer.append(", controls={");
354      for (int i=0; i < controls.length; i++)
355      {
356        if (i > 0)
357        {
358          buffer.append(", ");
359        }
360
361        buffer.append(controls[i]);
362      }
363      buffer.append('}');
364    }
365
366    buffer.append(')');
367  }
368}