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