Skip to content

Commit 32c9945

Browse files
author
Stephane Landelle
committed
Don't use System.currentTimeMillis, close AsyncHttpClient#280
1 parent 84917f8 commit 32c9945

15 files changed

+57
-31
lines changed

src/main/java/com/ning/http/client/Realm.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
*/
1717
package com.ning.http.client;
1818

19+
import static com.ning.http.util.DateUtil.millisTime;
1920
import static com.ning.http.util.MiscUtil.isNonEmpty;
2021

2122
import org.slf4j.Logger;
@@ -475,7 +476,7 @@ public RealmBuilder clone(Realm clone) {
475476
private void newCnonce() {
476477
try {
477478
MessageDigest md = MessageDigest.getInstance("MD5");
478-
byte[] b = md.digest(String.valueOf(System.currentTimeMillis()).getBytes("ISO-8859-1"));
479+
byte[] b = md.digest(String.valueOf(millisTime()).getBytes("ISO-8859-1"));
479480
cnonce = toHexString(b);
480481
} catch (Exception e) {
481482
throw new SecurityException(e);

src/main/java/com/ning/http/client/ntlm/NTLMEngine.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838

3939
package com.ning.http.client.ntlm;
4040

41+
import static com.ning.http.util.DateUtil.millisTime;
4142
import static com.ning.http.util.MiscUtil.isNonEmpty;
4243

4344
import java.io.UnsupportedEncodingException;
@@ -516,7 +517,7 @@ private static byte[] createBlob(byte[] clientChallenge, byte[] targetInformatio
516517
byte[] blobSignature = new byte[]{(byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00};
517518
byte[] reserved = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
518519
byte[] unknown1 = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
519-
long time = System.currentTimeMillis();
520+
long time = millisTime();
520521
time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
521522
time *= 10000; // tenths of a microsecond.
522523
// convert to little-endian byte array.

src/main/java/com/ning/http/client/oauth/OAuthSignatureCalculator.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
*/
1717
package com.ning.http.client.oauth;
1818

19+
import static com.ning.http.util.DateUtil.millisTime;
1920

2021
import com.ning.http.client.FluentStringsMap;
2122
import com.ning.http.client.Request;
@@ -78,15 +79,15 @@ public OAuthSignatureCalculator(ConsumerKey consumerAuth, RequestToken userAuth)
7879
mac = new ThreadSafeHMAC(consumerAuth, userAuth);
7980
this.consumerAuth = consumerAuth;
8081
this.userAuth = userAuth;
81-
random = new Random(System.identityHashCode(this) + System.currentTimeMillis());
82+
random = new Random(System.identityHashCode(this) + millisTime());
8283
}
8384

8485
//@Override // silly 1.5; doesn't allow this for interfaces
8586

8687
public void calculateAndAddSignature(String baseURL, Request request, RequestBuilderBase<?> requestBuilder) {
8788
String method = request.getMethod(); // POST etc
8889
String nonce = generateNonce();
89-
long timestamp = System.currentTimeMillis() / 1000L;
90+
long timestamp = millisTime() / 1000L;
9091
String signature = calculateSignature(method, baseURL, timestamp, nonce, request.getParams(), request.getQueryParams());
9192
String headerValue = constructAuthHeader(signature, nonce, timestamp);
9293
requestBuilder.setHeader(HEADER_AUTHORIZATION, headerValue);

src/main/java/com/ning/http/client/providers/apache/ApacheResponseFuture.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
*/
1313
package com.ning.http.client.providers.apache;
1414

15+
import static com.ning.http.util.DateUtil.millisTime;
16+
1517
import com.ning.http.client.AsyncHandler;
1618
import com.ning.http.client.Request;
1719
import com.ning.http.client.listenable.AbstractListenableFuture;
@@ -41,7 +43,7 @@ public class ApacheResponseFuture<V> extends AbstractListenableFuture<V> {
4143
private final AtomicBoolean timedOut = new AtomicBoolean(false);
4244
private final AtomicBoolean isDone = new AtomicBoolean(false);
4345
private final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
44-
private final AtomicLong touch = new AtomicLong(System.currentTimeMillis());
46+
private final AtomicLong touch = new AtomicLong(millisTime());
4547
private final AtomicBoolean contentProcessed = new AtomicBoolean(false);
4648
private final Request request;
4749
private final HttpMethodBase method;
@@ -174,7 +176,7 @@ public V get(long timeout, TimeUnit unit) throws InterruptedException, Execution
174176
content = innerFuture.get(timeout, unit);
175177
}
176178
} catch (TimeoutException t) {
177-
if (!contentProcessed.get() && timeout != -1 && ((System.currentTimeMillis() - touch.get()) <= responseTimeoutInMs)) {
179+
if (!contentProcessed.get() && timeout != -1 && ((millisTime() - touch.get()) <= responseTimeoutInMs)) {
178180
return get(timeout, unit);
179181
}
180182

@@ -197,11 +199,11 @@ public V get(long timeout, TimeUnit unit) throws InterruptedException, Execution
197199
* @return <code>true</code> if response has expired and should be terminated.
198200
*/
199201
public boolean hasExpired() {
200-
return responseTimeoutInMs != -1 && ((System.currentTimeMillis() - touch.get()) >= responseTimeoutInMs);
202+
return responseTimeoutInMs != -1 && ((millisTime() - touch.get()) >= responseTimeoutInMs);
201203
}
202204

203205
public void touch() {
204-
touch.set(System.currentTimeMillis());
206+
touch.set(millisTime());
205207
}
206208

207209
public Request getRequest() {

src/main/java/com/ning/http/client/providers/grizzly/GrizzlyAsyncHttpProvider.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
package com.ning.http.client.providers.grizzly;
1515

16+
import static com.ning.http.util.DateUtil.millisTime;
1617
import static com.ning.http.util.MiscUtil.isNonEmpty;
1718

1819
import com.ning.org.jboss.netty.handler.codec.http.CookieDecoder;
@@ -427,7 +428,7 @@ void touchConnection(final Connection c, final Request request) {
427428
if (config != null) {
428429
final long timeout = config.getRequestTimeoutInMs();
429430
if (timeout > 0) {
430-
final long newTimeout = System.currentTimeMillis() + timeout;
431+
final long newTimeout = millisTime() + timeout;
431432
if (resolver != null) {
432433
resolver.setTimeoutMillis(c, newTimeout);
433434
}
@@ -436,7 +437,7 @@ void touchConnection(final Connection c, final Request request) {
436437
final long timeout = clientConfig.getRequestTimeoutInMs();
437438
if (timeout > 0) {
438439
if (resolver != null) {
439-
resolver.setTimeoutMillis(c, System.currentTimeMillis() + timeout);
440+
resolver.setTimeoutMillis(c, millisTime() + timeout);
440441
}
441442
}
442443
}

src/main/java/com/ning/http/client/providers/grizzly/GrizzlyConnectionsPool.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313

1414
package com.ning.http.client.providers.grizzly;
1515

16+
import static com.ning.http.util.DateUtil.millisTime;
17+
1618
import com.ning.http.client.AsyncHttpClientConfig;
1719
import com.ning.http.client.ConnectionsPool;
1820

@@ -310,7 +312,7 @@ private class DelayedRunnable implements Runnable {
310312
@Override
311313
public void run() {
312314
while (isStarted) {
313-
final long currentTimeMs = System.currentTimeMillis();
315+
final long currentTimeMs = millisTime();
314316

315317
for (final IdleConnectionQueue delayQueue : queues) {
316318
if (delayQueue.queue.isEmpty()) continue;
@@ -381,7 +383,7 @@ public IdleConnectionQueue(final long timeout) {
381383

382384
void offer(final Connection c) {
383385
if (timeout >= 0) {
384-
resolver.setTimeoutMs(c, System.currentTimeMillis() + timeout);
386+
resolver.setTimeoutMs(c, millisTime() + timeout);
385387
}
386388
queue.offer(c);
387389
count.incrementAndGet();

src/main/java/com/ning/http/client/providers/jdk/JDKDelegateFuture.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
*/
1313
package com.ning.http.client.providers.jdk;
1414

15+
import static com.ning.http.util.DateUtil.millisTime;
16+
1517
import com.ning.http.client.AsyncHandler;
1618
import com.ning.http.client.ListenableFuture;
1719

@@ -66,7 +68,7 @@ public V get(long timeout, TimeUnit unit) throws InterruptedException, Execution
6668
content = innerFuture.get(timeout, unit);
6769
}
6870
} catch (Throwable t) {
69-
if (!contentProcessed.get() && timeout != -1 && ((System.currentTimeMillis() - touch.get()) <= responseTimeoutInMs)) {
71+
if (!contentProcessed.get() && timeout != -1 && ((millisTime() - touch.get()) <= responseTimeoutInMs)) {
7072
return get(timeout, unit);
7173
}
7274
timedOut.set(true);

src/main/java/com/ning/http/client/providers/jdk/JDKFuture.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
*/
1313
package com.ning.http.client.providers.jdk;
1414

15+
import static com.ning.http.util.DateUtil.millisTime;
16+
1517
import com.ning.http.client.AsyncHandler;
1618
import com.ning.http.client.listenable.AbstractListenableFuture;
1719
import org.slf4j.Logger;
@@ -40,7 +42,7 @@ public class JDKFuture<V> extends AbstractListenableFuture<V> {
4042
protected final AtomicBoolean timedOut = new AtomicBoolean(false);
4143
protected final AtomicBoolean isDone = new AtomicBoolean(false);
4244
protected final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
43-
protected final AtomicLong touch = new AtomicLong(System.currentTimeMillis());
45+
protected final AtomicLong touch = new AtomicLong(millisTime());
4446
protected final AtomicBoolean contentProcessed = new AtomicBoolean(false);
4547
protected final HttpURLConnection urlConnection;
4648
private boolean writeHeaders;
@@ -126,7 +128,7 @@ public V get(long timeout, TimeUnit unit) throws InterruptedException, Execution
126128
content = innerFuture.get(timeout, unit);
127129
}
128130
} catch (TimeoutException t) {
129-
if (!contentProcessed.get() && timeout != -1 && ((System.currentTimeMillis() - touch.get()) <= responseTimeoutInMs)) {
131+
if (!contentProcessed.get() && timeout != -1 && ((millisTime() - touch.get()) <= responseTimeoutInMs)) {
130132
return get(timeout, unit);
131133
}
132134

@@ -149,15 +151,15 @@ public V get(long timeout, TimeUnit unit) throws InterruptedException, Execution
149151
* @return <code>true</code> if response has expired and should be terminated.
150152
*/
151153
public boolean hasExpired() {
152-
return responseTimeoutInMs != -1 && ((System.currentTimeMillis() - touch.get()) > responseTimeoutInMs);
154+
return responseTimeoutInMs != -1 && ((millisTime() - touch.get()) > responseTimeoutInMs);
153155
}
154156

155157
/**
156158
* {@inheritDoc}
157159
*/
158160
/* @Override */
159161
public void touch() {
160-
touch.set(System.currentTimeMillis());
162+
touch.set(millisTime());
161163
}
162164

163165
/**

src/main/java/com/ning/http/client/providers/netty/NettyConnectionsPool.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
*/
1313
package com.ning.http.client.providers.netty;
1414

15+
import static com.ning.http.util.DateUtil.millisTime;
16+
1517
import com.ning.http.client.ConnectionsPool;
1618
import org.jboss.netty.channel.Channel;
1719
import org.slf4j.Logger;
@@ -61,7 +63,7 @@ private static class IdleChannel {
6163
IdleChannel(String uri, Channel channel) {
6264
this.uri = uri;
6365
this.channel = channel;
64-
this.start = System.currentTimeMillis();
66+
this.start = millisTime();
6567
}
6668

6769
@Override
@@ -97,7 +99,7 @@ public void run() {
9799
}
98100

99101
List<IdleChannel> channelsInTimeout = new ArrayList<IdleChannel>();
100-
long currentTime = System.currentTimeMillis();
102+
long currentTime = millisTime();
101103

102104
for (IdleChannel idleChannel : channel2IdleChannel.values()) {
103105
long age = currentTime - idleChannel.start;
@@ -109,7 +111,7 @@ public void run() {
109111
channelsInTimeout.add(idleChannel);
110112
}
111113
}
112-
long endConcurrentLoop = System.currentTimeMillis();
114+
long endConcurrentLoop = millisTime();
113115

114116
for (IdleChannel idleChannel : channelsInTimeout) {
115117
Object attachment = idleChannel.channel.getPipeline().getContext(NettyAsyncHttpProvider.class).getAttachment();
@@ -136,7 +138,7 @@ public void run() {
136138
openChannels += hostChannels.size();
137139
}
138140
log.trace(String.format("%d channel open, %d idle channels closed (times: 1st-loop=%d, 2nd-loop=%d).\n",
139-
openChannels, channelsInTimeout.size(), endConcurrentLoop - currentTime, System.currentTimeMillis() - endConcurrentLoop));
141+
openChannels, channelsInTimeout.size(), endConcurrentLoop - currentTime, millisTime() - endConcurrentLoop));
140142
}
141143

142144
} catch (Throwable t) {

src/main/java/com/ning/http/client/providers/netty/NettyResponseFuture.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
*/
1616
package com.ning.http.client.providers.netty;
1717

18+
import static com.ning.http.util.DateUtil.millisTime;
19+
1820
import com.ning.http.client.AsyncHandler;
1921
import com.ning.http.client.ConnectionPoolKeyStrategy;
2022
import com.ning.http.client.ProxyServer;
@@ -74,8 +76,8 @@ enum STATE {
7476
private volatile Future<?> reaperFuture;
7577
private final AtomicBoolean inAuth = new AtomicBoolean(false);
7678
private final AtomicBoolean statusReceived = new AtomicBoolean(false);
77-
private final AtomicLong touch = new AtomicLong(System.currentTimeMillis());
78-
private final long start = System.currentTimeMillis();
79+
private final AtomicLong touch = new AtomicLong(millisTime());
80+
private final long start = millisTime();
7981
private final NettyAsyncHttpProvider asyncHttpProvider;
8082
private final AtomicReference<STATE> state = new AtomicReference<STATE>(STATE.NEW);
8183
private final AtomicBoolean contentProcessed = new AtomicBoolean(false);
@@ -189,7 +191,7 @@ public boolean cancel(boolean force) {
189191
* @return <code>true</code> if response has expired and should be terminated.
190192
*/
191193
public boolean hasExpired() {
192-
long now = System.currentTimeMillis();
194+
long now = millisTime();
193195
return idleConnectionTimeoutInMs != -1 && ((now - touch.get()) >= idleConnectionTimeoutInMs)
194196
|| responseTimeoutInMs != -1 && ((now - start) >= responseTimeoutInMs);
195197
}
@@ -408,7 +410,7 @@ public boolean getAndSetStatusReceived(boolean sr) {
408410
*/
409411
/* @Override */
410412
public void touch() {
411-
touch.set(System.currentTimeMillis());
413+
touch.set(millisTime());
412414
}
413415

414416
/**

src/main/java/com/ning/http/util/AsyncHttpProviderUtils.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
*/
1313
package com.ning.http.util;
1414

15+
import static com.ning.http.util.DateUtil.millisTime;
16+
1517
import java.io.ByteArrayInputStream;
1618
import java.io.FileNotFoundException;
1719
import java.io.IOException;
@@ -467,7 +469,7 @@ public static Cookie parseCookie(String value) {
467469

468470
public static int convertExpireField(String timestring) {
469471
String trimmedTimeString = removeQuote(timestring.trim());
470-
long now = System.currentTimeMillis();
472+
long now = millisTime();
471473
Date date = null;
472474

473475
for (SimpleDateFormat sdf : simpleDateFormat.get()) {

src/main/java/com/ning/http/util/DateUtil.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,4 +231,7 @@ public DateParseException(String message) {
231231

232232
}
233233

234+
public static long millisTime() {
235+
return System.nanoTime() / 1000000;
236+
}
234237
}

src/test/java/com/ning/http/client/async/AsyncProvidersBasicTest.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
package com.ning.http.client.async;
1717

18+
import static com.ning.http.util.DateUtil.millisTime;
1819
import static com.ning.http.util.MiscUtil.isNonEmpty;
1920
import static org.testng.Assert.assertEquals;
2021
import static org.testng.Assert.assertNull;
@@ -1591,7 +1592,7 @@ public void idleRequestTimeoutTest() throws Exception {
15911592
h.add("Content-Type", "application/x-www-form-urlencoded");
15921593
h.add("LockThread", "true");
15931594

1594-
long t1 = System.currentTimeMillis();
1595+
long t1 = millisTime();
15951596
try {
15961597
client.prepareGet(getTargetUrl()).setHeaders(h).setUrl(getTargetUrl()).execute(new AsyncHandlerAdapter() {
15971598

@@ -1603,7 +1604,7 @@ public void onThrowable(Throwable t) {
16031604
}).get();
16041605
Assert.fail();
16051606
} catch (Throwable ex) {
1606-
final long elapsedTime = System.currentTimeMillis() - t1;
1607+
final long elapsedTime = millisTime() - t1;
16071608
System.out.println("EXPIRED: " + (elapsedTime));
16081609
Assert.assertNotNull(ex.getCause());
16091610
Assert.assertTrue(elapsedTime >= 10000 && elapsedTime <= 25000);

src/test/java/com/ning/http/client/async/PerRequestTimeoutTest.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
*/
1616
package com.ning.http.client.async;
1717

18+
import static com.ning.http.util.DateUtil.millisTime;
19+
1820
import com.ning.http.client.AsyncCompletionHandler;
1921
import com.ning.http.client.AsyncHttpClient;
2022
import com.ning.http.client.AsyncHttpClientConfig;
@@ -171,13 +173,13 @@ public Response onCompleted(Response response) throws Exception {
171173

172174
@Override
173175
public STATE onBodyPartReceived(HttpResponseBodyPart content) throws Exception {
174-
times[0] = System.currentTimeMillis();
176+
times[0] = millisTime();
175177
return super.onBodyPartReceived(content);
176178
}
177179

178180
@Override
179181
public void onThrowable(Throwable t) {
180-
times[1] = System.currentTimeMillis();
182+
times[1] = millisTime();
181183
super.onThrowable(t);
182184
}
183185
});

src/test/java/com/ning/http/client/providers/netty/NettyAsyncResponseTest.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313

1414
package com.ning.http.client.providers.netty;
1515

16+
import static com.ning.http.util.DateUtil.millisTime;
17+
1618
import com.ning.http.client.Cookie;
1719
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
1820
import com.ning.http.client.HttpResponseHeaders;
@@ -38,7 +40,7 @@ public void testCookieParseExpires() {
3840
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
3941
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
4042

41-
Date date = new Date(System.currentTimeMillis() + 60000); // sdf.parse( dateString );
43+
Date date = new Date(millisTime() + 60000); // sdf.parse( dateString );
4244
final String cookieDef = String.format("efmembercheck=true; expires=%s; path=/; domain=.eclipse.org", sdf.format(date));
4345

4446
NettyResponse response = new NettyResponse(new ResponseStatus(null, null, null), new HttpResponseHeaders(null, null, false) {

0 commit comments

Comments
 (0)