mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Jean-Noel Rouvignac
04.55.2013 2cc0baf3e716683c5fb8bc67cee764c46c5eb97d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2009-2010 Sun Microsystems, Inc.
 */
 
package com.forgerock.opendj.util;
 
import static org.forgerock.opendj.ldap.ErrorResultException.*;
 
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
 
import org.forgerock.opendj.ldap.CancelledResultException;
import org.forgerock.opendj.ldap.ErrorResultException;
import org.forgerock.opendj.ldap.FutureResult;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ResultHandler;
 
/**
 * This class provides a skeletal implementation of the {@code FutureResult}
 * interface, to minimize the effort required to implement this interface.
 * <p>
 * This {@code FutureResult} implementation provides the following features:
 * <ul>
 * <li>The {@link #get} methods throw {@link ErrorResultException}s instead of
 * the more generic {@code ExecutionException}s.
 * <li>The {@link #get} methods never throw {@code CancellationException} since
 * requests in this SDK can usually be cancelled via other external means (e.g.
 * the {@code Cancel} extended operation) for which there are well defined error
 * results. Therefore cancellation is always signalled by throwing a
 * {@link CancelledResultException} in order to be consistent with other error
 * results.
 * <li>A {@link ResultHandler} can be provided to the constructor. The result
 * handler will be invoked immediately after the result or error is received but
 * before threads blocked on {@link #get} are released. More specifically,
 * result handler invocation <i>happens-before</i> a call to {@link #get}.
 * <b>NOTE:</b> a result handler which attempts to call {@link #get} will
 * deadlock.
 * <li>Sub-classes may choose to implement specific cancellation cleanup by
 * implementing the {@link #handleCancelRequest} method.
 * </ul>
 *
 * @param <M>
 *          The type of result returned by this future.
 * @param <H>
 *          The type of {@link ResultHandler} associated to this future.
 */
