1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.directory.ldap.client.api.future;
21
22 import java.util.concurrent.TimeUnit;
23
24 import org.apache.directory.api.ldap.model.message.Response;
25 import org.apache.directory.ldap.client.api.LdapConnection;
26
27
28
29
30
31
32
33
34 public abstract class UniqueResponseFuture<R extends Response> implements ResponseFuture<R>
35 {
36
37 private R response;
38
39
40 protected boolean cancelled = false;
41
42
43 protected Throwable cause;
44
45
46 protected int messageId;
47
48
49 protected LdapConnection connection;
50
51
52 private volatile boolean done = false;
53
54
55
56
57
58
59
60 public UniqueResponseFuture( LdapConnection connection, int messageId )
61 {
62 this.messageId = messageId;
63 this.connection = connection;
64 }
65
66
67
68
69
70
71 @Override
72 public synchronized R get() throws InterruptedException
73 {
74 while ( !done && !cancelled )
75 {
76 wait();
77 }
78
79 return response;
80 }
81
82
83
84
85
86
87 @Override
88 public synchronized R get( long timeout, TimeUnit unit ) throws InterruptedException
89 {
90
91 if ( !done && !cancelled )
92 {
93 wait( unit.toMillis( timeout ) );
94 }
95
96 return response;
97 }
98
99
100
101
102
103
104
105
106 public synchronized void set( R response ) throws InterruptedException
107 {
108 this.response = response;
109
110 done = response != null;
111
112 notifyAll();
113 }
114
115
116
117
118
119 @Override
120 public boolean cancel( boolean mayInterruptIfRunning )
121 {
122 if ( cancelled )
123 {
124 return cancelled;
125 }
126
127
128 cancelled = true;
129
130
131 if ( !connection.isRequestCompleted( messageId ) )
132 {
133 connection.abandon( messageId );
134 }
135
136
137 try
138 {
139 set( null );
140 }
141 catch ( InterruptedException ie )
142 {
143
144 }
145
146 return cancelled;
147 }
148
149
150
151
152
153 @Override
154 public boolean isCancelled()
155 {
156 return cancelled;
157 }
158
159
160
161
162
163
164
165 @Override
166 public boolean isDone()
167 {
168 return done;
169 }
170
171
172
173
174
175 public Throwable getCause()
176 {
177 return cause;
178 }
179
180
181
182
183
184
185 public void setCause( Throwable cause )
186 {
187 this.cause = cause;
188 }
189
190
191
192
193
194
195 public void cancel()
196 {
197
198 cancelled = true;
199
200
201 try
202 {
203 set( null );
204 }
205 catch ( InterruptedException ie )
206 {
207
208 }
209 }
210
211
212
213
214
215 @Override
216 public String toString()
217 {
218 StringBuilder sb = new StringBuilder();
219
220 sb.append( "[msgId : " ).append( messageId ).append( ", " );
221 sb.append( "Canceled :" ).append( cancelled ).append( "]" );
222
223 return sb.toString();
224 }
225 }