Skip to content

Commit 3207479

Browse files
committed
拦截器支持异步等待(可做网络请求),默认超时时间30秒,可调用Card.setTimeout()设置
1 parent ed75a8b commit 3207479

File tree

17 files changed

+443
-52
lines changed

17 files changed

+443
-52
lines changed

GoRouter/src/main/java/com/wyjson/router/callback/GoCallback.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.wyjson.router.callback;
22

3+
import androidx.annotation.NonNull;
4+
35
import com.wyjson.router.core.Card;
46

57
public interface GoCallback {
@@ -30,5 +32,5 @@ public interface GoCallback {
3032
*
3133
* @param card
3234
*/
33-
void onInterrupt(Card card, Throwable exception);
35+
void onInterrupt(Card card, @NonNull Throwable exception);
3436
}

GoRouter/src/main/java/com/wyjson/router/core/Card.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ public final class Card extends CardMeta {
2828
private int enterAnim = -1;
2929
private int exitAnim = -1;
3030

31+
private Throwable interceptorException;// 拦截执行中断异常信息
32+
private int timeout = 300;// go() timeout, TimeUnit.Second
33+
3134
public Uri getUri() {
3235
return uri;
3336
}
@@ -272,4 +275,20 @@ public Card greenChannel() {
272275
this.greenChannel = true;
273276
return this;
274277
}
278+
279+
public Throwable getInterceptorException() {
280+
return interceptorException;
281+
}
282+
283+
public void setInterceptorException(Throwable interceptorException) {
284+
this.interceptorException = interceptorException;
285+
}
286+
287+
public int getTimeout() {
288+
return timeout;
289+
}
290+
291+
public void setTimeout(int timeout) {
292+
this.timeout = timeout;
293+
}
275294
}

GoRouter/src/main/java/com/wyjson/router/core/CardMeta.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import com.wyjson.router.enums.ParamType;
44
import com.wyjson.router.enums.RouteType;
5-
import com.wyjson.router.exception.RouterException;
65
import com.wyjson.router.utils.TextUtils;
76

87
import java.util.HashMap;
@@ -64,7 +63,7 @@ private RouteType extractType(String path) {
6463
} catch (Exception ignored) {
6564
}
6665
if (routeType == null) {
67-
throw new RouterException("The route type is incorrect! The path[" + path + "] type can only end with " + RouteType.toStringByValues());
66+
GoRouter.logger.warning(null, "The route type is incorrect! The path[" + path + "] type can only end with " + RouteType.toStringByValues());
6867
}
6968
return routeType;
7069
}

GoRouter/src/main/java/com/wyjson/router/core/GoRouter.java

Lines changed: 67 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
import com.wyjson.router.callback.GoCallback;
1818
import com.wyjson.router.enums.ParamType;
19+
import com.wyjson.router.enums.RouteType;
1920
import com.wyjson.router.exception.RouterException;
2021
import com.wyjson.router.interceptor.InterceptorCallback;
2122
import com.wyjson.router.interceptor.InterceptorUtils;
@@ -27,17 +28,29 @@
2728
import com.wyjson.router.interfaces.PathReplaceService;
2829
import com.wyjson.router.interfaces.PretreatmentService;
2930
import com.wyjson.router.service.ServiceHelper;
31+
import com.wyjson.router.thread.DefaultPoolExecutor;
32+
import com.wyjson.router.utils.DefaultLogger;
33+
import com.wyjson.router.utils.ILogger;
3034
import com.wyjson.router.utils.MapUtils;
3135
import com.wyjson.router.utils.TextUtils;
3236

3337
import java.lang.reflect.Field;
3438
import java.util.HashMap;
3539
import java.util.Map;
40+
import java.util.concurrent.ThreadPoolExecutor;
3641

