Skip to content

Commit 1edcf2d

Browse files
author
alafighting
committed
代码细节优化
1 parent ee556c1 commit 1edcf2d

File tree

10 files changed

+89
-183
lines changed

10 files changed

+89
-183
lines changed

app/src/main/java/com/im4j/kakacache/rxjava/demo/MainActivity.java

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -45,29 +45,41 @@ protected void onCreate(@Nullable Bundle savedInstanceState) {
4545

4646
btnTestCache = (Button) findViewById(R.id.btn_test_cache);
4747
btnTestCache.setOnClickListener(view -> {
48-
// 不修改原有代码,增加对Cache的支持
49-
service.listReposForNormal("alafighting")
50-
.compose(KakaCache.transformer(KEY_CACHE, new FirstCacheStrategy()))
51-
.subscribe(data -> {
52-
LogUtils.log("next data=" + data);
53-
}, error -> {
54-
LogUtils.log("error", error);
55-
}, () -> {
56-
LogUtils.log("completed");
57-
});
48+
demoForNormal();
5849
});
5950

6051
btnTestRetrofit = (Button) findViewById(R.id.btn_test_retrofit);
6152
btnTestRetrofit.setOnClickListener(view -> {
62-
// 通过注解,自动支持Cache
63-
service.listReposForKaka("alafighting")
64-
.subscribeOn(Schedulers.io())
65-
.subscribe(data -> {
66-
LogUtils.log("listReposForKaka => "+data);
67-
}, error -> {
68-
LogUtils.log(error);
69-
});
53+
demoForKaka();
7054
});
7155
}
7256

57+
/**
58+
* 案例一:不修改原有代码,增加对Cache的支持
59+
*/
60+
void demoForNormal() {
61+
service.listReposForNormal("alafighting")
62+
.compose(KakaCache.transformer(KEY_CACHE, new FirstCacheStrategy()))
63+
.subscribe(data -> {
64+
LogUtils.log("next data=" + data);
65+
}, error -> {
66+
LogUtils.log("error", error);
67+
}, () -> {
68+
LogUtils.log("completed");
69+
});
70+
}
71+
72+
/**
73+
* 案例二:通过注解,自动支持Cache
74+
*/
75+
void demoForKaka() {
76+
service.listReposForKaka("alafighting")
77+
.subscribeOn(Schedulers.io())
78+
.subscribe(data -> {
79+
LogUtils.log("listReposForKaka => "+data);
80+
}, error -> {
81+
LogUtils.log(error);
82+
});
83+
}
84+
7385
}

