├── .gitignore
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── im4j
│ │ └── kakacache
│ │ └── rxjava
│ │ └── demo
│ │ ├── GitHubService.java
│ │ ├── GithubRepoEntity.java
│ │ └── MainActivity.java
│ └── res
│ ├── layout
│ └── actiity_main.xml
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── config.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── libs
│ └── lite-orm-1.9.2.jar
├── proguard-rules.pro
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── im4j
│ │ │ └── kakacache
│ │ │ └── rxjava
│ │ │ ├── KakaCache.java
│ │ │ ├── common
│ │ │ ├── exception
│ │ │ │ ├── ArgumentException.java
│ │ │ │ ├── CacheException.java
│ │ │ │ ├── Exception.java
│ │ │ │ ├── InstanceException.java
│ │ │ │ ├── NotFoundException.java
│ │ │ │ ├── NotImplementException.java
│ │ │ │ ├── NullException.java
│ │ │ │ └── ReadEndException.java
│ │ │ └── utils
│ │ │ │ ├── L.java
│ │ │ │ ├── MemorySizeOf.java
│ │ │ │ └── Utils.java
│ │ │ ├── core
│ │ │ ├── BasicCache.java
│ │ │ ├── CacheCore.java
│ │ │ ├── CacheEntry.java
│ │ │ ├── CacheTarget.java
│ │ │ ├── disk
│ │ │ │ ├── DiskCache.java
│ │ │ │ ├── converter
│ │ │ │ │ ├── GsonDiskConverter.java
│ │ │ │ │ ├── IDiskConverter.java
│ │ │ │ │ ├── KryoDiskConverter.java
│ │ │ │ │ └── SerializableDiskConverter.java
│ │ │ │ ├── journal
│ │ │ │ │ ├── BasicDiskJournal.java
│ │ │ │ │ ├── FIFODiskJournal.java
│ │ │ │ │ ├── IDiskJournal.java
│ │ │ │ │ ├── LFUDiskJournal.java
│ │ │ │ │ ├── LRUDiskJournal.java
│ │ │ │ │ └── UnlimitedDiskJournal.java
│ │ │ │ └── storage
│ │ │ │ │ ├── EmptyDiskStorage.java
│ │ │ │ │ ├── FileDiskStorage.java
│ │ │ │ │ └── IDiskStorage.java
│ │ │ └── memory
│ │ │ │ ├── CloneUtils.java
│ │ │ │ ├── MemoryCache.java
│ │ │ │ ├── journal
│ │ │ │ ├── BasicMemoryJournal.java
│ │ │ │ ├── FIFOMemoryJournal.java
│ │ │ │ ├── IMemoryJournal.java
│ │ │ │ ├── LFUMemoryJournal.java
│ │ │ │ └── LRUMemoryJournal.java
│ │ │ │ └── storage
│ │ │ │ ├── IMemoryStorage.java
│ │ │ │ └── SimpleMemoryStorage.java
│ │ │ ├── manager
│ │ │ └── RxCacheManager.java
│ │ │ └── netcache
│ │ │ ├── ResultData.java
│ │ │ ├── ResultFrom.java
│ │ │ └── strategy
│ │ │ └── CacheStrategy.java
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── im4j
│ └── kakacache
│ └── rxjava
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 |
16 | # Gradle files
17 | .gradle/
18 | build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
29 | # Android Studio Navigation editor temp files
30 | .navigation/
31 |
32 | # Android Studio captures folder
33 | captures/
34 |
35 | # Intellij
36 | *.iml
37 | .idea/
38 |
39 | # Keystore files
40 | *.jks
41 |
42 | .DS_Store
43 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 咔咔缓存(KakaCache)
2 | > 咔咔一声,缓存搞定。这是一个专用于解决Android中网络请求及图片加载的缓存处理框架
3 |
4 | ## 如何使用
5 |
6 | ### 准备Retrofit
7 | ```
8 | retrofit = new Retrofit.Builder()
9 | .baseUrl("https://api.github.com/")
10 | .addConverterFactory(KakaCache.gsonConverter())
11 | .addCallAdapterFactory(KakaCache.rxCallAdapter())
12 | .build();
13 | ```
14 |
15 | ### 定义接口
16 | ```
17 | @GET("users/{user}/repos")
18 | @CACHE(value = "custom_key_listRepos", strategy = CacheAndRemoteStrategy.class)
19 | rx.Observable>> listReposForKaka(@Path("user") String user);
20 | ```
21 |
22 | ### 调用接口
23 | ```
24 | service.listReposForKaka("alafighting")
25 | .subscribeOn(Schedulers.io())
26 | .observeOn(AndroidSchedulers.mainThread())
27 | .subscribe(data -> {
28 | LogUtils.log("listReposForKaka => "+data);
29 | }, error -> {
30 | LogUtils.log(error);
31 | });
32 | ```
33 |
34 | ### or 太麻烦?给你`一步到位`!!
35 |
36 | 在原有代码的基础上,仅需一行代码搞定
37 | ```
38 | .compose(KakaCache.transformer(KEY_CACHE, new FirstCacheStrategy()))
39 | ```
40 |
41 | 在这里声明缓存策略即可,不影响原有代码结构
42 |
43 |
44 | ## 支持特性
45 |
46 | #### 缓存层级 - 更优良可靠的缓存
47 | - Internet临时缓存
48 | - 磁盘缓存
49 | - 内存缓存
50 |
51 | #### 缓存策略 - 尽可能适应多种使用场景
52 | - 仅缓存
53 | - 仅网络
54 | - 优先缓存
55 | - 优先网络
56 | - 先缓存后网络
57 |
58 | #### 缓存置换算法 - 多种实现,按需选择
59 | - 先进先出算法(FIFO):最先进入的内容作为替换对象
60 | - 最近最少使用算法(LFU):最近最少使用的内容作为替换对象
61 | - 最久未使用算法(LRU):最久没有访问的内容作为替换对象
62 | - 非最近使用算法(NMRU):在最近没有使用的内容中随机选择一个作为替换对象
63 | - 其他算法,包括变种算法和组合算法
64 |
65 | #### 存储策略 - 支持不同数据的缓存需求
66 | - 不存储
67 | - 仅内存
68 | - 仅磁盘
69 | - 内存+磁盘
70 |
71 | #### 线程管理 - 异步执行
72 | - 支持多线程操作
73 | - 支持异步执行,UI线程回调
74 |
75 | #### 自动清理 - 自动检查
76 | - 缓存过期后,自动清理
77 | - 存储空间不足时,清理超出数据
78 | - 存储个数超量时,清理超出数据
79 |
80 | #### 配置项 - 约定大于配置
81 | - 策略
82 | - 存储空间大小
83 | - 存储个数
84 | - 有效期
85 | - 是否启用缓存
86 | - 置换算法
87 | - 线程池大小
88 | - 缓存实现
89 | - 任务优先级
90 |
91 | ## **项目分层结构**
92 | ```
93 | common >> core >> manager >> netcache\imagecache
94 | 公用类 >> 存储核心 >> 缓存管理 >> 应用缓存
95 | ```
96 |
97 | - **common** 通用代码,一般为通用工具类或通用基类,也包含丰富语言特性的基础代码等
98 | - **core** 数据存储,负责数据的读取和写入,不关心线程等
99 | - **manager** 缓存管理,包括但不限于线程等的管理
100 | - **netcache** 网络缓存,针对网络请求的特点,优化缓存功能,重点在于数据同步问题
101 | - **imagecache** 图片缓存,因图片的同步要求不那么苛刻,可以适当的放宽缓存条件
102 |
103 | ## 关于
104 |
105 | - 这是一个正在成长中的开源项目…
106 | - 参与项目开发,欢迎入群:574171290
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'me.tatarka.retrolambda'
3 | apply from: "${project.rootProject.file('config.gradle')}"
4 |
5 | android {
6 | compileSdkVersion compile_sdk_version
7 | buildToolsVersion build_tools_version
8 |
9 | defaultConfig {
10 | applicationId "com.im4j.kakacache.rxjava.test"
11 | minSdkVersion min_sdk_version
12 | targetSdkVersion target_sdk_version
13 | versionCode app_version_code
14 | versionName app_version_name
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | compileOptions {
23 | sourceCompatibility JavaVersion.VERSION_1_8
24 | targetCompatibility JavaVersion.VERSION_1_8
25 | }
26 | }
27 |
28 | dependencies {
29 | compile fileTree(dir: 'libs', include: ['*.jar'])
30 | compile project(':library')
31 |
32 | compile "com.android.support:appcompat-v7:${support_version}"
33 |
34 | // rxjava
35 | compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
36 |
37 | // retrofit
38 | compile 'com.squareup.retrofit2:retrofit:2.2.0'
39 | compile 'com.squareup.retrofit2:converter-gson:2.2.0'
40 | compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
41 |
42 | compile 'com.esotericsoftware:kryo:4.0.0'
43 | }
44 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/king/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/com/im4j/kakacache/rxjava/demo/GitHubService.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.demo;
2 |
3 | import java.util.List;
4 |
5 | import io.reactivex.Observable;
6 | import retrofit2.http.GET;
7 | import retrofit2.http.Path;
8 |
9 | /**
10 | * @version alafighting 2016-07
11 | */
12 | public interface GitHubService {
13 |
14 | @GET("users/{user}/repos")
15 | Observable> listReposForNormal(@Path("user") String user);
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/im4j/kakacache/rxjava/demo/GithubRepoEntity.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.demo;
2 |
3 | import com.im4j.kakacache.rxjava.common.utils.MemorySizeOf;
4 |
5 | /**
6 | * @version alafighting 2016-07
7 | */
8 | public class GithubRepoEntity implements MemorySizeOf.SizeOf {
9 |
10 | private String id;
11 | private String name;
12 | private String description;
13 |
14 | public GithubRepoEntity() {
15 | }
16 | public GithubRepoEntity(String id, String name, String description) {
17 | this.id = id;
18 | this.name = name;
19 | this.description = description;
20 | }
21 |
22 | @Override
23 | public String toString() {
24 | return "GithubRepoEntity{" +
25 | "id='" + id + '\'' +
26 | ", name='" + name + '\'' +
27 | ", description='" + description + '\'' +
28 | '}';
29 | }
30 |
31 | public String getId() {
32 | return id;
33 | }
34 |
35 | public void setId(String id) {
36 | this.id = id;
37 | }
38 |
39 | public String getName() {
40 | return name;
41 | }
42 |
43 | public void setName(String name) {
44 | this.name = name;
45 | }
46 |
47 | public String getDescription() {
48 | return description;
49 | }
50 |
51 | public void setDescription(String description) {
52 | this.description = description;
53 | }
54 |
55 | @Override
56 | public long sizeOf() {
57 | return MemorySizeOf.sizeOf(id)
58 | + MemorySizeOf.sizeOf(name)
59 | + MemorySizeOf.sizeOf(description);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/app/src/main/java/com/im4j/kakacache/rxjava/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.demo;
2 |
3 | import android.os.Bundle;
4 | import android.support.annotation.Nullable;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.widget.Button;
7 |
8 | import com.im4j.kakacache.rxjava.KakaCache;
9 | import com.im4j.kakacache.rxjava.common.utils.L;
10 | import com.im4j.kakacache.rxjava.common.utils.Utils;
11 | import com.im4j.kakacache.rxjava.netcache.ResultData;
12 | import com.im4j.kakacache.rxjava.netcache.strategy.CacheStrategy;
13 |
14 | import io.reactivex.android.schedulers.AndroidSchedulers;
15 | import io.reactivex.schedulers.Schedulers;
16 | import retrofit2.Retrofit;
17 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
18 | import retrofit2.converter.gson.GsonConverterFactory;
19 |
20 | /**
21 | * Demo主界面
22 | * @version alafighting 2016-06
23 | */
24 | public class MainActivity extends AppCompatActivity {
25 | static final String KEY_CACHE = "key_cache_listRepos";
26 |
27 | private Retrofit retrofit;
28 | private GitHubService service;
29 |
30 | private Button btnTestCache;
31 |
32 | @Override
33 | protected void onCreate(@Nullable Bundle savedInstanceState) {
34 | super.onCreate(savedInstanceState);
35 | setContentView(R.layout.actiity_main);
36 |
37 | L.isDebug = false;
38 | KakaCache.init(this, Utils.getUsableCacheDir(this));
39 |
40 | retrofit = new Retrofit.Builder()
41 | .baseUrl("https://api.github.com/")
42 | .addConverterFactory(GsonConverterFactory.create())
43 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
44 | .build();
45 |
46 | service = retrofit.create(GitHubService.class);
47 |
48 | btnTestCache = (Button) findViewById(R.id.btn_test_cache);
49 | btnTestCache.setOnClickListener(view -> {
50 | demoForNormal();
51 | });
52 | }
53 |
54 | /**
55 | * 案例一:不修改原有代码,增加对Cache的支持
56 | */
57 | void demoForNormal() {
58 | service.listReposForNormal("imkarl")
59 | .compose(KakaCache.transformer(KEY_CACHE, CacheStrategy.FirstCache))
60 | .subscribeOn(Schedulers.io())
61 | .observeOn(AndroidSchedulers.mainThread())
62 | .subscribe(data -> {
63 | L.log("next data=" + data);
64 | }, error -> {
65 | L.log("error");
66 | L.log(error);
67 | }, () -> {
68 | L.log("completed");
69 | });
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/actiity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LittleFriendsGroup/KakaCache-RxJava/1b1b82d1a5366ca7ca0e8b91a23a33176e2b903f/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | KakaCacheForRxJava
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.2'
9 | classpath 'me.tatarka:gradle-retrolambda:3.6.1'
10 | }
11 | }
12 |
13 | allprojects {
14 | repositories {
15 | jcenter()
16 | maven { url 'http://repo1.maven.org/maven2' }
17 | maven { url "https://jitpack.io" }
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/config.gradle:
--------------------------------------------------------------------------------
1 | ext {
2 | // SDK版本
3 | compile_sdk_version = 24
4 | build_tools_version = "25.0.2"
5 | // 支持的最小版本、目标版本
6 | min_sdk_version = 11
7 | target_sdk_version = 22
8 |
9 | app_version_code = 1
10 | app_version_name = "1.0"
11 |
12 | //support版本
13 | support_version = "25.3.1"
14 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LittleFriendsGroup/KakaCache-RxJava/1b1b82d1a5366ca7ca0e8b91a23a33176e2b903f/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu May 11 20:53:28 CST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'me.tatarka.retrolambda'
3 | apply from: "${project.rootProject.file('config.gradle')}"
4 |
5 | android {
6 | compileSdkVersion compile_sdk_version
7 | buildToolsVersion build_tools_version
8 |
9 | defaultConfig {
10 | minSdkVersion min_sdk_version
11 | targetSdkVersion target_sdk_version
12 | versionCode app_version_code
13 | versionName app_version_name
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | compileOptions {
22 | sourceCompatibility JavaVersion.VERSION_1_8
23 | targetCompatibility JavaVersion.VERSION_1_8
24 | }
25 | }
26 |
27 | dependencies {
28 | compile fileTree(dir: 'libs', include: ['*.jar'])
29 | testCompile 'junit:junit:4.12'
30 |
31 | // rxjava
32 | provided 'io.reactivex.rxjava2:rxandroid:2.0.1'
33 |
34 | // retrofit
35 | provided 'com.squareup.retrofit2:retrofit:2.2.0'
36 | provided 'com.squareup.retrofit2:converter-gson:2.2.0'
37 | provided 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
38 |
39 | // storage
40 | provided 'com.esotericsoftware:kryo:4.0.0'
41 |
42 | // support
43 | provided 'com.android.support:support-annotations:25.3.1'
44 | }
45 |
--------------------------------------------------------------------------------
/library/libs/lite-orm-1.9.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LittleFriendsGroup/KakaCache-RxJava/1b1b82d1a5366ca7ca0e8b91a23a33176e2b903f/library/libs/lite-orm-1.9.2.jar
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/king/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/KakaCache.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava;
2 |
3 | import android.content.Context;
4 |
5 | import com.esotericsoftware.kryo.Kryo;
6 | import com.im4j.kakacache.rxjava.common.utils.L;
7 | import com.im4j.kakacache.rxjava.common.utils.Utils;
8 | import com.im4j.kakacache.rxjava.core.CacheCore;
9 | import com.im4j.kakacache.rxjava.core.disk.converter.KryoDiskConverter;
10 | import com.im4j.kakacache.rxjava.core.disk.journal.LRUDiskJournal;
11 | import com.im4j.kakacache.rxjava.core.disk.storage.EmptyDiskStorage;
12 | import com.im4j.kakacache.rxjava.core.disk.storage.FileDiskStorage;
13 | import com.im4j.kakacache.rxjava.core.memory.journal.LRUMemoryJournal;
14 | import com.im4j.kakacache.rxjava.core.memory.storage.SimpleMemoryStorage;
15 | import com.im4j.kakacache.rxjava.manager.RxCacheManager;
16 | import com.im4j.kakacache.rxjava.netcache.ResultData;
17 | import com.im4j.kakacache.rxjava.netcache.strategy.CacheStrategy;
18 | import com.litesuits.orm.LiteOrm;
19 |
20 | import java.io.File;
21 |
22 | import io.reactivex.Observable;
23 | import io.reactivex.ObservableSource;
24 | import io.reactivex.ObservableTransformer;
25 |
26 | /**
27 | * RxJava的远程数据缓存处理
28 | * @version alafighting 2016-06
29 | */
30 | public final class KakaCache {
31 |
32 | private KakaCache() {
33 | }
34 |
35 | // 缓存默认有效期
36 | private static final int DEFAULT_EXPIRES = 12 * 60 * 60 * 1000;
37 | // 缓存保存路径
38 | private static final String DEFAULT_STORAGE_DIR = "kakacache";
39 |
40 | private static LiteOrm liteOrm;
41 | private static RxCacheManager cacheManager;
42 | private static Context context;
43 | private static File cacheDir;
44 |
45 | public static void init(Context context, File cacheDir) {
46 | KakaCache.context = context.getApplicationContext();
47 | KakaCache.cacheDir = cacheDir;
48 | }
49 |
50 | public static RxCacheManager manager() {
51 | if (liteOrm == null) {
52 | liteOrm = LiteOrm.newSingleInstance(context, "kakacache_journal.db");
53 | }
54 | liteOrm.setDebugged(true); // open the log
55 |
56 | if (cacheManager == null) {
57 | File storageDir = cacheDir;
58 | if (storageDir == null || !storageDir.exists()) {
59 | storageDir = Utils.getUsableCacheDir(context, DEFAULT_STORAGE_DIR);
60 | }
61 | L.log("storageDir="+storageDir);
62 |
63 | CacheCore.Builder coreBuilder = new CacheCore.Builder();
64 | coreBuilder.memory(new SimpleMemoryStorage());
65 | coreBuilder.memoryJournal(new LRUMemoryJournal());
66 | coreBuilder.memoryMax(10 * 1024 * 1024, 1000);
67 | coreBuilder.disk(EmptyDiskStorage.INSTANCE);
68 |
69 | if (storageDir != null) {
70 | storageDir.mkdirs();
71 | try {
72 | FileDiskStorage fileDiskStorage = new FileDiskStorage(storageDir);
73 | coreBuilder.disk(fileDiskStorage);
74 | } catch (Exception ignored) { }
75 | }
76 |
77 | coreBuilder.diskJournal(new LRUDiskJournal(liteOrm));
78 | coreBuilder.diskMax(30 * 1024 * 1024, 10 * 1000);
79 | coreBuilder.diskConverter(new KryoDiskConverter(new Kryo()));
80 | CacheCore core = coreBuilder.create();
81 | cacheManager = new RxCacheManager(core, DEFAULT_EXPIRES);
82 | }
83 | return cacheManager;
84 | }
85 |
86 |
87 |
88 | public static ObservableTransformer> transformer(String key, CacheStrategy strategy) {
89 | return transformer(key, strategy, DEFAULT_EXPIRES);
90 | }
91 | public static ObservableTransformer> transformer(String key, CacheStrategy strategy, int expires) {
92 | return new CacheTransformer(key, strategy, expires);
93 | }
94 |
95 | public static void isDebug(boolean isDebug) {
96 | L.isDebug = isDebug;
97 | liteOrm.setDebugged(isDebug);
98 | }
99 | public static void setLog(L.Printer printer) {
100 | L.usePrinter(printer);
101 | }
102 |
103 |
104 | private static class CacheTransformer implements ObservableTransformer> {
105 | private String key;
106 | private CacheStrategy strategy;
107 | private int expires;
108 |
109 | CacheTransformer(String key, CacheStrategy strategy, int expires) {
110 | this.key = key;
111 | this.strategy = strategy;
112 | this.expires = expires;
113 | }
114 |
115 | @Override
116 | public ObservableSource> apply(Observable source) {
117 | return strategy.execute(key, source, expires);
118 | }
119 | }
120 |
121 | }
122 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/exception/ArgumentException.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.exception;
2 |
3 | /**
4 | * 参数错误
5 | * @version 0.1 king 2016-03
6 | */
7 | public class ArgumentException extends Exception {
8 |
9 | public ArgumentException() {
10 | }
11 |
12 | public ArgumentException(String message) {
13 | super(message);
14 | }
15 |
16 | public ArgumentException(String message, Throwable throwable) {
17 | super(message, throwable);
18 | }
19 |
20 | public ArgumentException(Throwable throwable) {
21 | super(throwable);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/exception/CacheException.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.exception;
2 |
3 | /**
4 | * 缓存处理错误
5 | * @version 0.1 king 2016-03
6 | */
7 | public class CacheException extends Exception {
8 |
9 | public CacheException() {
10 | }
11 |
12 | public CacheException(String message) {
13 | super(message);
14 | }
15 |
16 | public CacheException(String message, Throwable throwable) {
17 | super(message, throwable);
18 | }
19 |
20 | public CacheException(Throwable throwable) {
21 | super(throwable);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/exception/Exception.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.exception;
2 |
3 | /**
4 | * 异常基类
5 | * @version 0.1 king 2016-03
6 | */
7 | class Exception extends RuntimeException {
8 |
9 | public Exception() {
10 | }
11 |
12 | public Exception(String message) {
13 | super(message);
14 | }
15 |
16 | public Exception(String message, Throwable throwable) {
17 | super(message, throwable);
18 | }
19 |
20 | public Exception(Throwable throwable) {
21 | super(throwable);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/exception/InstanceException.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.exception;
2 |
3 | /**
4 | * 实例化错误
5 | * @version 0.1 king 2016-07
6 | */
7 | public class InstanceException extends Exception {
8 |
9 | public InstanceException() {
10 | }
11 |
12 | public InstanceException(String message) {
13 | super(message);
14 | }
15 |
16 | public InstanceException(String message, Throwable throwable) {
17 | super(message, throwable);
18 | }
19 |
20 | public InstanceException(Throwable throwable) {
21 | super(throwable);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/exception/NotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.exception;
2 |
3 | /**
4 | * 找不到目标的错误
5 | * @version 0.1 alafighting 2016-04
6 | */
7 | public class NotFoundException extends Exception {
8 |
9 | public NotFoundException() {
10 | }
11 |
12 | public NotFoundException(String message) {
13 | super(message);
14 | }
15 |
16 | public NotFoundException(String message, Throwable throwable) {
17 | super(message, throwable);
18 | }
19 |
20 | public NotFoundException(Throwable throwable) {
21 | super(throwable);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/exception/NotImplementException.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.exception;
2 |
3 | /**
4 | * 没有实现接口的错误
5 | * @version 0.1 alafighting 2016-07
6 | */
7 | public class NotImplementException extends Exception {
8 |
9 | public NotImplementException() {
10 | }
11 |
12 | public NotImplementException(String message) {
13 | super(message);
14 | }
15 |
16 | public NotImplementException(String message, Throwable throwable) {
17 | super(message, throwable);
18 | }
19 |
20 | public NotImplementException(Throwable throwable) {
21 | super(throwable);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/exception/NullException.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.exception;
2 |
3 | /**
4 | * 空数据错误
5 | * @version 0.1 king 2016-06
6 | */
7 | public class NullException extends Exception {
8 |
9 | public NullException() {
10 | }
11 |
12 | public NullException(String message) {
13 | super(message);
14 | }
15 |
16 | public NullException(String message, Throwable throwable) {
17 | super(message, throwable);
18 | }
19 |
20 | public NullException(Throwable throwable) {
21 | super(throwable);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/exception/ReadEndException.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.exception;
2 |
3 | /**
4 | * 已读取到末尾的异常
5 | * @version 0.1 king 2016-04
6 | */
7 | public class ReadEndException extends Exception {
8 |
9 | public ReadEndException() {
10 | }
11 |
12 | public ReadEndException(String message) {
13 | super(message);
14 | }
15 |
16 | public ReadEndException(String message, Throwable throwable) {
17 | super(message, throwable);
18 | }
19 |
20 | public ReadEndException(Throwable throwable) {
21 | super(throwable);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/utils/L.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.utils;
2 |
3 | import android.text.TextUtils;
4 | import android.util.Log;
5 |
6 | import java.io.PrintWriter;
7 | import java.io.StringWriter;
8 |
9 | /**
10 | * 日志打印工具
11 | * @author imkarl 2017-05
12 | */
13 | public final class L {
14 | private L() {}
15 |
16 | public interface Printer {
17 | void print(int level, StackTraceElement element, String tag, Object msg);
18 | }
19 |
20 | private static class AndroidPrinter implements Printer {
21 | @Override
22 | public void print(int level, StackTraceElement element, String tag, Object msg) {
23 | String className = element.getClassName();
24 | className = className.substring(className.lastIndexOf(".") + 1);
25 | String codeLine = className+'.'+element.getMethodName()+'('+element.getFileName()+':'+element.getLineNumber()+')';
26 | Log.println(level, tag, codeLine);
27 |
28 | String message = toString(msg);
29 | Log.println(level, tag, "\t" + message);
30 | }
31 | private static String toString(Object msg) {
32 | String message;
33 |
34 | if (msg == null) {
35 | message = "[null]";
36 | } else if (msg instanceof Enum) {
37 | Enum enumObj = (Enum) msg;
38 | message = enumObj.getClass().getSimpleName()+"."+enumObj.name();
39 | } else if (msg instanceof Throwable) {
40 | Throwable tr = (Throwable) msg;
41 | StringWriter sw = new StringWriter();
42 | PrintWriter pw = new PrintWriter(sw);
43 | tr.printStackTrace(pw);
44 | pw.flush();
45 | message = sw.toString();
46 | } else {
47 | message = String.valueOf(msg);
48 | }
49 |
50 | if (TextUtils.isEmpty(message)) {
51 | message = "[ ]";
52 | }
53 |
54 | return message;
55 | }
56 | }
57 |
58 |
59 | public static boolean isDebug = true;
60 | private final static int DEBUG = Log.DEBUG;
61 | private final static int INFO = Log.INFO;
62 |
63 | private static Printer mPrinter = new AndroidPrinter();
64 | private static String mTag = "KakaCache";
65 |
66 | public static synchronized L usePrinter(Printer printer) {
67 | mPrinter = printer;
68 | return null;
69 | }
70 | public static synchronized L useTag(String tag) {
71 | mTag = tag;
72 | return null;
73 | }
74 |
75 | public static void debug(Object msg) {
76 | if (isDebug) {
77 | log(DEBUG, msg);
78 | }
79 | }
80 | public static void log(Object msg) {
81 | log(INFO, msg);
82 | }
83 |
84 |
85 | private static void log(int level, Object msg) {
86 | print(level, mTag, msg);
87 | }
88 | private static void print(int level, String tag, Object msg) {
89 | if (mPrinter == null) {
90 | return;
91 | }
92 | StackTraceElement element = new Throwable().getStackTrace()[3];
93 | mPrinter.print(level, element, tag, msg);
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/utils/MemorySizeOf.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.utils;
2 |
3 | import android.graphics.Bitmap;
4 |
5 | import com.im4j.kakacache.rxjava.common.exception.NotImplementException;
6 |
7 | import java.io.ByteArrayOutputStream;
8 | import java.io.FileNotFoundException;
9 | import java.io.IOException;
10 | import java.io.NotSerializableException;
11 | import java.io.ObjectOutputStream;
12 | import java.io.Serializable;
13 |
14 | /**
15 | * 计算内存大小
16 | * @version alafighting 2016-06
17 | *
18 | * FIXME 修复计算方式
19 | */
20 | public final class MemorySizeOf {
21 |
22 | public interface SizeOf {
23 | long sizeOf();
24 | }
25 |
26 | private MemorySizeOf() {
27 | }
28 |
29 | /**
30 | * 计算大小
31 | */
32 | public static long sizeOf(SizeOf obj) {
33 | if (obj == null) {
34 | return 0;
35 | }
36 |
37 | return obj.sizeOf();
38 | }
39 |
40 | /**
41 | * 计算大小
42 | */
43 | public static long sizeOf(Serializable serial) throws NotImplementException {
44 | if (serial == null) {
45 | return 0;
46 | }
47 |
48 | long size = -1;
49 | ByteArrayOutputStream baos = null;
50 | ObjectOutputStream oos = null;
51 | try {
52 | baos = new ByteArrayOutputStream();
53 | oos = new ObjectOutputStream(baos);
54 | oos.writeObject(serial);
55 | oos.flush(); //缓冲流
56 | size = baos.size();
57 | } catch (FileNotFoundException e) {
58 | throw new NotImplementException(e.getMessage());
59 | } catch (NotSerializableException e) {
60 | throw new NotImplementException(e.getMessage() + " does not implement the MemorySizeOf.SizeOf.");
61 | } catch (IOException e) {
62 | L.log(e);
63 | } finally {
64 | Utils.close(oos);
65 | Utils.close(baos);
66 | }
67 | return size;
68 | }
69 |
70 | /**
71 | * 计算大小
72 | */
73 | public static long sizeOf(Bitmap bitmap) {
74 | if (bitmap == null) {
75 | return 0;
76 | }
77 |
78 | long size = -1;
79 | ByteArrayOutputStream baos = null;
80 | try {
81 | baos = new ByteArrayOutputStream();
82 | bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
83 | size = baos.size();
84 | } finally {
85 | Utils.close(baos);
86 | }
87 | return size;
88 | }
89 |
90 | }
91 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/common/utils/Utils.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.common.utils;
2 |
3 | import android.Manifest;
4 | import android.content.Context;
5 | import android.content.pm.PackageManager;
6 | import android.os.Environment;
7 | import android.support.annotation.NonNull;
8 |
9 | import com.im4j.kakacache.rxjava.common.exception.ArgumentException;
10 | import com.im4j.kakacache.rxjava.common.exception.NullException;
11 |
12 | import java.io.Closeable;
13 | import java.io.File;
14 | import java.io.IOException;
15 | import java.lang.reflect.Array;
16 | import java.lang.reflect.GenericArrayType;
17 | import java.lang.reflect.ParameterizedType;
18 | import java.lang.reflect.Type;
19 | import java.lang.reflect.TypeVariable;
20 | import java.lang.reflect.WildcardType;
21 |
22 | import okhttp3.Request;
23 | import okio.Buffer;
24 | import okio.ByteString;
25 |
26 | /**
27 | * 工具类
28 | */
29 | public final class Utils {
30 |
31 | private Utils() {
32 | }
33 |
34 | /**
35 | * 不为空
36 | */
37 | public static T checkNotNull(T obj) {
38 | if (obj == null) {
39 | throw new NullException("Can not be empty.");
40 | }
41 | return obj;
42 | }
43 |
44 | /**
45 | * 不小于0
46 | */
47 | public static long checkNotLessThanZero(long number) {
48 | if (number < 0) {
49 | throw new ArgumentException("Can not be < 0.");
50 | }
51 |
52 | return number;
53 | }
54 |
55 | public static boolean isEmpty(String str) {
56 | return str == null || str.isEmpty();
57 | }
58 |
59 |
60 | public static Class> getRawType(Type type) {
61 | if (type == null) throw new NullPointerException("type == null");
62 |
63 | if (type instanceof Class>) {
64 | // Type is a normal class.
65 | return (Class>) type;
66 | }
67 | if (type instanceof ParameterizedType) {
68 | ParameterizedType parameterizedType = (ParameterizedType) type;
69 |
70 | // I'm not exactly sure why getRawType() returns Type instead of Class. Neal isn't either but
71 | // suspects some pathological case related to nested classes exists.
72 | Type rawType = parameterizedType.getRawType();
73 | if (!(rawType instanceof Class)) throw new IllegalArgumentException();
74 | return (Class>) rawType;
75 | }
76 | if (type instanceof GenericArrayType) {
77 | Type componentType = ((GenericArrayType) type).getGenericComponentType();
78 | return Array.newInstance(getRawType(componentType), 0).getClass();
79 | }
80 | if (type instanceof TypeVariable) {
81 | // We could use the variable's bounds, but that won't work if there are multiple. Having a raw
82 | // type that's more general than necessary is okay.
83 | return Object.class;
84 | }
85 | if (type instanceof WildcardType) {
86 | return getRawType(((WildcardType) type).getUpperBounds()[0]);
87 | }
88 |
89 | throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
90 | + "GenericArrayType, but <" + type + "> is of type " + type.getClass().getName());
91 | }
92 |
93 | /**
94 | * 根据Request生成哈希值
95 | */
96 | public static String getHash(Request request) {
97 | StringBuilder str = new StringBuilder();
98 | str.append('[');
99 | str.append(request.method());
100 | str.append(']');
101 | str.append('[');
102 | str.append(request.url().toString());
103 | str.append(']');
104 |
105 | try {
106 | Buffer buffer = new Buffer();
107 | request.body().writeTo(buffer);
108 | str.append(buffer.readByteString().sha1().hex());
109 | } catch (IOException e) {
110 | L.log(e);
111 | return "";
112 | }
113 |
114 | str.append('-');
115 | str.append(ByteString.of(request.headers().toString().getBytes()).sha1().hex());
116 |
117 | return str.toString();
118 | }
119 |
120 |
121 |
122 |
123 | /**
124 | * 获取外部缓存目录
125 | */
126 | public static File getExternalCacheDir(Context context) {
127 | File cacheDir = context.getExternalCacheDir();
128 | if (cacheDir != null) {
129 | cacheDir.mkdirs();
130 | }
131 | return cacheDir;
132 | }
133 |
134 | /**
135 | * 获取APP缓存目录
136 | */
137 | public static File getCacheDir(Context context) {
138 | File appCacheDir = context.getCacheDir();
139 | if(appCacheDir == null) {
140 | String cacheDirPath = "/data/data/" + context.getPackageName() + "/cache/";
141 | appCacheDir = new File(cacheDirPath);
142 | }
143 | return appCacheDir;
144 | }
145 |
146 | /**
147 | * 获取可用的缓存目录
148 | * @tips 优先外置存储
149 | */
150 | public static File getUsableCacheDir(Context context) {
151 | if (hasExternalStorage(context)) {
152 | return getExternalCacheDir(context);
153 | } else {
154 | return getCacheDir(context);
155 | }
156 | }
157 |
158 | /**
159 | * 获取可用的缓存目录
160 | * @param child 子目录
161 | * @tips 优先外置存储
162 | */
163 | public static File getUsableCacheDir(Context context, String child) {
164 | File dir = getUsableCacheDir(context);
165 | if (dir == null) {
166 | return null;
167 | }
168 | return new File(dir, child);
169 | }
170 |
171 |
172 | /**
173 | * 是否有可用的外置存储
174 | */
175 | public static boolean hasExternalStorage(Context context) {
176 | return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
177 | && hasPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
178 | }
179 | private static boolean hasPermission(Context context, @NonNull String permission) {
180 | int perm = context.checkCallingOrSelfPermission(permission);
181 | return perm == PackageManager.PERMISSION_GRANTED;
182 | }
183 |
184 | public static void close(Closeable close) {
185 | if (close != null) {
186 | try {
187 | closeThrowException(close);
188 | } catch (IOException ignored) {
189 | }
190 | }
191 | }
192 |
193 | public static void closeThrowException(Closeable close) throws IOException {
194 | if (close != null) {
195 | close.close();
196 | }
197 | }
198 |
199 | }
200 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/BasicCache.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core;
2 |
3 | import com.im4j.kakacache.rxjava.common.utils.Utils;
4 |
5 | import java.util.Collection;
6 | import java.util.concurrent.locks.ReadWriteLock;
7 | import java.util.concurrent.locks.ReentrantReadWriteLock;
8 |
9 | /**
10 | * 缓存基类
11 | * @version alafighting 2016-04
12 | */
13 | public abstract class BasicCache {
14 |
15 | private final long mMaxSize;
16 | private final long mMaxQuantity;
17 | private final ReadWriteLock mLock = new ReentrantReadWriteLock();
18 |
19 | public BasicCache(long maxSize, long maxQuantity) {
20 | this.mMaxSize = maxSize;
21 | this.mMaxQuantity = maxQuantity;
22 | }
23 |
24 |
25 | /**
26 | * 读取
27 | */
28 | public final T load(String key) {
29 | Utils.checkNotNull(key);
30 | if (!containsKey(key)) {
31 | return null;
32 | }
33 |
34 | // 过期自动清理
35 | if (isExpiry(key)) {
36 | remove(key);
37 | return null;
38 | }
39 |
40 | mLock.readLock().lock();
41 | try {
42 | // 读取缓存
43 | T value = doLoad(key);
44 | return ensureTypeMatching(value);
45 | } finally {
46 | mLock.readLock().unlock();
47 | }
48 | }
49 |
50 | /**
51 | * 确保类型是匹配的
52 | * @return 如果最终类型和读取的类型不匹配,则返回null
53 | */
54 | @SuppressWarnings("unchecked")
55 | private static T ensureTypeMatching(T value) {
56 | if (value == null) {
57 | return null;
58 | }
59 | // TODO 检查类型是否匹配,避免出现ClassCastException
60 | return value;
61 | }
62 |
63 | /**
64 | * 读取
65 | */
66 | protected abstract T doLoad(String key);
67 |
68 | /**
69 | * 保存
70 | * @param maxAge 最大有效期时长(单位:毫秒)
71 | */
72 | public final boolean save(String key, T value, int maxAge, CacheTarget target) {
73 | Utils.checkNotNull(key);
74 |
75 | if (value == null) {
76 | return remove(key);
77 | }
78 |
79 | // TODO 先写入,后清理。会超出限定条件,需要一定交换空间
80 | boolean status = false;
81 | mLock.writeLock().lock();
82 | try {
83 | // 写入缓存
84 | status = doSave(key, value, maxAge, target);
85 | } finally {
86 | mLock.writeLock().unlock();
87 | }
88 |
89 | // 清理无用数据
90 | clearUnused();
91 | return status;
92 | }
93 |
94 | /**
95 | * 保存
96 | * @param maxAge 最长有效期时长(单位:毫秒)
97 | */
98 | protected abstract boolean doSave(String key, T value, int maxAge, CacheTarget target);
99 |
100 |
101 | /**
102 | * 是否过期
103 | */
104 | protected abstract boolean isExpiry(String key);
105 |
106 | /**
107 | * 是否包含
108 | */
109 | public final boolean containsKey(String key) {
110 | mLock.readLock().lock();
111 | try {
112 | return doContainsKey(key);
113 | } finally {
114 | mLock.readLock().unlock();
115 | }
116 | }
117 |
118 | /**
119 | * 删除缓存
120 | */
121 | public final boolean remove(String key) {
122 | mLock.writeLock().lock();
123 | try {
124 | return doRemove(key);
125 | } finally {
126 | mLock.writeLock().unlock();
127 | }
128 | }
129 |
130 | /**
131 | * 清空缓存
132 | */
133 | public final boolean clear() {
134 | mLock.writeLock().lock();
135 | try {
136 | return doClear();
137 | } finally {
138 | mLock.writeLock().unlock();
139 | }
140 | }
141 |
142 | /**
143 | * 是否包含
144 | */
145 | protected abstract boolean doContainsKey(String key);
146 |
147 | /**
148 | * 删除缓存
149 | */
150 | protected abstract boolean doRemove(String key);
151 |
152 | /**
153 | * 清空缓存
154 | */
155 | protected abstract boolean doClear();
156 |
157 |
158 | /**
159 | * 日志快照
160 | */
161 | public abstract Collection snapshot();
162 |
163 |
164 | /**
165 | * 获取准备丢弃的Key
166 | * @return 准备丢弃的Key(如存储空间不足时,需要清理)
167 | */
168 | public abstract String getLoseKey();
169 |
170 | /**
171 | * 缓存大小
172 | * @return 单位:byte
173 | */
174 | public abstract long getTotalSize();
175 |
176 | /**
177 | * 缓存个数
178 | * @return 单位:个数
179 | */
180 | public abstract long getTotalQuantity();
181 |
182 | /**
183 | * 清理无用缓存
184 | */
185 | public void clearUnused() {
186 | // 清理过期
187 | for (CacheEntry entry : snapshot()) {
188 | if (entry.isExpiry()) {
189 | remove(entry.getKey());
190 | }
191 | }
192 |
193 | // 清理超出缓存
194 | if (mMaxSize != 0) {
195 | while (mMaxSize < getTotalSize()) {
196 | remove(getLoseKey());
197 | }
198 | }
199 | if (mMaxQuantity != 0) {
200 | while (mMaxQuantity < getTotalQuantity()) {
201 | remove(getLoseKey());
202 | }
203 | }
204 | }
205 |
206 | }
207 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/CacheCore.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core;
2 |
3 | import com.im4j.kakacache.rxjava.common.utils.L;
4 | import com.im4j.kakacache.rxjava.common.utils.Utils;
5 | import com.im4j.kakacache.rxjava.core.disk.DiskCache;
6 | import com.im4j.kakacache.rxjava.core.disk.converter.IDiskConverter;
7 | import com.im4j.kakacache.rxjava.core.disk.journal.IDiskJournal;
8 | import com.im4j.kakacache.rxjava.core.disk.storage.IDiskStorage;
9 | import com.im4j.kakacache.rxjava.core.memory.CloneUtils;
10 | import com.im4j.kakacache.rxjava.core.memory.MemoryCache;
11 | import com.im4j.kakacache.rxjava.core.memory.journal.IMemoryJournal;
12 | import com.im4j.kakacache.rxjava.core.memory.storage.IMemoryStorage;
13 |
14 | /**
15 | * 缓存核心
16 | *
17 | * @version 0.1 king 2016-04
18 | */
19 | public class CacheCore {
20 |
21 | private MemoryCache memory;
22 | private DiskCache disk;
23 |
24 | private CacheCore(MemoryCache memory, DiskCache disk) {
25 | this.memory = Utils.checkNotNull(memory);
26 | this.disk = Utils.checkNotNull(disk);
27 | }
28 |
29 |
30 | /**
31 | * 读取
32 | */
33 | public T load(String key) {
34 | if (memory != null) {
35 | T result = memory.load(key);
36 | L.debug("load memory cache key="+key+", value="+result);
37 | if (result != null) {
38 | // FIXME 通过标识符判断是否被篡改
39 | try {
40 | return CloneUtils.deepClone(result);
41 | } catch (Exception e) {
42 | L.debug(e);
43 | }
44 | }
45 | }
46 |
47 | if (disk != null) {
48 | T result = disk.load(key);
49 | L.debug("load disk cache key="+key+", value="+result);
50 | if (result != null) {
51 | return result;
52 | }
53 | }
54 |
55 | return null;
56 | }
57 |
58 | /**
59 | * 保存
60 | *
61 | * @param expires 有效期(单位:毫秒)
62 | */
63 | public boolean save(String key, T value, int expires, CacheTarget target) {
64 | if (value == null) {
65 | return memory.remove(key) && disk.remove(key);
66 | }
67 |
68 | if (memory != null) {
69 | // FIXME 通过标识符判断是否被篡改
70 | T cloneValue = null;
71 | try {
72 | cloneValue = CloneUtils.deepClone(value);
73 | value = cloneValue;
74 | } catch (Exception e) {
75 | L.debug(e);
76 | }
77 | memory.save(key, cloneValue, expires, target);
78 | }
79 | if (disk != null) {
80 | return disk.save(key, value, expires, target);
81 | }
82 |
83 | return false;
84 | }
85 |
86 | /**
87 | * 是否包含
88 | */
89 | public boolean containsKey(String key) {
90 | if (memory != null) {
91 | if (memory.containsKey(key)) {
92 | return true;
93 | }
94 | }
95 | if (disk != null) {
96 | if (disk.containsKey(key)) {
97 | return true;
98 | }
99 | }
100 | return false;
101 | }
102 |
103 | /**
104 | * 删除缓存
105 | */
106 | public void remove(String key) {
107 | if (memory != null) {
108 | memory.remove(key);
109 | }
110 | if (disk != null) {
111 | disk.remove(key);
112 | }
113 | }
114 |
115 | /**
116 | * 清空缓存
117 | */
118 | public void clear() {
119 | if (memory != null) {
120 | memory.clear();
121 | }
122 | if (disk != null) {
123 | disk.clear();
124 | }
125 | }
126 |
127 |
128 | /**
129 | * 构造器
130 | */
131 | public static class Builder {
132 | private IMemoryStorage memory;
133 | private IMemoryJournal memoryJournal;
134 | private long memoryMaxSize;
135 | private long memoryMaxQuantity;
136 |
137 | private IDiskStorage disk;
138 | private IDiskJournal diskJournal;
139 | private IDiskConverter diskConverter;
140 | private long diskMaxSize;
141 | private long diskMaxQuantity;
142 |
143 | public Builder() {
144 | }
145 |
146 | public Builder memory(IMemoryStorage memory) {
147 | this.memory = Utils.checkNotNull(memory);
148 | return this;
149 | }
150 |
151 | public Builder memoryJournal(IMemoryJournal journal) {
152 | this.memoryJournal = Utils.checkNotNull(journal);
153 | return this;
154 | }
155 |
156 | public Builder memoryMax(long maxSize, long maxQuantity) {
157 | this.memoryMaxSize = maxSize;
158 | this.memoryMaxQuantity = maxQuantity;
159 | return this;
160 | }
161 |
162 | public Builder disk(IDiskStorage disk) {
163 | this.disk = Utils.checkNotNull(disk);
164 | return this;
165 | }
166 |
167 | public Builder diskJournal(IDiskJournal journal) {
168 | this.diskJournal = Utils.checkNotNull(journal);
169 | return this;
170 | }
171 |
172 | public Builder diskConverter(IDiskConverter converter) {
173 | this.diskConverter = Utils.checkNotNull(converter);
174 | return this;
175 | }
176 |
177 | public Builder diskMax(long maxSize, long maxQuantity) {
178 | this.diskMaxSize = maxSize;
179 | this.diskMaxQuantity = maxQuantity;
180 | return this;
181 | }
182 |
183 | public CacheCore create() {
184 | // TODO 根据配置,选择合适的构造方法
185 | return new CacheCore(new MemoryCache(memory, memoryJournal, memoryMaxSize, memoryMaxQuantity),
186 | new DiskCache(disk, diskJournal, diskConverter, diskMaxSize, diskMaxQuantity));
187 | }
188 | }
189 |
190 | }
191 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/CacheEntry.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core;
2 |
3 | import com.litesuits.orm.db.annotation.Column;
4 | import com.litesuits.orm.db.annotation.PrimaryKey;
5 | import com.litesuits.orm.db.enums.AssignType;
6 |
7 | import java.io.Serializable;
8 |
9 | /**
10 | * 日志项
11 | * @version 0.1 king 2016-04
12 | */
13 | public class CacheEntry implements Serializable, Cloneable {
14 | public static final String COL_KEY = "key";
15 | public static final String COL_CREATE_TIME = "create_time";
16 | public static final String COL_LAST_USE_TIME = "last_use_time";
17 | public static final String COL_USE_COUNT = "use_count";
18 | public static final String COL_EXPIRY_TIME = "expiry_time";
19 | public static final String COL_TARGET = "expiry_target";
20 |
21 | /**
22 | * KEY
23 | */
24 | @PrimaryKey(AssignType.BY_MYSELF)
25 | @Column(COL_KEY)
26 | private String key;
27 | /**
28 | * 创建时间
29 | */
30 | @Column(COL_CREATE_TIME)
31 | private long createTime;
32 | /**
33 | * 最后使用时间
34 | */
35 | @Column(COL_LAST_USE_TIME)
36 | private long lastUseTime;
37 | /**
38 | * 总使用次数
39 | */
40 | @Column(COL_USE_COUNT)
41 | private long useCount;
42 | /**
43 | * 过期时间
44 | */
45 | @Column(COL_EXPIRY_TIME)
46 | private long expiryTime;
47 | /**
48 | * 缓存目标
49 | */
50 | @Column(COL_TARGET)
51 | private CacheTarget target;
52 |
53 | public CacheEntry() {
54 | }
55 | CacheEntry(CacheEntry entry) {
56 | this.key = entry.key;
57 | this.createTime = entry.createTime;
58 | this.lastUseTime = entry.lastUseTime;
59 | this.expiryTime = entry.expiryTime;
60 | this.target = entry.target;
61 | this.useCount = entry.useCount;
62 | }
63 | public CacheEntry(String key, long maxAge, CacheTarget target) {
64 | long currentTime = System.currentTimeMillis();
65 |
66 | this.key = key;
67 | this.createTime = currentTime;
68 | this.lastUseTime = currentTime;
69 | this.expiryTime = currentTime + maxAge;
70 | this.target = target;
71 | this.useCount = 1;
72 | }
73 |
74 |
75 | /**
76 | * 是否过期
77 | */
78 | public boolean isExpiry() {
79 | return System.currentTimeMillis() > expiryTime;
80 | }
81 |
82 |
83 | @Override
84 | public CacheEntry clone() {
85 | return new CacheEntry(this);
86 | }
87 |
88 | @Override
89 | public boolean equals(Object o) {
90 | if (this == o) return true;
91 | if (o == null || getClass() != o.getClass()) return false;
92 |
93 | CacheEntry entry = (CacheEntry) o;
94 |
95 | if (createTime != entry.createTime) return false;
96 | if (lastUseTime != entry.lastUseTime) return false;
97 | if (useCount != entry.useCount) return false;
98 | if (expiryTime != entry.expiryTime) return false;
99 | if (key != null ? !key.equals(entry.key) : entry.key != null) return false;
100 | return target == entry.target;
101 | }
102 |
103 | @Override
104 | public int hashCode() {
105 | int result = key != null ? key.hashCode() : 0;
106 | result = 31 * result + (int) (createTime ^ (createTime >>> 32));
107 | result = 31 * result + (int) (lastUseTime ^ (lastUseTime >>> 32));
108 | result = 31 * result + (int) (useCount ^ (useCount >>> 32));
109 | result = 31 * result + (int) (expiryTime ^ (expiryTime >>> 32));
110 | result = 31 * result + (target != null ? target.hashCode() : 0);
111 | return result;
112 | }
113 |
114 | @Override
115 | public String toString() {
116 | return "{" +
117 | "key='" + key + '\'' +
118 | ", createTime=" + createTime +
119 | ", lastUseTime=" + lastUseTime +
120 | ", useCount=" + useCount +
121 | ", expiryTime=" + expiryTime +
122 | ", target=" + target +
123 | '}';
124 | }
125 |
126 |
127 | public String getKey() {
128 | return key;
129 | }
130 |
131 | public long getCreateTime() {
132 | return createTime;
133 | }
134 |
135 | public void setCreateTime(long createTime) {
136 | this.createTime = createTime;
137 | }
138 |
139 | public long getLastUseTime() {
140 | return lastUseTime;
141 | }
142 |
143 | public void setLastUseTime(long lastUseTime) {
144 | this.lastUseTime = lastUseTime;
145 | }
146 |
147 | public long getUseCount() {
148 | return useCount;
149 | }
150 |
151 | public void setUseCount(long useCount) {
152 | this.useCount = useCount;
153 | }
154 |
155 | public long getExpiryTime() {
156 | return expiryTime;
157 | }
158 |
159 | public void setExpiryTime(long expiryTime) {
160 | this.expiryTime = expiryTime;
161 | }
162 |
163 | public CacheTarget getTarget() {
164 | return target;
165 | }
166 |
167 | public void setTarget(CacheTarget target) {
168 | this.target = target;
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/CacheTarget.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core;
2 |
3 | /**
4 | * 缓存目标
5 | * @version alafighting 2016-04
6 | */
7 | public enum CacheTarget {
8 |
9 | NONE,
10 | Memory,
11 | Disk,
12 | MemoryAndDisk;
13 |
14 | public boolean supportMemory() {
15 | return this==Memory || this== MemoryAndDisk;
16 | }
17 |
18 | public boolean supportDisk() {
19 | return this==Disk || this== MemoryAndDisk;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/DiskCache.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk;
2 |
3 | import com.google.gson.reflect.TypeToken;
4 | import com.im4j.kakacache.rxjava.common.utils.Utils;
5 | import com.im4j.kakacache.rxjava.core.BasicCache;
6 | import com.im4j.kakacache.rxjava.core.CacheEntry;
7 | import com.im4j.kakacache.rxjava.core.CacheTarget;
8 | import com.im4j.kakacache.rxjava.core.disk.converter.IDiskConverter;
9 | import com.im4j.kakacache.rxjava.core.disk.journal.IDiskJournal;
10 | import com.im4j.kakacache.rxjava.core.disk.storage.IDiskStorage;
11 |
12 | import java.io.InputStream;
13 | import java.io.OutputStream;
14 | import java.util.Collection;
15 |
16 | /**
17 | * 磁盘缓存
18 | * @version 0.1 king 2016-04
19 | */
20 | public final class DiskCache extends BasicCache {
21 |
22 | private final IDiskStorage mStorage;
23 | private final IDiskJournal mJournal;
24 | private final IDiskConverter mConverter;
25 |
26 | public DiskCache(IDiskStorage storage,
27 | IDiskJournal journal,
28 | IDiskConverter converter,
29 | long maxSize,
30 | long maxQuantity) {
31 | super(maxSize, maxQuantity);
32 | this.mStorage = storage;
33 | this.mJournal = journal;
34 | this.mConverter = converter;
35 | }
36 |
37 |
38 | /**
39 | * 读取
40 | */
41 | @Override
42 | protected T doLoad(String key) {
43 | // 读取缓存
44 | InputStream source = mStorage.load(key);
45 | T value = null;
46 | if (source != null) {
47 | value = (T) mConverter.load(source, new TypeToken(){}.getType());
48 | Utils.close(source);
49 | }
50 | return value;
51 | }
52 |
53 | /**
54 | * 保存
55 | * @param maxAge 最大有效期时长(单位:毫秒)
56 | */
57 | @Override
58 | protected boolean doSave(String key, T value, int maxAge, CacheTarget target) {
59 | if (target == null || target == CacheTarget.NONE || target == CacheTarget.Memory) {
60 | return true;
61 | }
62 |
63 | // 写入缓存
64 | OutputStream sink = mStorage.create(key);
65 | if (sink != null) {
66 | mConverter.writer(sink, value);
67 | Utils.close(sink);
68 |
69 | mJournal.put(key, new CacheEntry(key, maxAge, target));
70 | return true;
71 | }
72 |
73 | return false;
74 | }
75 |
76 | @Override
77 | protected boolean isExpiry(String key) {
78 | CacheEntry entry = mJournal.get(key);
79 | return entry == null || entry.isExpiry();
80 | }
81 |
82 | @Override
83 | protected boolean doContainsKey(String key) {
84 | return mJournal.containsKey(key);
85 | }
86 |
87 | @Override
88 | protected boolean doRemove(String key) {
89 | return mStorage.remove(key) && mJournal.remove(key);
90 | }
91 |
92 | @Override
93 | protected boolean doClear() {
94 | return mStorage.clear() && mJournal.clear();
95 | }
96 |
97 | @Override
98 | public Collection snapshot() {
99 | return mJournal.snapshot();
100 | }
101 |
102 | @Override
103 | public String getLoseKey() {
104 | return mJournal.getLoseKey();
105 | }
106 |
107 | @Override
108 | public long getTotalSize() {
109 | long size = mStorage.getTotalSize();
110 | Utils.checkNotLessThanZero(size);
111 | return size;
112 | }
113 |
114 | @Override
115 | public long getTotalQuantity() {
116 | long quantity = mStorage.getTotalQuantity();
117 | Utils.checkNotLessThanZero(quantity);
118 | return quantity;
119 | }
120 |
121 | }
122 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/converter/GsonDiskConverter.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.converter;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.JsonIOException;
5 | import com.google.gson.JsonSyntaxException;
6 | import com.im4j.kakacache.rxjava.common.utils.L;
7 | import com.im4j.kakacache.rxjava.common.utils.Utils;
8 |
9 | import java.io.IOException;
10 | import java.io.InputStream;
11 | import java.io.InputStreamReader;
12 | import java.io.OutputStream;
13 | import java.lang.reflect.Type;
14 |
15 | /**
16 | * GSON-数据转换器
17 | * @version alafighting 2016-07
18 | */
19 | public class GsonDiskConverter implements IDiskConverter {
20 | private Gson gson;
21 |
22 | public GsonDiskConverter(Gson gson) {
23 | this.gson = gson;
24 | }
25 |
26 | @Override
27 | public Object load(InputStream source, Type type) {
28 | Object value = null;
29 | try {
30 | value = gson.fromJson(new InputStreamReader(source), type);
31 | } catch (JsonIOException e) {
32 | L.log(e);
33 | } catch (JsonSyntaxException e) {
34 | L.log(e);
35 | } finally {
36 | Utils.close(source);
37 | }
38 | return value;
39 | }
40 |
41 | @Override
42 | public boolean writer(OutputStream sink, Object data) {
43 | try {
44 | String json = gson.toJson(data);
45 | byte[] bytes = json.getBytes();
46 | sink.write(bytes, 0, bytes.length);
47 | sink.flush();
48 | return true;
49 | } catch (JsonIOException e) {
50 | L.log(e);
51 | } catch (JsonSyntaxException e) {
52 | L.log(e);
53 | } catch (IOException e) {
54 | L.log(e);
55 | }
56 | return false;
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/converter/IDiskConverter.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.converter;
2 |
3 | import java.io.InputStream;
4 | import java.io.OutputStream;
5 | import java.lang.reflect.Type;
6 |
7 | /**
8 | * 通用转换器
9 | *
10 | * @version alafighting 2016-04
11 | */
12 | public interface IDiskConverter {
13 |
14 | /**
15 | * 读取
16 | */
17 | Object load(InputStream source, Type type);
18 |
19 | /**
20 | * 写入
21 | */
22 | boolean writer(OutputStream sink, Object data);
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/converter/KryoDiskConverter.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.converter;
2 |
3 | import com.esotericsoftware.kryo.Kryo;
4 | import com.esotericsoftware.kryo.io.Input;
5 | import com.esotericsoftware.kryo.io.Output;
6 | import com.im4j.kakacache.rxjava.common.utils.L;
7 | import com.im4j.kakacache.rxjava.common.utils.Utils;
8 |
9 | import java.io.InputStream;
10 | import java.io.OutputStream;
11 | import java.lang.reflect.Type;
12 |
13 | /**
14 | * Kryo-数据转换器
15 | * @version alafighting 2016-07
16 | */
17 | public class KryoDiskConverter implements IDiskConverter {
18 | private Kryo kryo;
19 |
20 | public KryoDiskConverter(Kryo kryo) {
21 | this.kryo = kryo;
22 | }
23 |
24 | @Override
25 | public Object load(InputStream source, Type type) {
26 | Object value = null;
27 | Input input = null;
28 | try {
29 | input = new Input(source);
30 | value = kryo.readClassAndObject(input);
31 | } finally {
32 | Utils.close(input);
33 | }
34 | return value;
35 | }
36 |
37 | @Override
38 | public boolean writer(OutputStream sink, Object data) {
39 | Output output = null;
40 | try {
41 | output = new Output(sink);
42 | kryo.writeClassAndObject(output, data);
43 | return true;
44 | } catch (Exception e) {
45 | L.debug(e);
46 | return false;
47 | } finally {
48 | Utils.close(output);
49 | }
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/converter/SerializableDiskConverter.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.converter;
2 |
3 | import com.im4j.kakacache.rxjava.common.utils.L;
4 | import com.im4j.kakacache.rxjava.common.utils.Utils;
5 |
6 | import java.io.IOException;
7 | import java.io.InputStream;
8 | import java.io.ObjectInputStream;
9 | import java.io.ObjectOutputStream;
10 | import java.io.OutputStream;
11 | import java.lang.reflect.Type;
12 |
13 | /**
14 | * 序列化-数据转换器
15 | * @version alafighting 2016-07
16 | */
17 | public class SerializableDiskConverter implements IDiskConverter {
18 |
19 | @Override
20 | public Object load(InputStream source, Type type) {
21 | Object value = null;
22 | ObjectInputStream oin = null;
23 | try {
24 | oin = new ObjectInputStream(source);
25 | value = oin.readObject();
26 | } catch (IOException | ClassNotFoundException e) {
27 | L.log(e);
28 | } finally {
29 | Utils.close(oin);
30 | }
31 | return value;
32 | }
33 |
34 | @Override
35 | public boolean writer(OutputStream sink, Object data) {
36 | ObjectOutputStream oos = null;
37 | try {
38 | oos = new ObjectOutputStream(sink);
39 | oos.writeObject(data);
40 | oos.flush(); //缓冲流
41 | return true;
42 | } catch (IOException e) {
43 | L.log(e);
44 | return false;
45 | } finally {
46 | Utils.close(oos);
47 | }
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/journal/BasicDiskJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.journal;
2 |
3 | import com.im4j.kakacache.rxjava.common.exception.NullException;
4 | import com.im4j.kakacache.rxjava.common.utils.Utils;
5 | import com.im4j.kakacache.rxjava.core.CacheEntry;
6 | import com.litesuits.orm.LiteOrm;
7 | import com.litesuits.orm.db.assit.WhereBuilder;
8 |
9 | import java.io.IOException;
10 | import java.util.Collection;
11 |
12 | /**
13 | * 缓存日志-基类
14 | * @version alafighting 2016-07
15 | */
16 | public abstract class BasicDiskJournal implements IDiskJournal {
17 |
18 | private final LiteOrm mLiteOrm;
19 |
20 | public BasicDiskJournal(LiteOrm liteOrm) {
21 | this.mLiteOrm = liteOrm;
22 | }
23 |
24 | final LiteOrm getDb() {
25 | return mLiteOrm;
26 | }
27 |
28 | @Override
29 | public CacheEntry get(String key) {
30 | if (Utils.isEmpty(key)) {
31 | throw new NullException("key == null");
32 | }
33 |
34 | CacheEntry entry = mLiteOrm.queryById(key, CacheEntry.class);
35 | if (entry != null) {
36 | // 有效期内,才记录最后使用时间
37 | if (!entry.isExpiry()) {
38 | entry.setLastUseTime(System.currentTimeMillis());
39 | entry.setUseCount(entry.getUseCount() + 1);
40 | mLiteOrm.update(entry);
41 | }
42 | return entry;
43 | } else {
44 | return null;
45 | }
46 | }
47 |
48 | @Override
49 | public void put(String key, CacheEntry entry) {
50 | if (Utils.isEmpty(key) || entry == null) {
51 | throw new NullException("key == null || value == null");
52 | }
53 | if (!entry.isExpiry()) {
54 | entry.setLastUseTime(System.currentTimeMillis());
55 | entry.setUseCount(1);
56 | mLiteOrm.save(entry);
57 | } else {
58 | remove(key);
59 | }
60 | }
61 |
62 | @Override
63 | public final boolean containsKey(String key) {
64 | CacheEntry entry = get(key);
65 | return entry != null;
66 | }
67 |
68 | @Override
69 | public abstract String getLoseKey();
70 |
71 | @Override
72 | public final boolean remove(String key) {
73 | int result = mLiteOrm.delete(new WhereBuilder(CacheEntry.class)
74 | .where(CacheEntry.COL_KEY + " = ?", "%"+key+"%"));
75 | return result > 0;
76 | }
77 |
78 | @Override
79 | public final boolean clear() {
80 | int result = mLiteOrm.deleteAll(CacheEntry.class);
81 | return result >= 0;
82 | }
83 |
84 | @Override
85 | public final Collection snapshot() {
86 | return mLiteOrm.query(CacheEntry.class);
87 | }
88 |
89 | @Override
90 | public void close() throws IOException {
91 | // TODO Nothing
92 | //mLiteOrm.close();
93 | }
94 |
95 | }
96 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/journal/FIFODiskJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.journal;
2 |
3 | import com.im4j.kakacache.rxjava.core.CacheEntry;
4 | import com.litesuits.orm.LiteOrm;
5 | import com.litesuits.orm.db.assit.QueryBuilder;
6 |
7 | import java.util.List;
8 |
9 | /**
10 | * FIFO缓存日志
11 | * @version alafighting 2016-07
12 | */
13 | public class FIFODiskJournal extends BasicDiskJournal {
14 |
15 | public FIFODiskJournal(LiteOrm liteOrm) {
16 | super(liteOrm);
17 | }
18 |
19 | @Override
20 | public String getLoseKey() {
21 | QueryBuilder query = new QueryBuilder(CacheEntry.class);
22 | query.orderBy(CacheEntry.COL_CREATE_TIME);
23 | query.limit(0, 1);
24 | List list = getDb().query(query);
25 | if (list != null && list.size() >0) {
26 | return list.get(0).getKey();
27 | } else {
28 | return null;
29 | }
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/journal/IDiskJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.journal;
2 |
3 | import com.im4j.kakacache.rxjava.core.CacheEntry;
4 |
5 | import java.io.Closeable;
6 | import java.util.Collection;
7 |
8 | /**
9 | * 磁盘缓存日志
10 | * @version alafighting 2016-04
11 | */
12 | public interface IDiskJournal extends Closeable {
13 |
14 | CacheEntry get(String key);
15 |
16 | void put(String key, CacheEntry entry);
17 |
18 | boolean containsKey(String key);
19 |
20 | /**
21 | * 获取准备丢弃的Key
22 | * @return 准备丢弃的Key(如存储空间不足时,需要清理)
23 | */
24 | String getLoseKey();
25 |
26 | boolean remove(String key);
27 |
28 | boolean clear();
29 |
30 | Collection snapshot();
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/journal/LFUDiskJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.journal;
2 |
3 | import com.im4j.kakacache.rxjava.core.CacheEntry;
4 | import com.litesuits.orm.LiteOrm;
5 | import com.litesuits.orm.db.assit.QueryBuilder;
6 |
7 | import java.util.List;
8 |
9 | /**
10 | * LFU缓存日志
11 | * @version alafighting 2016-07
12 | */
13 | public class LFUDiskJournal extends BasicDiskJournal {
14 |
15 | public LFUDiskJournal(LiteOrm liteOrm) {
16 | super(liteOrm);
17 | }
18 |
19 | @Override
20 | public String getLoseKey() {
21 | QueryBuilder query = new QueryBuilder(CacheEntry.class);
22 | query.orderBy(CacheEntry.COL_USE_COUNT).appendOrderAscBy(CacheEntry.COL_LAST_USE_TIME);
23 | query.limit(0, 1);
24 | List list = getDb().query(query);
25 | if (list != null && list.size() >0) {
26 | return list.get(0).getKey();
27 | } else {
28 | return null;
29 | }
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/journal/LRUDiskJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.journal;
2 |
3 | import com.im4j.kakacache.rxjava.core.CacheEntry;
4 | import com.litesuits.orm.LiteOrm;
5 | import com.litesuits.orm.db.assit.QueryBuilder;
6 |
7 | import java.util.List;
8 |
9 | /**
10 | * LRU缓存日志
11 | * @version alafighting 2016-07
12 | */
13 | public class LRUDiskJournal extends BasicDiskJournal {
14 |
15 | public LRUDiskJournal(LiteOrm liteOrm) {
16 | super(liteOrm);
17 | }
18 |
19 | @Override
20 | public String getLoseKey() {
21 | QueryBuilder query = new QueryBuilder(CacheEntry.class);
22 | query.orderBy(CacheEntry.COL_LAST_USE_TIME);
23 | query.limit(0, 1);
24 | List list = getDb().query(query);
25 | if (list != null && list.size() >0) {
26 | return list.get(0).getKey();
27 | } else {
28 | return null;
29 | }
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/journal/UnlimitedDiskJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.journal;
2 |
3 | import com.litesuits.orm.LiteOrm;
4 |
5 | /**
6 | * Unlimited缓存日志
7 | * @version alafighting 2016-07
8 | */
9 | public class UnlimitedDiskJournal extends BasicDiskJournal {
10 |
11 | public UnlimitedDiskJournal(LiteOrm liteOrm) {
12 | super(liteOrm);
13 | }
14 |
15 | // 永不清除有效的缓存(过期依旧会被清理)
16 | @Override
17 | public String getLoseKey() {
18 | return null;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/storage/EmptyDiskStorage.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.storage;
2 |
3 | import java.io.FileInputStream;
4 | import java.io.FileOutputStream;
5 |
6 | /**
7 | * 空的磁盘存储
8 | * @author imkarl 2016-09
9 | */
10 | public class EmptyDiskStorage implements IDiskStorage {
11 |
12 | public static final EmptyDiskStorage INSTANCE = new EmptyDiskStorage();
13 |
14 | private EmptyDiskStorage() {
15 | }
16 |
17 | @Override
18 | public FileInputStream load(String key) {
19 | return null;
20 | }
21 |
22 | @Override
23 | public FileOutputStream create(String key) {
24 | return null;
25 | }
26 |
27 | @Override
28 | public void close() {
29 | }
30 |
31 | @Override
32 | public boolean remove(String key) {
33 | return true;
34 | }
35 |
36 | @Override
37 | public boolean clear() {
38 | return true;
39 | }
40 |
41 | @Override
42 | public long getTotalSize() {
43 | return 0;
44 | }
45 |
46 | @Override
47 | public long getTotalQuantity() {
48 | return 0;
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/storage/FileDiskStorage.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.storage;
2 |
3 | import com.im4j.kakacache.rxjava.common.exception.NotFoundException;
4 | import com.im4j.kakacache.rxjava.common.utils.L;
5 | import com.im4j.kakacache.rxjava.common.utils.Utils;
6 |
7 | import java.io.File;
8 | import java.io.FileInputStream;
9 | import java.io.FileNotFoundException;
10 | import java.io.FileOutputStream;
11 | import java.io.IOException;
12 |
13 | /**
14 | * 文件形式的磁盘存储
15 | * @version alafighting 2016-06
16 | */
17 | public class FileDiskStorage implements IDiskStorage {
18 | private File mStorageDir;
19 |
20 | /**
21 | * @param storageDir 磁盘存储根目录
22 | */
23 | public FileDiskStorage(File storageDir) {
24 | if (storageDir == null || !storageDir.isDirectory()) {
25 | throw new NotFoundException("'"+storageDir+"' not found.");
26 | }
27 | this.mStorageDir = storageDir;
28 | }
29 |
30 | @Override
31 | public FileInputStream load(String key) {
32 | if (Utils.isEmpty(key)) {
33 | return null;
34 | }
35 | File file = new File(mStorageDir, key);
36 | if (!file.exists() || !file.isFile()) {
37 | return null;
38 | }
39 | try {
40 | return new FileInputStream(file);
41 | } catch (FileNotFoundException e) {
42 | throw new NotFoundException(e);
43 | }
44 | }
45 |
46 | @Override
47 | public FileOutputStream create(String key) {
48 | if (Utils.isEmpty(key)) {
49 | return null;
50 | }
51 | File file = new File(mStorageDir, key);
52 | if (!exists(file) || file.isDirectory()) {
53 | try {
54 | L.debug("createNewFile => "+file);
55 | file.getParentFile().mkdirs();
56 | file.createNewFile();
57 | } catch (IOException e) {
58 | L.log(e);
59 | return null;
60 | }
61 | }
62 | try {
63 | return new FileOutputStream(file);
64 | } catch (FileNotFoundException e) {
65 | throw new NotFoundException(e);
66 | }
67 | }
68 |
69 | @Override
70 | public void close() {
71 | // TODO Nothing
72 | }
73 |
74 | @Override
75 | public boolean remove(String key) {
76 | return !Utils.isEmpty(key) && delete(new File(mStorageDir, key));
77 | }
78 |
79 | @Override
80 | public boolean clear() {
81 | try {
82 | deleteContents(mStorageDir);
83 | return true;
84 | } catch (IOException e) {
85 | return false;
86 | }
87 | }
88 |
89 | @Override
90 | public long getTotalSize() {
91 | return countSize(mStorageDir);
92 | }
93 |
94 | @Override
95 | public long getTotalQuantity() {
96 | String[] files = mStorageDir.list();
97 | if (files == null) {
98 | return 0;
99 | }
100 | return files.length;
101 | }
102 |
103 |
104 |
105 | public boolean exists(File file) {
106 | return file != null && file.exists();
107 | }
108 |
109 | private long countSize(File file) {
110 | return file.length();
111 | }
112 |
113 | public boolean delete(File file) {
114 | if (file == null) {
115 | return false;
116 | }
117 | // If delete() fails, make sure it's because the file didn't exist!
118 | return file.delete() || !file.exists();
119 |
120 | }
121 |
122 | private void deleteContents(File directory) throws IOException {
123 | File[] files = directory.listFiles();
124 | if (files == null) {
125 | throw new IOException("not a readable directory: " + directory);
126 | }
127 | for (File file : files) {
128 | if (file.isDirectory()) {
129 | deleteContents(file);
130 | }
131 | if (!file.delete()) {
132 | throw new IOException("failed to delete " + file);
133 | }
134 | }
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/disk/storage/IDiskStorage.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.disk.storage;
2 |
3 | import java.io.Closeable;
4 | import java.io.InputStream;
5 | import java.io.OutputStream;
6 |
7 | /**
8 | * 磁盘存储
9 | * @version alafighting 2016-04
10 | */
11 | public interface IDiskStorage extends Closeable {
12 |
13 | /**
14 | * 加载数据源
15 | * @param key
16 | * @return
17 | */
18 | InputStream load(String key);
19 |
20 | /**
21 | * 创建数据槽
22 | * @param key
23 | */
24 | OutputStream create(String key);
25 |
26 |
27 |
28 | /**
29 | * 关闭
30 | */
31 | @Override
32 | void close();
33 |
34 | /**
35 | * 删除缓存
36 | * @param key
37 | */
38 | boolean remove(String key);
39 |
40 | /**
41 | * 清空缓存
42 | */
43 | boolean clear();
44 |
45 | /**
46 | * 缓存总大小
47 | * @return 单位:byte
48 | */
49 | long getTotalSize();
50 |
51 | /**
52 | * 缓存总数目
53 | * @return 单位:缓存个数
54 | */
55 | long getTotalQuantity();
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/memory/CloneUtils.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.memory;
2 |
3 | import java.lang.reflect.Field;
4 | import java.lang.reflect.InvocationTargetException;
5 | import java.lang.reflect.Modifier;
6 | import java.util.Arrays;
7 | import java.util.Collection;
8 | import java.util.HashSet;
9 | import java.util.Map;
10 | import java.util.Set;
11 |
12 | /**
13 | * 对象深度克隆
14 | * @version imkarl 2016-09
15 | */
16 | public class CloneUtils {
17 | private CloneUtils() {}
18 |
19 | /**
20 | * 无需进行复制的特殊类型数组
21 | */
22 | private static final Class[] needlessCloneClasses = new Class[]{String.class,Boolean.class,Character.class,Byte.class,Short.class,
23 | Integer.class,Long.class,Float.class,Double.class,Void.class,Object.class,Class.class
24 | };
25 | /**
26 | * 判断该类型对象是否无需复制
27 | * @param c 指定类型
28 | * @return 如果不需要复制则返回真,否则返回假
29 | */
30 | private static boolean isNeedlessClone(Class c){
31 | if(c.isPrimitive()){//基本类型
32 | return true;
33 | }
34 | for(Class tmp:needlessCloneClasses){//是否在无需复制类型数组里
35 | if(c.equals(tmp)){
36 | return true;
37 | }
38 | }
39 | return false;
40 | }
41 |
42 | /**
43 | * 尝试创建新对象
44 | * @param value 原始对象
45 | * @return 新的对象
46 | * @throws IllegalAccessException
47 | */
48 | private static Object createObject(Object value) throws IllegalAccessException{
49 | try {
50 | return value.getClass().newInstance();
51 | } catch (InstantiationException e) {
52 | return null;
53 | } catch (IllegalAccessException e) {
54 | throw e;
55 | }
56 | }
57 |
58 | /**
59 | * 复制对象数据
60 | * @param value 原始对象
61 | * @param level 复制深度。小于0为无限深度,即将深入到最基本类型和Object类级别的数据复制;
62 | * 大于0则按照其值复制到指定深度的数据,等于0则直接返回对象本身而不进行任何复制行为。
63 | * @return 返回复制后的对象
64 | * @throws IllegalAccessException
65 | * @throws InstantiationException
66 | * @throws InvocationTargetException
67 | * @throws NoSuchMethodException
68 | */
69 | public static T clone(T value,int level) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException{
70 | Object cloneValue;
71 | if(value==null){
72 | return null;
73 | }
74 | if(level==0){
75 | return value;
76 | }
77 | Class c = value.getClass();
78 | if(isNeedlessClone(c)){
79 | return value;
80 | }
81 | level--;
82 | if(value instanceof Collection){//复制新的集合
83 | Collection tmp = (Collection)c.newInstance();
84 | for(Object v:(Collection)value){
85 | tmp.add(clone(v,level));//深度复制
86 | }
87 | cloneValue = tmp;
88 | }
89 | else if(c.isArray()){//复制新的Array
90 | //首先判断是否为基本数据类型
91 | if(c.equals(int[].class)){
92 | int[] old = (int[])value;
93 | cloneValue = (T) Arrays.copyOf(old, old.length);
94 | }
95 | else if(c.equals(short[].class)){
96 | short[] old = (short[])value;
97 | cloneValue = (T) Arrays.copyOf(old, old.length);
98 | }
99 | else if(c.equals(char[].class)){
100 | char[] old = (char[])value;
101 | cloneValue = (T) Arrays.copyOf(old, old.length);
102 | }
103 | else if(c.equals(float[].class)){
104 | float[] old = (float[])value;
105 | cloneValue = (T) Arrays.copyOf(old, old.length);
106 | }
107 | else if(c.equals(double[].class)){
108 | double[] old = (double[])value;
109 | cloneValue = (T) Arrays.copyOf(old, old.length);
110 | }
111 | else if(c.equals(long[].class)){
112 | long[] old = (long[])value;
113 | cloneValue = (T) Arrays.copyOf(old, old.length);
114 | }
115 | else if(c.equals(boolean[].class)){
116 | boolean[] old = (boolean[])value;
117 | cloneValue = (T) Arrays.copyOf(old, old.length);
118 | }
119 | else if(c.equals(byte[].class)){
120 | byte[] old = (byte[])value;
121 | cloneValue = (T) Arrays.copyOf(old, old.length);
122 | }
123 | else {
124 | Object[] old = (Object[])value;
125 | Object[] tmp = Arrays.copyOf(old, old.length, old.getClass());
126 | for(int i = 0;i fields = new HashSet();
146 | while(c!=null&&!c.equals(Object.class)){
147 | fields.addAll(Arrays.asList(c.getDeclaredFields()));
148 | c = c.getSuperclass();
149 | }
150 | for(Field field:fields){
151 | if(!Modifier.isFinal(field.getModifiers())){//仅复制非final字段
152 | field.setAccessible(true);
153 | field.set(tmp, clone(field.get(value),level));//深度复制
154 | }
155 | }
156 | cloneValue = (T) tmp;
157 | }
158 | return (T) cloneValue;
159 | }
160 |
161 | /**
162 | * 浅表复制对象
163 | * @param value 原始对象
164 | * @return 复制后的对象,只复制一层
165 | * @throws IllegalAccessException
166 | * @throws InstantiationException
167 | * @throws InvocationTargetException
168 | * @throws NoSuchMethodException
169 | */
170 | public static T clone(T value) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException{
171 | return clone(value, 1);
172 | }
173 |
174 | /**
175 | * 深度复制对象
176 | * @param value 原始对象
177 | * @return 复制后的对象
178 | * @throws IllegalAccessException
179 | * @throws InstantiationException
180 | * @throws InvocationTargetException
181 | * @throws NoSuchMethodException
182 | */
183 | public static T deepClone(T value) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException{
184 | return clone(value, -1);
185 | }
186 | }
187 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/memory/MemoryCache.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.memory;
2 |
3 | import com.im4j.kakacache.rxjava.common.utils.Utils;
4 | import com.im4j.kakacache.rxjava.core.BasicCache;
5 | import com.im4j.kakacache.rxjava.core.CacheEntry;
6 | import com.im4j.kakacache.rxjava.core.CacheTarget;
7 | import com.im4j.kakacache.rxjava.core.memory.journal.IMemoryJournal;
8 | import com.im4j.kakacache.rxjava.core.memory.storage.IMemoryStorage;
9 |
10 | import java.util.Collection;
11 |
12 | /**
13 | * 内存缓存
14 | * @version 0.1 king 2016-04
15 | */
16 | public final class MemoryCache extends BasicCache {
17 |
18 | private final IMemoryStorage mStorage;
19 | private final IMemoryJournal mJournal;
20 |
21 | public MemoryCache(IMemoryStorage storage,
22 | IMemoryJournal journal,
23 | long maxSize,
24 | long maxQuantity) {
25 | super(maxSize, maxQuantity);
26 | this.mStorage = storage;
27 | this.mJournal = journal;
28 | }
29 |
30 |
31 | @Override
32 | protected T doLoad(String key) {
33 | return (T) mStorage.load(key);
34 | }
35 |
36 | @Override
37 | protected boolean doSave(String key, T value, int maxAge, CacheTarget target) {
38 | if (target == null || target == CacheTarget.NONE || target == CacheTarget.Disk) {
39 | return true;
40 | }
41 |
42 | // 写入缓存
43 | if (mStorage.save(key, value)) {
44 | mJournal.put(key, new CacheEntry(key, maxAge, target));
45 | return true;
46 | }
47 | return false;
48 | }
49 |
50 | @Override
51 | protected boolean isExpiry(String key) {
52 | CacheEntry entry = mJournal.get(key);
53 | return entry == null || entry.isExpiry();
54 | }
55 |
56 | @Override
57 | protected boolean doContainsKey(String key) {
58 | return mJournal.containsKey(key);
59 | }
60 |
61 | /**
62 | * 删除缓存
63 | * @param key
64 | */
65 | @Override
66 | protected boolean doRemove(String key) {
67 | return mStorage.remove(key) && mJournal.remove(key);
68 | }
69 |
70 | /**
71 | * 清空缓存
72 | */
73 | @Override
74 | protected boolean doClear() {
75 | return mStorage.clear() && mJournal.clear();
76 | }
77 |
78 | @Override
79 | public Collection snapshot() {
80 | return mJournal.snapshot();
81 | }
82 |
83 | @Override
84 | public String getLoseKey() {
85 | return mJournal.getLoseKey();
86 | }
87 |
88 | @Override
89 | public long getTotalSize() {
90 | long size = mStorage.getTotalSize();
91 | Utils.checkNotLessThanZero(size);
92 | return size;
93 | }
94 |
95 | @Override
96 | public long getTotalQuantity() {
97 | long quantity = mStorage.getTotalQuantity();
98 | Utils.checkNotLessThanZero(quantity);
99 | return quantity;
100 | }
101 |
102 | }
103 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/memory/journal/BasicMemoryJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.memory.journal;
2 |
3 | import com.im4j.kakacache.rxjava.common.exception.NullException;
4 | import com.im4j.kakacache.rxjava.common.utils.L;
5 | import com.im4j.kakacache.rxjava.common.utils.Utils;
6 | import com.im4j.kakacache.rxjava.core.CacheEntry;
7 |
8 | import java.io.IOException;
9 | import java.util.Collection;
10 | import java.util.LinkedHashMap;
11 |
12 | /**
13 | * 缓存日志-基类
14 | * @version alafighting 2016-07
15 | */
16 | public abstract class BasicMemoryJournal implements IMemoryJournal {
17 |
18 | private final LinkedHashMap mKeyValues;
19 |
20 | public BasicMemoryJournal() {
21 | this.mKeyValues = new LinkedHashMap<>(0, 0.75f, true);
22 | }
23 |
24 | final LinkedHashMap getKeyValues() {
25 | return mKeyValues;
26 | }
27 |
28 | @Override
29 | public CacheEntry get(String key) {
30 | if (Utils.isEmpty(key)) {
31 | throw new NullException("key == null");
32 | }
33 |
34 | CacheEntry entry = mKeyValues.get(key);
35 | if (entry != null) {
36 | // 有效期内,才记录最后使用时间
37 | if (!entry.isExpiry()) {
38 | entry.setLastUseTime(System.currentTimeMillis());
39 | entry.setUseCount(entry.getUseCount() + 1);
40 | }
41 | return entry.clone();
42 | } else {
43 | return null;
44 | }
45 | }
46 |
47 | @Override
48 | public boolean put(String key, CacheEntry entry) {
49 | if (Utils.isEmpty(key) || entry == null) {
50 | throw new NullException("key == null || value == null");
51 | }
52 |
53 | L.debug("memory journal put "+key);
54 | if (!entry.isExpiry()) {
55 | entry.setLastUseTime(System.currentTimeMillis());
56 | entry.setUseCount(1);
57 | return mKeyValues.put(key, entry) != null;
58 | } else {
59 | return remove(key);
60 | }
61 | }
62 |
63 | @Override
64 | public boolean containsKey(String key) {
65 | if (Utils.isEmpty(key)) {
66 | throw new NullException("key == null");
67 | }
68 |
69 | CacheEntry entry = mKeyValues.get(key);
70 | return entry != null;
71 | }
72 |
73 | @Override
74 | public abstract String getLoseKey();
75 |
76 | @Override
77 | public boolean remove(String key) {
78 | if (Utils.isEmpty(key)) {
79 | throw new NullException("key == null");
80 | }
81 |
82 | return mKeyValues.remove(key) != null;
83 | }
84 |
85 | @Override
86 | public boolean clear() {
87 | mKeyValues.clear();
88 | return true;
89 | }
90 |
91 | @Override
92 | public Collection snapshot() {
93 | return mKeyValues.values();
94 | }
95 |
96 | @Override
97 | public void close() throws IOException {
98 | // TODO Nothing
99 | }
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/memory/journal/FIFOMemoryJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.memory.journal;
2 |
3 | import com.im4j.kakacache.rxjava.core.CacheEntry;
4 |
5 | /**
6 | * FIFO缓存日志
7 | * @version alafighting 2016-07
8 | */
9 | public class FIFOMemoryJournal extends BasicMemoryJournal {
10 |
11 | @Override
12 | public String getLoseKey() {
13 | CacheEntry entry = null;
14 | for (CacheEntry item : getKeyValues().values()) {
15 | if (entry == null || entry.getCreateTime() > item.getCreateTime()) {
16 | entry = item;
17 | }
18 | }
19 | if (entry != null) {
20 | return entry.getKey();
21 | } else {
22 | return null;
23 | }
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/memory/journal/IMemoryJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.memory.journal;
2 |
3 | import com.im4j.kakacache.rxjava.core.CacheEntry;
4 |
5 | import java.io.Closeable;
6 | import java.util.Collection;
7 |
8 | /**
9 | * 内存缓存日志
10 | * @version alafighting 2016-04
11 | */
12 | public interface IMemoryJournal extends Closeable {
13 |
14 | CacheEntry get(String key);
15 |
16 | boolean put(String key, CacheEntry entry);
17 |
18 | boolean containsKey(String key);
19 |
20 | /**
21 | * 获取准备丢弃的Key
22 | * @return 准备丢弃的Key(如存储空间不足时,需要清理)
23 | */
24 | String getLoseKey();
25 |
26 | boolean remove(String key);
27 |
28 | boolean clear();
29 |
30 | Collection snapshot();
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/memory/journal/LFUMemoryJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.memory.journal;
2 |
3 | import com.im4j.kakacache.rxjava.core.CacheEntry;
4 |
5 | /**
6 | * LFU缓存日志
7 | * @version alafighting 2016-07
8 | */
9 | public class LFUMemoryJournal extends BasicMemoryJournal {
10 |
11 | @Override
12 | public String getLoseKey() {
13 | CacheEntry entry = null;
14 | for (CacheEntry item : getKeyValues().values()) {
15 | if (entry == null || entry.getUseCount() > item.getUseCount()) {
16 | entry = item;
17 | } else {
18 | if (entry.getUseCount() == item.getUseCount()
19 | && entry.getLastUseTime() > item.getLastUseTime()) {
20 | entry = item;
21 | }
22 | }
23 | }
24 | if (entry != null) {
25 | return entry.getKey();
26 | } else {
27 | return null;
28 | }
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/memory/journal/LRUMemoryJournal.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.memory.journal;
2 |
3 | /**
4 | * LRU缓存日志
5 | * @version alafighting 2016-07
6 | */
7 | public class LRUMemoryJournal extends BasicMemoryJournal {
8 |
9 | @Override
10 | public String getLoseKey() {
11 | return getKeyValues().entrySet().iterator().next().getKey();
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/memory/storage/IMemoryStorage.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.memory.storage;
2 |
3 | import java.io.Closeable;
4 |
5 | /**
6 | * 内存存储
7 | * @author alafighting 2016-04
8 | */
9 | public interface IMemoryStorage extends Closeable {
10 |
11 | /**
12 | * 读取
13 | * @param key
14 | * @return
15 | */
16 | Object load(String key);
17 |
18 | /**
19 | * 保存
20 | * @param key
21 | * @param value
22 | */
23 | boolean save(String key, Object value);
24 |
25 |
26 | /**
27 | * 关闭
28 | */
29 | @Override
30 | void close();
31 |
32 | /**
33 | * 删除缓存
34 | * @param key
35 | */
36 | boolean remove(String key);
37 |
38 | /**
39 | * 清空缓存
40 | */
41 | boolean clear();
42 |
43 | /**
44 | * 缓存总大小
45 | * @return 单位:byte
46 | */
47 | long getTotalSize();
48 |
49 | /**
50 | * 缓存总数目
51 | * @return 单位:缓存个数
52 | */
53 | long getTotalQuantity();
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/core/memory/storage/SimpleMemoryStorage.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.core.memory.storage;
2 |
3 | import android.graphics.Bitmap;
4 |
5 | import com.im4j.kakacache.rxjava.common.utils.L;
6 | import com.im4j.kakacache.rxjava.common.utils.MemorySizeOf;
7 | import com.im4j.kakacache.rxjava.common.utils.Utils;
8 |
9 | import java.io.Serializable;
10 | import java.util.HashMap;
11 | import java.util.Map;
12 |
13 | /**
14 | * 简单的内存存储
15 | * @version alafighting 2016-06
16 | */
17 | public class SimpleMemoryStorage implements IMemoryStorage {
18 |
19 | private Map mStorageMap;
20 |
21 | public SimpleMemoryStorage() {
22 | this.mStorageMap = new HashMap<>();
23 | }
24 |
25 | @Override
26 | public Object load(String key) {
27 | if (Utils.isEmpty(key)) {
28 | return null;
29 | }
30 | return mStorageMap.get(key);
31 | }
32 |
33 | @Override
34 | public boolean save(String key, Object value) {
35 | if (Utils.isEmpty(key)) {
36 | return true;
37 | }
38 |
39 | return mStorageMap.put(key, value) != null;
40 | }
41 |
42 | @Override
43 | public void close() {
44 | // TODO Nothing
45 | }
46 |
47 | @Override
48 | public boolean remove(String key) {
49 | if (Utils.isEmpty(key)) {
50 | return true;
51 | }
52 | return mStorageMap.remove(key) != null;
53 | }
54 |
55 | @Override
56 | public boolean clear() {
57 | mStorageMap.clear();
58 | return true;
59 | }
60 |
61 | @Override
62 | public long getTotalSize() {
63 | long totalSize = 0;
64 | for (Object value : mStorageMap.values()) {
65 | totalSize += countSize(value);
66 | }
67 | L.debug("memory total size = "+totalSize);
68 | return totalSize;
69 | }
70 |
71 | private static long countSize(Object value) {
72 | if (value == null) {
73 | return 0;
74 | }
75 |
76 | // FIXME 更优良的内存大小算法
77 | long size = 1;
78 | if (value instanceof MemorySizeOf.SizeOf) {
79 | //L.debug("SizeOf");
80 | size = MemorySizeOf.sizeOf((MemorySizeOf.SizeOf) value);
81 | } else if (value instanceof Bitmap) {
82 | //L.debug("Bitmap");
83 | size = MemorySizeOf.sizeOf((Bitmap) value);
84 | } else if (value instanceof Iterable) {
85 | //L.debug("Iterable");
86 | for (Object item : ((Iterable) value)) {
87 | size += countSize(item);
88 | }
89 | } else if (value instanceof Serializable) {
90 | //L.debug("Serializable");
91 | size = MemorySizeOf.sizeOf((Serializable) value);
92 | }
93 | //L.debug("size="+size+" value="+value);
94 | return size;
95 | }
96 |
97 | @Override
98 | public long getTotalQuantity() {
99 | return mStorageMap.size();
100 | }
101 |
102 | }
103 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/manager/RxCacheManager.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.manager;
2 |
3 | import com.im4j.kakacache.rxjava.common.exception.NotFoundException;
4 | import com.im4j.kakacache.rxjava.common.utils.L;
5 | import com.im4j.kakacache.rxjava.core.CacheCore;
6 | import com.im4j.kakacache.rxjava.core.CacheTarget;
7 |
8 | import io.reactivex.Observable;
9 |
10 | /**
11 | * RxJava模式缓存管理
12 | * @version alafighting 2016-04
13 | */
14 | public class RxCacheManager {
15 |
16 | private CacheCore cache;
17 | private int defaultExpires;
18 |
19 | /**
20 | * 构造函数
21 | * @param defaultExpires 默认有效期(毫秒)
22 | */
23 | public RxCacheManager(CacheCore cache, int defaultExpires) {
24 | this.cache = cache;
25 | this.defaultExpires = defaultExpires;
26 | }
27 |
28 | /**
29 | * 读取
30 | */
31 | public Observable load(final String key) {
32 | return Observable.just(key).map(it -> {
33 | L.debug("loadCache key="+it);
34 | try {
35 | T result = cache.load(it);
36 | if (result != null) {
37 | return result;
38 | }
39 | } catch (Throwable e) {
40 | L.debug(e);
41 | }
42 | throw new NotFoundException("load cache is null.");
43 | });
44 | }
45 |
46 | /**
47 | * 保存
48 | */
49 | public Observable save(String key, T value) {
50 | return save(key, value, defaultExpires, CacheTarget.MemoryAndDisk);
51 | }
52 | /**
53 | * 保存
54 | * @param expires 有效期(单位:毫秒)
55 | */
56 | public Observable save(final String key, final T value, final int expires) {
57 | return save(key, value, expires, CacheTarget.MemoryAndDisk);
58 | }
59 | /**
60 | * 保存
61 | * @param expires 有效期(单位:毫秒)
62 | */
63 | public Observable save(String key, final T value, final int expires, final CacheTarget target) {
64 | return Observable.just(key).map(it -> {
65 | try {
66 | cache.save(it, value, expires, target);
67 | return true;
68 | } catch (Exception e) {
69 | L.debug(e);
70 | return false;
71 | }
72 | });
73 | }
74 |
75 | /**
76 | * 是否包含
77 | */
78 | public Observable containsKey(final String key) {
79 | return Observable.just(key).map(it -> {
80 | try {
81 | return cache.containsKey(it);
82 | } catch (Exception e) {
83 | L.debug(e);
84 | return false;
85 | }
86 | });
87 | }
88 |
89 | /**
90 | * 删除缓存
91 | */
92 | public Observable remove(final String key) {
93 | return Observable.just(key).map(it -> {
94 | try {
95 | cache.remove(key);
96 | return true;
97 | } catch (Exception e) {
98 | L.debug(e);
99 | return false;
100 | }
101 | });
102 | }
103 |
104 | /**
105 | * 清空缓存
106 | */
107 | public Observable clear() {
108 | return Observable.just(0).map(it -> {
109 | try {
110 | cache.clear();
111 | return true;
112 | } catch (Exception e) {
113 | L.debug(e);
114 | return false;
115 | }
116 | });
117 | }
118 |
119 | }
120 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/netcache/ResultData.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.netcache;
2 |
3 | /**
4 | * 数据
5 | * @version alafighting 2016-06
6 | */
7 | public class ResultData {
8 |
9 | public ResultFrom from;
10 | public String key;
11 | public T data;
12 |
13 | public ResultData() {
14 | }
15 | public ResultData(ResultFrom from, String key, T data) {
16 | this.from = from;
17 | this.key = key;
18 | this.data = data;
19 | }
20 |
21 | public ResultFrom getFrom() {
22 | return from;
23 | }
24 |
25 | public void setFrom(ResultFrom from) {
26 | this.from = from;
27 | }
28 |
29 | public String getKey() {
30 | return key;
31 | }
32 |
33 | public void setKey(String key) {
34 | this.key = key;
35 | }
36 |
37 | public T getData() {
38 | return data;
39 | }
40 |
41 | public void setData(T data) {
42 | this.data = data;
43 | }
44 |
45 | @Override
46 | public String toString() {
47 | return "ResultData{" +
48 | "from=" + from +
49 | ", key='" + key + '\'' +
50 | ", data=" + data +
51 | '}';
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/netcache/ResultFrom.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.netcache;
2 |
3 | /**
4 | * 数据来源
5 | * @version alafighting 2016-06
6 | */
7 | public enum ResultFrom {
8 | Remote, Cache
9 | }
10 |
--------------------------------------------------------------------------------
/library/src/main/java/com/im4j/kakacache/rxjava/netcache/strategy/CacheStrategy.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava.netcache.strategy;
2 |
3 | import com.im4j.kakacache.rxjava.KakaCache;
4 | import com.im4j.kakacache.rxjava.common.exception.NotFoundException;
5 | import com.im4j.kakacache.rxjava.common.utils.L;
6 | import com.im4j.kakacache.rxjava.netcache.ResultData;
7 | import com.im4j.kakacache.rxjava.netcache.ResultFrom;
8 |
9 | import io.reactivex.Observable;
10 | import io.reactivex.internal.operators.single.SingleToObservable;
11 | import io.reactivex.schedulers.Schedulers;
12 |
13 | /**
14 | * 缓存策略
15 | * @version alafighting 2016-07
16 | * @version imkarl 2017-02 调整为rx2的语法,优化实现逻辑
17 | */
18 | public enum CacheStrategy {
19 | /** 仅缓存 */
20 | OnlyCache{
21 | @Override
22 | Observable> execute(String key,
23 | Observable> cache,
24 | Observable> remote) {
25 | return cache;
26 | }
27 | },
28 | /** 仅网络 */
29 | OnlyRemote{
30 | @Override
31 | Observable> execute(String key,
32 | Observable> cache,
33 | Observable> remote) {
34 | return remote;
35 | }
36 | },
37 |
38 | /** 优先缓存 */
39 | FirstCache{
40 | @Override
41 | Observable> execute(String key,
42 | Observable> cache,
43 | Observable> remote) {
44 | cache = cache.onErrorReturnItem(new ResultData<>(ResultFrom.Cache, key, null));
45 | return new SingleToObservable<>(Observable.concat(cache, remote)
46 | .filter(it -> it != null && it.data != null)
47 | .first(new ResultData<>(null, key, null)));
48 | }
49 | },
50 | /** 优先服务器 */
51 | FirstRemote{
52 | @Override
53 | Observable> execute(String key,
54 | Observable> cache,
55 | Observable> remote) {
56 | remote = remote.onErrorReturnItem(new ResultData<>(ResultFrom.Remote, key, null));
57 | return new SingleToObservable<>(Observable.concat(remote, cache)
58 | .filter(it -> it != null && it.data != null)
59 | .first(new ResultData<>(null, key, null)));
60 | }
61 | },
62 | /** 先缓存,后网络 */
63 | CacheAndRemote{
64 | @Override
65 | Observable> execute(String key,
66 | Observable> cache,
67 | Observable> remote) {
68 | cache = cache.onErrorReturnItem(new ResultData<>(ResultFrom.Cache, key, null));
69 | return Observable.concat(cache, remote)
70 | .filter(result -> result != null && result.data != null);
71 | }
72 | };
73 |
74 |
75 |
76 | public final Observable> execute(String key, Observable source, int expires) {
77 | Observable> cache = KakaCache.manager().load(key)
78 | .subscribeOn(Schedulers.io())
79 | .observeOn(Schedulers.io())
80 | .map(it -> {
81 | L.debug("loadCache result="+it);
82 | return new ResultData<>(ResultFrom.Cache, key, (T) it);
83 | });
84 | Observable> remote = source
85 | .subscribeOn(Schedulers.io())
86 | .observeOn(Schedulers.io())
87 | .map(it -> {
88 | L.debug("loadRemote result="+it);
89 | KakaCache.manager()
90 | .save(key, it, expires)
91 | .subscribe(status -> L.debug("save status => "+status), L::debug);
92 | return new ResultData<>(ResultFrom.Remote, key, it);
93 | });
94 |
95 | return execute(key, cache, remote)
96 | .subscribeOn(Schedulers.io())
97 | .observeOn(Schedulers.io())
98 | .flatMap(it -> {
99 | if (it == null || it.data == null) {
100 | return Observable.error(new NotFoundException("load data is null."));
101 | } else {
102 | return Observable.just(it);
103 | }
104 | });
105 | }
106 |
107 | abstract Observable> execute(String key,
108 | Observable> cache,
109 | Observable> remote);
110 |
111 | }
112 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | KakaCache For RxJava
3 |
4 |
--------------------------------------------------------------------------------
/library/src/test/java/com/im4j/kakacache/rxjava/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.im4j.kakacache.rxjava;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 |
--------------------------------------------------------------------------------