3742
public final class GoRouter {
3843

44+
public static final String ROUTER_RAW_URI = "router_raw_uri";
45+
public static final String ROUTER_PARAM_INJECT = "router_param_inject";
46+
47+
private final Handler mHandler = new Handler(Looper.getMainLooper());
48+
private static final Map<String, CardMeta> routes = new HashMap<>();
49+
private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInstance();
50+
public static ILogger logger = new DefaultLogger("GoRouter");
51+
3952
private GoRouter() {
40-
mHandler = new Handler(Looper.getMainLooper());
53+
logger.info(null, "GoRouter init!");
4154
InterceptorUtils.clearIterator();
4255
addService(InterceptorServiceImpl.class);
4356
}
@@ -50,19 +63,41 @@ public static GoRouter getInstance() {
5063
return InstanceHolder.mInstance;
5164
}
5265

53-
public static final String ROUTER_RAW_URI = "router_raw_uri";
54-
public static final String ROUTER_PARAM_INJECT = "router_param_inject";
55-
private final Handler mHandler;
66+
public static synchronized void setExecutor(ThreadPoolExecutor tpe) {
67+
executor = tpe;
68+
}
5669

57-
private static final Map<String, CardMeta> routes = new HashMap<>();
70+
public ThreadPoolExecutor getExecutor() {
71+
return executor;
72+
}
73+
74+
public static void setLogger(ILogger userLogger) {
75+
if (userLogger != null) {
76+
logger = userLogger;
77+
}
78+
}
79+
80+
static synchronized void openLog() {
81+
logger.showLog(true);
82+
logger.info(null, "GoRouter openLog");
83+
}
84+
85+
public static synchronized void printStackTrace() {
86+
logger.showStackTrace(true);
87+
logger.info(null, "GoRouter printStackTrace");
88+
}
5889

5990
@Nullable
6091
CardMeta getCardMeta(Card card) {
6192
return routes.get(card.getPath());
6293
}
6394

6495
void addCardMeta(CardMeta cardMeta) {
65-
routes.put(cardMeta.getPath(), cardMeta);
96+
if (cardMeta.getType() != null) {
97+
routes.put(cardMeta.getPath(), cardMeta);
98+
} else {
99+
throw new RouterException("The route type is incorrect! The path[" + cardMeta.getPath() + "] type can only end with " + RouteType.toStringByValues());
100+
}
66101
}
67102

68103
/**
@@ -189,6 +224,7 @@ Object go(Context context, Card card, int requestCode, GoCallback callback) {
189224
return null;
190225
}
191226
card.setContext(context);
227+
card.setInterceptorException(null);
192228
CardMeta cardMeta = getCardMeta(card);
193229
if (cardMeta != null) {
194230
card.setPathClass(cardMeta.getPathClass());
@@ -215,9 +251,11 @@ Object go(Context context, Card card, int requestCode, GoCallback callback) {
215251
card.withString(GoRouter.ROUTER_RAW_URI, rawUri.toString());
216252
}
217253

218-
if (callback != null) {
219-
callback.onFound(card);
220-
}
254+
runInMainThread(() -> {
255+
if (callback != null) {
256+
callback.onFound(card);
257+
}
258+
});
221259
switch (card.getType()) {
222260
case ACTIVITY:
223261
InterceptorService interceptorService = getService(InterceptorService.class);
@@ -229,10 +267,12 @@ public void onContinue(Card card) {
229267
}
230268

231269
@Override
232-
public void onInterrupt(Card card, Throwable exception) {
233-
if (callback != null) {
234-
callback.onInterrupt(card, exception);
235-
}
270+
public void onInterrupt(Card card, @NonNull Throwable exception) {
271+
runInMainThread(() -> {
272+
if (callback != null) {
273+
callback.onInterrupt(card, exception);
274+
}
275+
});
236276
}
237277
});
238278
} else {
@@ -295,14 +335,16 @@ private void setValue(Card card, ParamType type, String key, String value) {
295335
}
296336

297337
private void onLost(Context context, Card card, GoCallback callback) {
298-
if (callback != null) {
299-
callback.onLost(card);
300-
} else {
301-
DegradeService degradeService = getService(DegradeService.class);
302-
if (degradeService != null) {
303-
degradeService.onLost(context, card);
338+
runInMainThread(() -> {
339+
if (callback != null) {
340+
callback.onLost(card);
341+
} else {
342+
DegradeService degradeService = getService(DegradeService.class);
343+
if (degradeService != null) {
344+
degradeService.onLost(context, card);
345+
}
304346
}
305-
}
347+
});
306348
}
307349

308350
@SuppressLint("WrongConstant")
@@ -353,9 +395,11 @@ private Object goFragment(Context context, Card card, Class<?> cls, GoCallback c
353395
if (instance instanceof Fragment) {
354396
((Fragment) instance).setArguments(card.getExtras());
355397
}
356-
if (callback != null) {
357-
callback.onArrival(card);
358-
}
398+
runInMainThread(() -> {
399+
if (callback != null) {
400+
callback.onArrival(card);
401+
}
402+
});
359403
return instance;
360404
} catch (Exception e) {
361405
e.printStackTrace();
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package com.wyjson.router.interceptor;
22

3+
import androidx.annotation.NonNull;
4+
35
import com.wyjson.router.core.Card;
46

57
public interface InterceptorCallback {
68

79
void onContinue(Card card);
810

9-
void onInterrupt(Card card, Throwable exception);
11+
void onInterrupt(Card card, @NonNull Throwable exception);
1012
}

GoRouter/src/main/java/com/wyjson/router/interceptor/InterceptorUtils.java

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
package com.wyjson.router.interceptor;
22

3-
import androidx.annotation.NonNull;
4-
53
import com.wyjson.router.exception.RouterException;
64
import com.wyjson.router.interfaces.IInterceptor;
75

8-
import java.util.Iterator;
96
import java.util.Map;
107

118
public class InterceptorUtils {
@@ -15,6 +12,10 @@ private InterceptorUtils() {
1512

1613
private static final Map<Integer, IInterceptor> interceptors = new UniqueKeyTreeMap<>("More than one interceptors use same priority [%s]");
1714

15+
public static Map<Integer, IInterceptor> getInterceptors() {
16+
return interceptors;
17+
}
18+
1819
/**
1920
* 相同优先级添加会catch
2021
* 调用时机可以在application或插件模块加载时
@@ -47,15 +48,6 @@ public static void setInterceptor(int priority, Class<? extends IInterceptor> in
4748
addInterceptor(priority, interceptor, true);
4849
}
4950

50-
@NonNull
51-
public static Iterator<Map.Entry<Integer, IInterceptor>> getIterator() {
52-
return interceptors.entrySet().iterator();
53-
}
54-
55-
public static int getIteratorSize() {
56-
return interceptors.size();
57-
}
58-
5951
public static void clearIterator() {
6052
interceptors.clear();
6153
}

GoRouter/src/main/java/com/wyjson/router/interceptor/service/impl/InterceptorServiceImpl.java

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,64 @@
11
package com.wyjson.router.interceptor.service.impl;
22

33
import com.wyjson.router.core.Card;
4+
import com.wyjson.router.core.GoRouter;
5+
import com.wyjson.router.exception.RouterException;
46
import com.wyjson.router.interceptor.InterceptorCallback;
57
import com.wyjson.router.interceptor.InterceptorUtils;
68
import com.wyjson.router.interceptor.service.InterceptorService;
79
import com.wyjson.router.interfaces.IInterceptor;
10+
import com.wyjson.router.thread.CancelableCountDownLatch;
11+
import com.wyjson.router.utils.MapUtils;
812

913
import java.util.Iterator;
1014
import java.util.Map;
15+
import java.util.concurrent.TimeUnit;
1116

1217
public class InterceptorServiceImpl implements InterceptorService {
1318

1419
@Override
1520
public void doInterceptions(Card card, InterceptorCallback callback) {
16-
if (InterceptorUtils.getIteratorSize() > 0) {
17-
Iterator<Map.Entry<Integer, IInterceptor>> iterator = InterceptorUtils.getIterator();
18-
execute(card, iterator, callback);
21+
if (MapUtils.isNotEmpty(InterceptorUtils.getInterceptors())) {
22+
Iterator<Map.Entry<Integer, IInterceptor>> iterator = InterceptorUtils.getInterceptors().entrySet().iterator();
23+
GoRouter.getInstance().getExecutor().execute(new Runnable() {
24+
@Override
25+
public void run() {
26+
CancelableCountDownLatch interceptorCounter = new CancelableCountDownLatch(InterceptorUtils.getInterceptors().size());
27+
try {
28+
execute(card, iterator, interceptorCounter);
29+
interceptorCounter.await(card.getTimeout(), TimeUnit.SECONDS);
30+
if (interceptorCounter.getCount() > 0) {
31+
callback.onInterrupt(card, new RouterException("The interceptor processing timed out."));
32+
} else if (card.getInterceptorException() != null) {
33+
callback.onInterrupt(card, card.getInterceptorException());
34+
} else {
35+
callback.onContinue(card);
36+
}
37+
} catch (Exception e) {
38+
callback.onInterrupt(card, new RouterException("The interceptor handles exceptions."));
39+
}
40+
}
41+
});
1942
} else {
2043
callback.onContinue(card);
2144
}
2245
}
2346

24-
25-
private static void execute(Card card, Iterator<Map.Entry<Integer, IInterceptor>> iterator, InterceptorCallback callback) {
47+
private static void execute(Card card, Iterator<Map.Entry<Integer, IInterceptor>> iterator, final CancelableCountDownLatch counter) {
2648
if (iterator.hasNext()) {
27-
Map.Entry<Integer, IInterceptor> entry = iterator.next();
28-
entry.getValue().process(card, new InterceptorCallback() {
49+
iterator.next().getValue().process(card, new InterceptorCallback() {
2950
@Override
3051
public void onContinue(Card card) {
31-
execute(card, iterator, callback);
52+
counter.countDown();
53+
execute(card, iterator, counter);
3254
}
3355

3456
@Override
3557
public void onInterrupt(Card card, Throwable exception) {
36-
callback.onInterrupt(card, exception);
58+
card.setInterceptorException(exception == null ? new RouterException() : exception);
59+
counter.cancel();
3760
}
3861
});
39-
} else {
40-
callback.onContinue(card);
4162
}
4263
}
4364

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.wyjson.router.thread;
2+
3+
import java.util.concurrent.CountDownLatch;
4+
5+
public class CancelableCountDownLatch extends CountDownLatch {
6+
7+
/**
8+
* 构造一个用给定计数初始化的{@link CountDownLatch}
9+
*
10+
* @param count 计算在线程可以通过{@link #await}之前必须调用{@link #countDown}的次数。
11+
* @throws IllegalArgumentException if {@code count} is negative
12+
*/
13+
public CancelableCountDownLatch(int count) {
14+
super(count);
15+
}
16+
17+
public void cancel() {
18+
while (getCount() > 0) {
19+
countDown();
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)