library/src/main/java/com/im4j/kakacache/rxjava/KakaCache.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public static void init(Context context) {
5353

5454
public static RxCacheManager manager() {
5555
if (liteOrm == null) {
56-
liteOrm = LiteOrm.newSingleInstance(context, "cache_journal.db");
56+
liteOrm = LiteOrm.newSingleInstance(context, "kakacache_journal.db");
5757
}
5858
liteOrm.setDebugged(true); // open the log
5959

library/src/main/java/com/im4j/kakacache/rxjava/common/utils/Utils.java

Lines changed: 36 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,17 @@
1616
import java.lang.reflect.Type;
1717
import java.lang.reflect.TypeVariable;
1818
import java.lang.reflect.WildcardType;
19-
import java.util.Arrays;
19+
20+
import okhttp3.Request;
21+
import okio.Buffer;
22+
import okio.ByteString;
2023

2124
/**
2225
* 工具类
2326
* @version alafighting 2016-04
2427
*/
2528
public final class Utils {
2629

27-
static final Type[] EMPTY_TYPE_ARRAY = new Type[0];
28-
2930
private Utils() {
3031
}
3132

@@ -74,21 +75,6 @@ public static void checkOffsetAndCount(int arrayLength, int offset, int count) {
7475
+ "; regionLength=" + count);
7576
}
7677
}
77-
public static void checkOffsetAndCount(int offset, int count) {
78-
if ((offset | count) < 0) {
79-
throw new ArrayIndexOutOfBoundsException("regionStart=" + offset
80-
+ "; regionLength=" + count);
81-
}
82-
}
83-
public static void checkBytes(byte[] array, int len) {
84-
if (len < 0) {
85-
throw new ArrayIndexOutOfBoundsException("len=" + len);
86-
}
87-
if (array == null || array.length != len) {
88-
throw new ArrayIndexOutOfBoundsException("array=" + len+"; len="+len);
89-
}
90-
}
91-
9278

9379
/**
9480
* 取父类泛型
@@ -175,54 +161,6 @@ public static Class<?> getRawType(Type type) {
175161
+ "GenericArrayType, but <" + type + "> is of type " + type.getClass().getName());
176162
}
177163

178-
public static String typeToString(Type type) {
179-
return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
180-
}
181-
182-
public static boolean equals(Type a, Type b) {
183-
if (a == b) {
184-
return true; // Also handles (a == null && b == null).
185-
186-
} else if (a instanceof Class) {
187-
return a.equals(b); // Class already specifies equals().
188-
189-
} else if (a instanceof ParameterizedType) {
190-
if (!(b instanceof ParameterizedType)) return false;
191-
ParameterizedType pa = (ParameterizedType) a;
192-
ParameterizedType pb = (ParameterizedType) b;
193-
return equal(pa.getOwnerType(), pb.getOwnerType())
194-
&& pa.getRawType().equals(pb.getRawType())
195-
&& Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());
196-
197-
} else if (a instanceof GenericArrayType) {
198-
if (!(b instanceof GenericArrayType)) return false;
199-
GenericArrayType ga = (GenericArrayType) a;
200-
GenericArrayType gb = (GenericArrayType) b;
201-
return equals(ga.getGenericComponentType(), gb.getGenericComponentType());
202-
203-
} else if (a instanceof WildcardType) {
204-
if (!(b instanceof WildcardType)) return false;
205-
WildcardType wa = (WildcardType) a;
206-
WildcardType wb = (WildcardType) b;
207-
return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
208-
&& Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
209-
210-
} else if (a instanceof TypeVariable) {
211-
if (!(b instanceof TypeVariable)) return false;
212-
TypeVariable<?> va = (TypeVariable<?>) a;
213-
TypeVariable<?> vb = (TypeVariable<?>) b;
214-
return va.getGenericDeclaration() == vb.getGenericDeclaration()
215-
&& va.getName().equals(vb.getName());
216-
217-
} else {
218-
return false; // This isn't a type we support!
219-
}
220-
}
221-
222-
private static boolean equal(Object a, Object b) {
223-
return a == b || (a != null && a.equals(b));
224-
}
225-
226164
public static <T> T newInstance(Class<T> clazz) {
227165
try {
228166
return clazz.newInstance();
@@ -233,6 +171,38 @@ public static <T> T newInstance(Class<T> clazz) {
233171
}
234172
}
235173

174+
/**
175+
* 根据Request生成唯一KEY
176+
* @param request
177+
* @return
178+
*/
179+
public static String buildKey(Request request) {
180+
StringBuilder str = new StringBuilder();
181+
str.append('[');
182+
str.append(request.method());
183+
str.append(']');
184+
str.append('[');
185+
str.append(request.url());
186+
str.append(']');
187+
188+
189+
try {
190+
Buffer buffer = new Buffer();
191+
request.body().writeTo(buffer);
192+
str.append(buffer.readByteString().sha1().hex());
193+
} catch (IOException e) {
194+
LogUtils.log(e);
195+
return "";
196+
}
197+
198+
str.append('-');
199+
str.append(ByteString.of(request.headers().toString().getBytes()).sha1().hex());
200+
201+
return str.toString();
202+
}
203+
204+
205+
236206
public static final String SEPARATOR = File.separator;
237207
/**
238208
* 获取缓存目录路径

library/src/main/java/com/im4j/kakacache/rxjava/core/disk/DiskCache.java

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import com.im4j.kakacache.rxjava.core.disk.source.Source;
1313
import com.im4j.kakacache.rxjava.core.disk.storage.IDiskStorage;
1414

15-
import java.io.IOException;
1615
import java.util.Collection;
1716

1817
/**
@@ -51,11 +50,7 @@ protected <T> T doLoad(String key) throws CacheException {
5150
T value = null;
5251
if (source != null) {
5352
value = (T) mConverter.load(source, new TypeToken<T>(){}.getType());
54-
55-
try {
56-
source.close();
57-
} catch (IOException e) {
58-
}
53+
Utils.close(source);
5954
}
6055
return value;
6156
}
@@ -74,10 +69,7 @@ protected <T> void doSave(String key, T value, int expires, CacheTarget target)
7469
Sink sink = mStorage.create(key);
7570
if (sink != null) {
7671
mConverter.writer(sink, value);
77-
try {
78-
sink.close();
79-
} catch (IOException e) {
80-
}
72+
Utils.close(sink);
8173

8274
long createTime = System.currentTimeMillis();
8375
long expiresTime = createTime + expires;

library/src/main/java/com/im4j/kakacache/rxjava/core/disk/converter/SerializableDiskConverter.java

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import com.im4j.kakacache.rxjava.core.disk.source.BasicSource;
88
import com.im4j.kakacache.rxjava.core.disk.source.Source;
99

10-
import java.io.FileNotFoundException;
1110
import java.io.IOException;
1211
import java.io.ObjectInputStream;
1312
import java.io.ObjectOutputStream;
@@ -26,22 +25,12 @@ public Object load(Source source, Type type) {
2625
try {
2726
oin = new ObjectInputStream(new BasicSource(source));
2827
value = oin.readObject();
29-
} catch (FileNotFoundException e) {
30-
// TODO log
31-
e.printStackTrace();
3228
} catch (IOException e) {
33-
// TODO log
34-
e.printStackTrace();
29+
LogUtils.log(e);
3530
} catch (ClassNotFoundException e) {
36-
// TODO log
37-
e.printStackTrace();
31+
LogUtils.log(e);
3832
} finally {
39-
if (oin != null) {
40-
try {
41-
oin.close();
42-
} catch (IOException ignored) {
43-
}
44-
}
33+
Utils.close(oin);
4534
}
4635
return value;
4736
}
@@ -52,10 +41,7 @@ public void writer(Sink sink, Object data) {
5241
try {
5342
oos = new ObjectOutputStream(new BasicSink(sink));
5443
oos.writeObject(data);
55-
oos.flush(); //缓冲流
56-
oos.close(); //关闭流
57-
} catch (FileNotFoundException e) {
58-
LogUtils.log(e);
44+
oos.flush(); //缓冲流
5945
} catch (IOException e) {
6046
LogUtils.log(e);
6147
} finally {

library/src/main/java/com/im4j/kakacache/rxjava/core/disk/storage/FileDiskStorage.java

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,9 @@ public Sink create(String key) throws CacheException {
5050
return null;
5151
}
5252
File file = new File(mStorageDir, key);
53-
if (!file.exists() || !file.isFile()) {
53+
if (!exists(file) || file.isDirectory()) {
5454
try {
55-
LogUtils.log("createNewFile => "+file);
55+
LogUtils.debug("createNewFile => "+file);
5656
file.createNewFile();
5757
} catch (IOException e) {
5858
LogUtils.log(e);
@@ -106,7 +106,7 @@ public void clear() throws CacheException {
106106

107107
@Override
108108
public long getTotalSize() {
109-
return size(mStorageDir);
109+
return countSize(mStorageDir);
110110
}
111111

112112
@Override
@@ -116,32 +116,22 @@ public long getTotalQuantity() {
116116

117117

118118

119-
public void delete(File file) throws IOException {
120-
// If delete() fails, make sure it's because the file didn't exist!
121-
if (!file.delete() && file.exists()) {
122-
throw new IOException("failed to delete " + file);
123-
}
124-
}
125-
126119
public boolean exists(File file) {
127-
if (file == null) {
128-
return false;
129-
}
130-
return file.exists();
120+
return file != null && file.exists();
131121
}
132122

133-
public long size(File file) {
123+
private long countSize(File file) {
134124
return file.length();
135125
}
136126

137-
public void rename(File from, File to) throws IOException {
138-
delete(to);
139-
if (!from.renameTo(to)) {
140-
throw new IOException("failed to rename " + from + " to " + to);
127+
public void delete(File file) throws IOException {
128+
// If delete() fails, make sure it's because the file didn't exist!
129+
if (!file.delete() && file.exists()) {
130+
throw new IOException("failed to delete " + file);
141131
}
142132
}
143133

144-
public void deleteContents(File directory) throws IOException {
134+
private void deleteContents(File directory) throws IOException {
145135
File[] files = directory.listFiles();
146136
if (files == null) {
147137
throw new IOException("not a readable directory: " + directory);

library/src/main/java/com/im4j/kakacache/rxjava/manager/RxCacheManager.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ public <T> rx.Observable<T> load(final String key) {
6161
return rx.Observable.create(new SimpleSubscribe<T>() {
6262
@Override
6363
T execute() {
64-
LogUtils.log("loadCache key="+key);
64+
LogUtils.debug("loadCache key="+key);
6565
return cache.load(key);
6666
}
6767
});

0 commit comments

Comments
 (0)