public class AsynchronousFutureResult<M, H extends ResultHandler<? super M>> implements
    FutureResult<M>, ResultHandler<M> {
 
    @SuppressWarnings("serial")
    private final class Sync extends AbstractQueuedSynchronizer {
        // State value representing the initial state before a result has
        // been received.
        private static final int WAITING = 0;
 
        // State value representing that a result has been received and is
        // being processed.
        private static final int PENDING = 1;
 
        // State value representing that the request was cancelled.
        private static final int CANCELLED = 2;
 
        // State value representing that the request has failed.
        private static final int FAIL = 3;
 
        // State value representing that the request has succeeded.
        private static final int SUCCESS = 4;
 
        // These do not need to be volatile since their values are published
        // by updating the state after they are set and reading the state
        // immediately before they are read.
        private ErrorResultException errorResult = null;
 
        private M result = null;
 
        /**
         * Allow all threads to acquire if future has completed.
         */
        @Override
        protected int tryAcquireShared(final int ignore) {
            return innerIsDone() ? 1 : -1;
        }
 
        /**
         * Signal that the future has completed and threads waiting on get() can
         * be released.
         */
        @Override
        protected boolean tryReleaseShared(final int finalState) {
            // Ensures that errorResult/result is published.
            setState(finalState);
            return true;
        }
 
        boolean innerCancel(final boolean mayInterruptIfRunning) {
            if (!isCancelable() || !setStatePending()) {
                return false;
            }
 
            // Perform implementation defined cancellation.
            ErrorResultException errorResult = handleCancelRequest(mayInterruptIfRunning);
            if (errorResult == null) {
                errorResult = newErrorResult(ResultCode.CLIENT_SIDE_USER_CANCELLED);
            }
            this.errorResult = errorResult;
 
            try {
                // Invoke error result completion handler.
                if (handler != null) {
                    handler.handleErrorResult(errorResult);
                }
            } finally {
                releaseShared(CANCELLED); // Publishes errorResult.
            }
 
            return true;
        }
 
        M innerGet() throws ErrorResultException, InterruptedException {
            acquireSharedInterruptibly(0);
            return get0();
        }
 
        M innerGet(final long nanosTimeout) throws ErrorResultException, TimeoutException,
                InterruptedException {
            if (!tryAcquireSharedNanos(0, nanosTimeout)) {
                throw new TimeoutException();
            } else {
                return get0();
            }
        }
 
        boolean innerIsCancelled() {
            return getState() == CANCELLED;
        }
 
        boolean innerIsDone() {
            return getState() > 1;
        }
 
        void innerSetErrorResult(final ErrorResultException errorResult) {
            if (setStatePending()) {
                this.errorResult = errorResult;
 
                try {
                    // Invoke error result completion handler.
                    if (handler != null) {
                        handler.handleErrorResult(errorResult);
                    }
                } finally {
                    releaseShared(FAIL); // Publishes errorResult.
                }
            }
        }
 
        void innerSetResult(final M result) {
            if (setStatePending()) {
                this.result = result;
 
                try {
                    // Invoke result completion handler.
                    if (handler != null) {
                        handler.handleResult(result);
                    }
                } finally {
                    releaseShared(SUCCESS); // Publishes result.
                }
            }
        }
 
        private M get0() throws ErrorResultException {
            if (errorResult != null) {
                // State must be FAILED or CANCELLED.
                throw errorResult;
            } else {
                // State must be SUCCESS.
                return result;
            }
        }
 
        private boolean setStatePending() {
            for (;;) {
                final int s = getState();
                if (s != WAITING) {
                    return false;
                }
                if (compareAndSetState(s, PENDING)) {
                    return true;
                }
            }
        }
    }
 
    private final Sync sync = new Sync();
 
    private final H handler;
 
    private final int requestID;
 
    /**
     * Creates a new asynchronous future result with the provided result handler
     * and a request ID of -1.
     *
     * @param handler
     *            A result handler which will be forwarded the result or error
     *            when it arrives, may be {@code null}.
     */
    public AsynchronousFutureResult(final H handler) {
        this(handler, -1);
    }
 
    /**
     * Creates a new asynchronous future result with the provided result handler
     * and request ID.
     *
     * @param handler
     *            A result handler which will be forwarded the result or error
     *            when it arrives, may be {@code null}.
     * @param requestID
     *            The request ID which will be returned by the default
     *            implementation of {@link #getRequestID}.
     */
    public AsynchronousFutureResult(final H handler, final int requestID) {
        this.handler = handler;
        this.requestID = requestID;
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean cancel(final boolean mayInterruptIfRunning) {
        return sync.innerCancel(mayInterruptIfRunning);
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public final M get() throws ErrorResultException, InterruptedException {
        return sync.innerGet();
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public final M get(final long timeout, final TimeUnit unit) throws ErrorResultException,
            TimeoutException, InterruptedException {
        return sync.innerGet(unit.toNanos(timeout));
    }
 
    /**
     * Returns the result handler associated to this FutureResult.
     *
     * @return the result handler associated to this FutureResult.
     */
    public H getResultHandler() {
        return handler;
    }
 
    /**
     * {@inheritDoc}
     * <p>
     * The default implementation returns the request ID passed in during
     * construction, or -1 if none was provided.
     */
    @Override
    public int getRequestID() {
        return requestID;
    }
 
    /**
     * Sets the error result associated with this future. If ({@code isDone() ==
     * true}) then the error result will be ignored, otherwise the result
     * handler will be invoked if one was provided and, on return, any threads
     * waiting on {@link #get} will be released and the provided error result
     * will be thrown.
     *
     * @param errorResult
     *            The error result.
     */
    @Override
    public final void handleErrorResult(final ErrorResultException errorResult) {
        sync.innerSetErrorResult(errorResult);
    }
 
    /**
     * Sets the result associated with this future. If ({@code isDone() == true}
     * ) then the result will be ignored, otherwise the result handler will be
     * invoked if one was provided and, on return, any threads waiting on
     * {@link #get} will be released and the provided result will be returned.
     *
     * @param result
     *            The result.
     */
    @Override
    public final void handleResult(final M result) {
        sync.innerSetResult(result);
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean isCancelled() {
        return sync.innerIsCancelled();
    }
 
    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean isDone() {
        return sync.innerIsDone();
    }
 
    /**
     * Invoked when {@link #cancel} is called and {@code isDone() == false} and
     * immediately before any threads waiting on {@link #get} are released.
     * Implementations may choose to return a custom error result if needed or
     * return {@code null} if the following default error result is acceptable:
     *
     * <pre>
     * Result result = Responses.newResult(ResultCode.CLIENT_SIDE_USER_CANCELLED);
     * </pre>
     *
     * In addition, implementations may perform other cleanup, for example, by
     * issuing an LDAP abandon request. The default implementation is to do
     * nothing.
     *
     * @param mayInterruptIfRunning
     *            {@code true} if the thread executing executing the response
     *            handler should be interrupted; otherwise, in-progress response
     *            handlers are allowed to complete.
     * @return The custom error result, or {@code null} if the default is
     *         acceptable.
     */
    protected ErrorResultException handleCancelRequest(final boolean mayInterruptIfRunning) {
        // Do nothing by default.
        return null;
    }
 
    /**
     * Indicates whether this future result can be canceled.
     *
     * @return {@code true} if this future result is cancelable or {@code false}
     *         otherwise.
     */
    protected boolean isCancelable() {
        // Return true by default.
        return true;
    }
 
    /**
     * Appends a string representation of this future's state to the provided
     * builder.
     *
     * @param sb
     *            The string builder.
     */
    protected void toString(final StringBuilder sb) {
        sb.append(" state = ");
        sb.append(sync);
    }
 
}