[Store5] Target Android, iOS, JVM, JS (#493)

* [Temp] Remove all modules

* Remove references to Store 4

* Update CHANGELOG

* Update README

* Add Store 5 foundation
Co-authored-by: Andre Claßen <aclassen@users.noreply.github.com>
Co-authored-by: Mike Nakhimovich <mnakhimovich@Mikes-MBP.localdomain>
This commit is contained in:
mnakhimovich 2023-01-16 16:28:45 -05:00
parent 53a974e423
commit fee0bccde7
263 changed files with 5475 additions and 19837 deletions

15
.codecov.yml Normal file
View file

@ -0,0 +1,15 @@
coverage:
range: 50..80
round: down
precision: 2
comment:
layout: diff, files
ignore:
- "**/fake"
- "**/commonTest"
- "**/androidTest"
- "**/iOSTest"
- "**/jsTest"
- "**/jvmTest"

View file

@ -12,7 +12,7 @@ on:
jobs:
publish:
runs-on: ubuntu-latest
runs-on: macos-latest
if: github.repository == 'MobileNativeFoundation/Store' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/store5')
steps:

22
.github/workflows/check.yml vendored Normal file
View file

@ -0,0 +1,22 @@
name: Check
on: push
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Gradle
uses: gradle/gradle-build-action@v2
- name: Run check with Gradle Wrapper
run: ./gradlew check
coverage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- uses: codecov/codecov-action@v3
with:
files: ./kover/coverage.xml
name: codecov-umbrella
verbose: true

View file

@ -0,0 +1,7 @@
name: Create Swift Package
on:
workflow_dispatch:
jobs:
publish:
uses: touchlab/KMMBridgeGithubWorkflow/.github/workflows/faktorybuildbranches.yml@v0.6

4
.gitignore vendored
View file

@ -46,3 +46,7 @@ captures/
# Keystore files
*.jks
store/kover
*.podspec
yarn.lock

View file

@ -1,86 +1,104 @@
Change Log
==========
# Changelog
## [Unreleased]
The change log for Store version 1.x can be found [here](https://github.com/NYTimes/Store/blob/develop/CHANGELOG.md).
## [5.0.0-alpha03] (2022-12-18)
Version 4.0.7 (2022-11-20)
----------------------------
* Update CI
This release adds support for Store on iOS, JVM, and JS. Concepts and usage are unchanged from
Store4. In a future release we will reintroduce support for local and remote writes with conflict
resolution based on Google's offline first guidance.
Version 4.0.6 (2022-11-20)
----------------------------
* Flip coordinates from `com.dropbox.mobile.store` to `org.mobilenativefoundation.store`
* Target Android, iOS, JVM, JS
* Remove concept of Market
* Remove support for local and remote writes (temporary)
## [5.0.0-alpha02] (2022-12-04)
* Target iOS and JS
* Rename packages
## [5.0.0-alpha1] (2022-12-04)
* Introduce Market
* Support local and remote writes with conflict resolution based on Google's offline-first guidance
* Target Android and JVM
## [4.0.5] (2021-03-30)
Version 4.0.5 (2021-03-30)
----------------------------
* Update to Kotlin 1.6.10
* Store `4.0.4-KT15` is the last version supporting Kotlin 1.5
* Store `4.0.1` is the last version supporting Kotlin 1.4
Version 4.0.4-KT15 *(2021-12-08)
----------------------------
** Bug fixes and documentation updates
## [4.0.4-KT15] (2021-12-08)
Version 4.0.3-KT15 *(2021-11-18)
----------------------------
** Update to Kotlin 1.5.31 and Coroutines 1.5.2
** Bug fixes and documentation updates
* Bug fixes and documentation updates
## [4.0.3-KT15] (2021-11-18)
* Update to Kotlin 1.5.31 and Coroutines 1.5.2
* Bug fixes and documentation updates
## [4.0.2-KT15] (2021-05-06)
Version 4.0.2-KT15 *(2021-05-06)
----------------------------
**Kotlin 1.5 introduced breaking changes in the experimental Duration apis we used**
**4.0.2-KT15 is a duplicate of 4.0.1 but compiled for kotlin 1.5**
**Version 4.0.1 is the last version compatible with Kotlin 1.4**
* Fire off kotlin 1.5 compatible snapshot (#273)
## [4.0.1] (2021-05-06)
Version 4.0.1 *(2021-05-06)*
----------------------------
* Fixes issues when upgrading to kotlin 1.5 (Deprecated duration api)
* Fix issues when upgrading to kotlin 1.5 (Deprecated duration api)
* Add piggyback to all stores
Version 4.0.0 *(2020-11-30)*
----------------------------
* update coroutines to 1.4.0, kotlin to 1.4.10 [#242](https://github.com/dropbox/Store/pull/242)
## [4.0.0] (2020-11-30)
* Update coroutines to 1.4.0, kotlin to 1.4.10 [#242](https://github.com/dropbox/Store/pull/242)
## [4.0.0-beta] (2020-09-21)
Version 4.0.0-beta *(2020-09-21)*
----------------------------
**API change**
* Remove need for generics with `Error` type (#220)
**Bug Fixes and Stability Improvements**
* Revert cache implementation to guava, rather than rolling our own (#200)
* Sample App improvements (#227)
Version 4.0.0-alpha07 *(2020-08-19)*
----------------------------
## [4.0.0-alpha07] (2020-08-19)
**New Features**
* Add `StoreResult.NoNewData` to represent when a fetcher didn't return data. (#194)
* Move `Fetcher`-factories into `Companion` of `Fetcher` interface (#168)
**Bug Fixes and Stability Improvements**
* Fix a leak of non-global coroutine contexts. (#199)
* Update to Kotlin 1.4.0 and Coroutines 1.3.9 (#195)
* Update to Coroutines 1.3.5 and remove `@FlowPreview` and `@ExperimentalCoroutinesApi` annotations. (#166)
* Update to Coroutines 1.3.5 and remove `@FlowPreview` and `@ExperimentalCoroutinesApi`
annotations. (#166)
## [4.0.0-alpha06] (2020-04-29)
Version 4.0.0-alpha06 *(2020-04-29)*
----------------------------
**Major API change!** (#123)
This release introduces a major change to `StoreBuilder`'s API. This should be the LAST major API change to store before we'll move to beta.
This release introduces a major change to `StoreBuilder`'s API. This should be the LAST major API
change to store before
we'll move to beta.
* The typealias `Fetcher` was added to standardize the input type for a `StoreBuilder`
* `SourceOfTruth` in now a top level interface and part of `Store`'s public API
* `StoreBuilder` can now only be created using a `Fetcher` and optionally a `SourceOfTruth`
* All the overloads for creating a `StoreBuilder` were moved to `Fetcher` and `SourceOfTruth` as appropriate.
* All the overloads for creating a `StoreBuilder` were moved to `Fetcher` and `SourceOfTruth` as
appropriate.
* Rx artifacts were updated accordingly to match main artifacts.
Version 4.0.0-alpha05 *(2020-04-03)*
----------------------------
## [4.0.0-alpha05] (2020-04-03)
**Bug Fixes and Stability Improvements**
* Contain @ExperimentalStdlibApi within relevant scope. (#154)
* Use AtomicFu to replace Java's AtomicBoolean and ReentrantLock (#147)
* migrate Multicast to Kotlin Test (#146)
@ -88,10 +106,10 @@ Version 4.0.0-alpha05 *(2020-04-03)*
* Update AGP version (#143)
* Remove some unneeded java.util packages (#141)
Version 4.0.0-alpha04 *(2020-04-03)*
----------------------------
## [4.0.0-alpha04] (2020-04-03)
**New Features**
* Add `asMap` function to Cache for backward compat (#136)
* Migrate filesystem library to use kotlin.time APIs (#133)
* Rx get fresh bindings (#130)
@ -99,38 +117,38 @@ Version 4.0.0-alpha04 *(2020-04-03)*
* Update sample app (#117)
**Bug Fixes and Stability Improvements**
* Use Kotlin version of ArrayDeque in ChannelManager (#134)
* Kotlin 1.3.70 and other dependencies updates (#125)
* Make SharedFlowProducer APIs safe (#121)
* Ensure network starts after disk is established (#115)
* Update to Gradle 6.2 (#111)
Version 4.0.0-alpha03 *(2020-02-13)*
----------------------------
## [4.0.0-alpha03] (2020-02-13)
**New Features**
* Added Rx bindings, available as store-rx2 artifact (#93)
* Bug fixes (#90)
* Add ability to delete all entries in the store (#79)
Version 4.0.0-alpha02 *(2020-01-29)*
----------------------------
## [4.0.0-alpha02] (2020-01-29)
**New Features**
* Introduce piggyback only downstreams to multicaster and fix #59 (#75)
* Change flow collection util to drain the flow (#64)
* Readme improvements (#70, #72)
* Avoid illegal cast in RealStore.stream (#69)
* Added docs to MemoryPolicy.setMemorySize (#67) (#68)
Version 4.0.0-alpha01 *(2020-01-08)*
----------------------------
## [4.0.0-alpha01] (2020-01-08)
**New Features**
* Store has been rewritten using Kotlin Coroutines instead of RxJava
Version 3.1.0 *(2018-06-07)*
----------------------------
## [3.1.0] (2018-06-07)
**New Features**
@ -146,16 +164,14 @@ Version 3.1.0 *(2018-06-07)*
* (#273) Adds comments to the sample app
* (#336) Fixes errors in README
Version 3.0.1 *(2018-03-20)*
----------------------------
## [3.0.1] (2018-03-20)
**Bug Fixes and Stability Improvements**
* (#311) Update Kotlin & AGP versions
* (#314) Fix issues occured from RxJava1 dependency
Version 3.0.0 *(2018-02-01)*
----------------------------
## [3.0.0] (2018-02-01)
**New Features**
@ -169,8 +185,7 @@ Version 3.0.0 *(2018-02-01)*
* (#259, #261, #272, #289, #303) README + documentation updates
* (#310) Sample app fixes
Version 3.0.0-beta *(2017-07-26)*
----------------------------
## [3.0.0-beta] (2017-07-26)
**New Features**
@ -187,29 +202,81 @@ Version 3.0.0-beta *(2017-07-26)*
* (#246) Update to Moshi 1.5.0
* (#252) Fix stream for a single barcode
Version 3.0.0-alpha *(2017-05-23)*
----------------------------
## [3.0.0-alpha] (2017-05-23)
This is a first alpha release of Store ported to RxJava 2.
**New Features**
* (#155) Port to RxJava 2
* (#220) Packages have been renamed to store3 to allow use of this artifact alongside the original Store
* (#220) Packages have been renamed to store3 to allow use of this artifact alongside the original
Store
* (#185) Return Single/Maybe where appropriate
* (#189) Add lambdas to Store and Filesystem modules
* (#214) expireAfterAccess added to MemoryPolicy
* (#214) Deprecate setExpireAfter and getExpireAfter -- use new expireAfterWrite or expireAfterAccess, see #199 for
* (#214) Deprecate setExpireAfter and getExpireAfter -- use new expireAfterWrite or
expireAfterAccess, see #199 for
MemoryPolicy changes
* (#214) Add Raw to BufferedSource transformer
**Bug Fixes and Stability Improvements**
* (#214) Fix networkBeforeStale on cold start with no connectivity
* (#214) Add a missing source.close() call
* (#164) FileSystemPersister.persisterIsStale() should return false if record is missing or policy is unspecified
* (#164) FileSystemPersister.persisterIsStale() should return false if record is missing or policy
is unspecified
* (#166) Remove apt dependency and use annotationProcessor instead
* (#214) Standardize store.stream() to emit only new items
* (#214) Fix typos
* (#214) Close source after write to filesystem
## [1.x]
* The change log for Store version 1.x can be
found [here](https://github.com/NYTimes/Store/blob/develop/CHANGELOG.md).
[Unreleased]: https://github.com/MobileNativeFoundation/Store/compare/v4.0.5...HEAD
[5.0.0-alpha02]: https://github.com/MobileNativeFoundation/Store/releases/tag/5.0.0-alpha02
[5.0.0-alpha1]: https://github.com/MobileNativeFoundation/Store/releases/tag/5.0.0-alpha1
[4.0.5]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.5
[4.0.4-KT15]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.4-KT15
[4.0.3-KT15]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.3-KT15
[4.0.2-KT15]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.2-KT15
[4.0.1]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.1
[4.0.0]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.0
[4.0.0-beta]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.0-beta
[4.0.0-alpha07]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.0-alpha07
[4.0.0-alpha06]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.0-alpha06
[4.0.0-alpha05]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.0-alpha05
[4.0.0-alpha04]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.0-alpha04
[4.0.0-alpha03]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.0-alpha03
[4.0.0-alpha02]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.0-alpha02
[4.0.0-alpha01]: https://github.com/MobileNativeFoundation/Store/releases/tag/4.0.0-alpha01
[3.1.0]: https://github.com/MobileNativeFoundation/Store/releases/tag/3.1.0
[3.0.1]: https://github.com/MobileNativeFoundation/Store/releases/tag/3.0.1
[3.0.0]: https://github.com/MobileNativeFoundation/Store/releases/tag/3.0.0
[3.0.0-beta]: https://github.com/MobileNativeFoundation/Store/releases/tag/3.0.0-beta
[3.0.0-alpha]: https://github.com/MobileNativeFoundation/Store/releases/tag/3.0.0-alpha
[1.x]: https://github.com/NYTimes/Store/blob/develop/CHANGELOG.md

208
README.md
View file

@ -1,57 +1,62 @@
# Store 4
# Store 5
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.mobilenativefoundation.store/store4/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.mobilenativefoundation.store/store4/)
## Why We Made Store
[![codecov](https://codecov.io/gh/dropbox/Store/branch/master/graph/badge.svg)](https://codecov.io/gh/dropbox/Store)
- Modern software needs data representations to be fluid and always available.
- Users expect their UI experience to never be compromised (blocked) by new data loads. Whether an
application is social, news or business-to-business, users expect a seamless experience both
online and offline.
- International users expect minimal data downloads as many megabytes of downloaded data can quickly
result in astronomical phone bills.
Store is a Kotlin library for loading data from remote and local sources.
### The Problems:
+ Modern software needs data representations to be fluid and always available.
+ Users expect their UI experience to never be compromised (blocked) by new data loads. Whether an application is social, news or business-to-business, users expect a seamless experience both online and offline.
+ International users expect minimal data downloads as many megabytes of downloaded data can quickly result in astronomical phone bills.
A Store is a class that simplifies fetching, sharing, storage, and retrieval of data in your application. A Store is similar to the [Repository pattern](https://msdn.microsoft.com/en-us/library/ff649690.aspx) while exposing an API built with [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html) that adheres to a unidirectional data flow.
Store provides a level of abstraction between UI elements and data operations.
### Overview
A Store is responsible for managing a particular data request. When you create an implementation of a Store, you provide it with a `Fetcher`, a function that defines how data will be fetched over network. You can also define how your Store will cache data in-memory and on-disk. Since Store returns your data as a `Flow`, threading is a breeze! Once a Store is built, it handles the logic around data flow, allowing your views to use the best data source and ensuring that the newest data is always available for later offline use.
A Store is responsible for managing a particular data request. When you create an implementation of
a Store, you provide it with a `Fetcher`, a function that defines how data will be fetched over
network. You can also define how your Store will cache data in-memory and on-disk. Since Store
returns your data as a `Flow`, threading is a breeze! Once a Store is built, it handles the logic
around data flow, allowing your views to use the best data source and ensuring that the newest data
is always available for later offline use.
Store leverages multiple request throttling to prevent excessive calls to the network and disk cache. By utilizing Store, you eliminate the possibility of flooding your network with the same request while adding two layers of caching (memory and disk) as well as ability to add disk as a source of truth where you can modify the disk directly without going through Store (works best with databases that can provide observables sources like [Jetpack Room](https://developer.android.com/jetpack/androidx/releases/room), [SQLDelight](https://github.com/cashapp/sqldelight) or [Realm](https://realm.io/products/realm-database/))
Store leverages multiple request throttling to prevent excessive calls to the network and disk
cache. By utilizing Store, you eliminate the possibility of flooding your network with the same
request while adding two layers of caching (memory and disk) as well as ability to add disk as a
source of truth where you can modify the disk directly without going through Store (works best with
databases that can provide observables sources
like [Jetpack Room](https://developer.android.com/jetpack/androidx/releases/room)
, [SQLDelight](https://github.com/cashapp/sqldelight)
or [Realm](https://realm.io/products/realm-database/))
### How to include in your project
Artifacts are hosted on **Maven Central**.
###### Latest version:
```groovy
def store_version = "4.0.7"
```kotlin
STORE_VERSION = "5.0.0-alpha03"
```
###### Add the dependency to your `build.gradle`:
### Android
```groovy
implementation "org.mobilenativefoundation.store:store4:${store_version}"
implementation "org.mobilenativefoundation.store:store5:$STORE_VERSION"
```
###### Set the source & target compatibilities to `1.8`
### Multiplatform (Common, JVM, Native, JS)
```groovy
android {
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
```kotlin
commonMain {
dependencies {
implementation("org.mobilenativefoundation.store:store5:$STORE_VERSION")
}
...
}
```
### Fully Configured Store
Let's start by looking at what a fully configured Store looks like. We will then walk through simpler examples showing each piece:
Let's start by looking at what a fully configured Store looks like. We will then walk through
simpler examples showing each piece:
```kotlin
StoreBuilder
@ -67,6 +72,7 @@ StoreBuilder
```
With the above setup you have:
+ In-memory caching for rotation
+ Disk caching for when users are offline
+ Throttling of API calls when parallel requests are made for the same resource
@ -76,8 +82,8 @@ And now for the details:
### Creating a Store
You create a Store using a builder. The only requirement is to include a `Fetcher` which is just a `typealias` to a function that returns a `Flow<FetcherResult<ReturnType>>`.
You create a Store using a builder. The only requirement is to include a `Fetcher` which is just
a `typealias` to a function that returns a `Flow<FetcherResult<ReturnType>>`.
```kotlin
val store = StoreBuilder
@ -85,27 +91,39 @@ val store = StoreBuilder
.build()
```
Store uses generic keys as identifiers for data. A key can be any value object that properly implements `toString()`, `equals()` and `hashCode()`. When your `Fetcher` function is called, it will be passed a particular `Key` value. Similarly, the key will be used as a primary identifier within caches (Make sure to have a proper `hashCode()`!!).
Store uses generic keys as identifiers for data. A key can be any value object that properly
implements `toString()`, `equals()` and `hashCode()`. When your `Fetcher` function is called, it
will be passed a particular `Key` value. Similarly, the key will be used as a primary identifier
within caches (Make sure to have a proper `hashCode()`!!).
Note: We highly recommend using built-in types that implement `equals` and `hashcode` or Kotlin `data` classes for complex keys.
Note: We highly recommend using built-in types that implement `equals` and `hashcode` or
Kotlin `data` classes for complex keys.
### Public Interface - Stream
The primary function provided by a `Store` instance is the `stream` function which has the following signature:
The primary function provided by a `Store` instance is the `stream` function which has the following
signature:
```kotlin
fun stream(request: StoreRequest<Key>): Flow<StoreResponse<Output>>
```
Each `stream` call receives a `StoreRequest` object, which defines which key to fetch and which data sources to utilize.
The response is a `Flow` of `StoreResponse`. `StoreResponse` is a Kotlin sealed class that can be either
Each `stream` call receives a `StoreRequest` object, which defines which key to fetch and which data
sources to utilize.
The response is a `Flow` of `StoreResponse`. `StoreResponse` is a Kotlin sealed class that can be
either
a `Loading`, `Data` or `Error` instance.
Each `StoreResponse` includes an `origin` field which specifies where the event is coming from.
* The `Loading` class only has an `origin` field. This can provide you information like "network is fetching data", which can be a good signal to activate the loading spinner in your UI.
* The `Loading` class only has an `origin` field. This can provide you information like "network is
fetching data", which can be a good signal to activate the loading spinner in your UI.
* The `Data` class has a `value` field which includes an instance of the type returned by `Store`.
* The `Error` class includes an `error` field that contains the exception thrown by the given `origin`.
* The `Error` class includes an `error` field that contains the exception thrown by the
given `origin`.
When an error happens, `Store` does not throw an exception, instead, it wraps it in a `StoreResponse.Error` type which allows `Flow` to continue so that it can still receive updates that might be triggered by either changes in your data source or subsequent fetch operations.
When an error happens, `Store` does not throw an exception, instead, it wraps it in
a `StoreResponse.Error` type which allows `Flow` to continue so that it can still receive updates
that might be triggered by either changes in your data source or subsequent fetch operations.
```kotlin
viewModelScope.launch {
@ -127,8 +145,14 @@ viewModelScope.launch {
For convenience, there are `Store.get(key)` and `Store.fresh(key)` extension functions.
* `suspend fun Store.get(key: Key): Value`: This method returns a single value for the given key. If available, it will be returned from the in memory cache or the sourceOfTruth. An error will be thrown if no value is available in either the `cache` or `sourceOfTruth`, and the `fetcher` fails to load the data from the network.
* `suspend fun Store.fresh(key: Key): Value`: This method returns a single value for the given key that is obtained by querying the fetcher. An error will be thrown if the `fetcher` fails to load the data from the network, regardless of whether any value is available in the `cache` or `sourceOfTruth`.
* `suspend fun Store.get(key: Key): Value`: This method returns a single value for the given key. If
available, it will be returned from the in memory cache or the sourceOfTruth. An error will be
thrown if no value is available in either the `cache` or `sourceOfTruth`, and the `fetcher` fails
to load the data from the network.
* `suspend fun Store.fresh(key: Key): Value`: This method returns a single value for the given key
that is obtained by querying the fetcher. An error will be thrown if the `fetcher` fails to load
the data from the network, regardless of whether any value is available in the `cache`
or `sourceOfTruth`.
```kotlin
lifecycleScope.launchWhenStarted {
@ -137,29 +161,45 @@ lifecycleScope.launchWhenStarted {
}
```
The first time you call to `suspend store.get(key)`, the response will be stored in an in-memory cache and in the sourceOfTruth, if provided.
All subsequent calls to `store.get(key)` with the same `Key` will retrieve the cached version of the data, minimizing unnecessary data calls. This prevents your app from fetching fresh data over the network (or from another external data source) in situations when doing so would unnecessarily waste bandwidth and battery. A great use case is any time your views are recreated after a rotation, they will be able to request the cached data from your Store. Having this data available can help you avoid the need to retain this in the view layer.
By default, 100 items will be cached in memory for 24 hours. You may [pass in your own memory policy to override the default policy](#Configuring-In-memory-Cache).
The first time you call to `suspend store.get(key)`, the response will be stored in an in-memory
cache and in the sourceOfTruth, if provided.
All subsequent calls to `store.get(key)` with the same `Key` will retrieve the cached version of the
data, minimizing unnecessary data calls. This prevents your app from fetching fresh data over the
network (or from another external data source) in situations when doing so would unnecessarily waste
bandwidth and battery. A great use case is any time your views are recreated after a rotation, they
will be able to request the cached data from your Store. Having this data available can help you
avoid the need to retain this in the view layer.
By default, 100 items will be cached in memory for 24 hours. You
may [pass in your own memory policy to override the default policy](#Configuring-In-memory-Cache).
### Skipping Memory/Disk
Alternatively, you can call `store.fresh(key)` to get a `suspended result` that skips the memory (and optional disk cache).
Alternatively, you can call `store.fresh(key)` to get a `suspended result` that skips the memory (
and optional disk cache).
A good use case is overnight background updates use `fresh()` to make sure that calls to `store.get()` will not have to hit the network during normal usage. Another good use case for `fresh()` is when a user wants to pull to refresh.
A good use case is overnight background updates use `fresh()` to make sure that calls
to `store.get()` will not have to hit the network during normal usage. Another good use case
for `fresh()` is when a user wants to pull to refresh.
Calls to both `fresh()` and `get()` emit one value or throw an error.
### Stream
For real-time updates, you may also call `store.stream()` which returns a `Flow<T>` that emits each time a new item is returned from your store. You can think of stream as a way to create reactive streams that update when you db or memory cache updates
For real-time updates, you may also call `store.stream()` which returns a `Flow<T>` that emits each
time a new item is returned from your store. You can think of stream as a way to create reactive
streams that update when you db or memory cache updates
example calls:
```kotlin
lifecycleScope.launchWhenStarted {
store.stream(StoreRequest.cached(3, refresh = false)) //will get cached value followed by any fresh values, refresh will also trigger network call if set to `true` even if the data is available in cache or disk.
store.stream(
StoreRequest.cached(
3,
refresh = false
)
) //will get cached value followed by any fresh values, refresh will also trigger network call if set to `true` even if the data is available in cache or disk.
.collect {}
store.stream(StoreRequest.fresh(3)) //skip cache, go directly to fetcher
.collect {}
@ -168,20 +208,31 @@ lifecycleScope.launchWhenStarted {
### Inflight Debouncer
To prevent duplicate requests for the same data, Store offers an inflight debouncer. If the same request is made as a previous identical request that has not completed, the same response will be returned. This is useful for situations when your app needs to make many async calls for the same data at startup or when users are obsessively pulling to refresh. As an example, The New York Times news app asynchronously calls `ConfigStore.get()` from 12 different places on startup. The first call blocks while all others wait for the data to arrive. We have seen a dramatic decrease in the app's data usage after implementing this inflight logic.
To prevent duplicate requests for the same data, Store offers an inflight debouncer. If the same
request is made as a previous identical request that has not completed, the same response will be
returned. This is useful for situations when your app needs to make many async calls for the same
data at startup or when users are obsessively pulling to refresh. As an example, The New York Times
news app asynchronously calls `ConfigStore.get()` from 12 different places on startup. The first
call blocks while all others wait for the data to arrive. We have seen a dramatic decrease in the
app's data usage after implementing this inflight logic.
### Disk as Cache
Stores can enable disk caching by passing a `SourceOfTruth` into the builder. Whenever a new network request is made, the Store will first write to the disk cache and then read from the disk cache.
Stores can enable disk caching by passing a `SourceOfTruth` into the builder. Whenever a new network
request is made, the Store will first write to the disk cache and then read from the disk cache.
### Disk as Single Source of Truth
Providing `sourceOfTruth` whose `reader` function can return a `Flow<Value?>` allows you to make Store treat your disk as source of truth.
Providing `sourceOfTruth` whose `reader` function can return a `Flow<Value?>` allows you to make
Store treat your disk as source of truth.
Any changes made on disk, even if it is not made by Store, will update the active `Store` streams.
This feature, combined with persistence libraries that provide observable queries ([Jetpack Room](https://developer.android.com/jetpack/androidx/releases/room), [SQLDelight](https://github.com/cashapp/sqldelight) or [Realm](https://realm.io/products/realm-database/))
allows you to create offline first applications that can be used without an active network connection while still providing a great user experience.
This feature, combined with persistence libraries that provide observable
queries ([Jetpack Room](https://developer.android.com/jetpack/androidx/releases/room)
, [SQLDelight](https://github.com/cashapp/sqldelight)
or [Realm](https://realm.io/products/realm-database/))
allows you to create offline first applications that can be used without an active network
connection while still providing a great user experience.
```kotlin
StoreBuilder
@ -196,11 +247,18 @@ StoreBuilder
).build()
```
Stores dont care how youre storing or retrieving your data from disk. As a result, you can use Stores with object storage or any database (Realm, SQLite, CouchDB, Firebase etc). Technically, there is nothing stopping you from implementing an in-memory cache for the "sourceOfTruth" implementation and instead have two levels of in-memory caching--one with inflated and one with deflated models, allowing for sharing of the “sourceOfTruth” cache data between stores.
Stores dont care how youre storing or retrieving your data from disk. As a result, you can use
Stores with object storage or any database (Realm, SQLite, CouchDB, Firebase etc). Technically,
there is nothing stopping you from implementing an in-memory cache for the "sourceOfTruth"
implementation and instead have two levels of in-memory caching--one with inflated and one with
deflated models, allowing for sharing of the “sourceOfTruth” cache data between stores.
If using SQLite we recommend working with [Room](https://developer.android.com/topic/libraries/architecture/room) which returns a `Flow` from a query
If using SQLite we recommend working
with [Room](https://developer.android.com/topic/libraries/architecture/room) which returns a `Flow`
from a query
The above builder is how we recommend working with data on Android. With the above setup you have:
+ Memory caching with TTL & Size policies
+ Disk caching with simple integration with Room
+ In-flight request management
@ -230,9 +288,14 @@ StoreBuilder
).build()
```
* `setMaxSize(maxSize: Long)` sets the maximum number of entries to be kept in the cache before starting to evict the least recently used items.
* `setExpireAfterAccess(expireAfterAccess: Duration)` sets the maximum time an entry can live in the cache since the last access, where "access" means reading the cache, adding a new cache entry, and replacing an existing entry with a new one. This duration is also known as **time-to-idle (TTI)**.
* `setExpireAfterWrite(expireAfterWrite: Duration)` sets the maximum time an entry can live in the cache since the last write, where "write" means adding a new cache entry and replacing an existing entry with a new one. This duration is also known as **time-to-live (TTL)**.
* `setMaxSize(maxSize: Long)` sets the maximum number of entries to be kept in the cache before
starting to evict the least recently used items.
* `setExpireAfterAccess(expireAfterAccess: Duration)` sets the maximum time an entry can live in the
cache since the last access, where "access" means reading the cache, adding a new cache entry, and
replacing an existing entry with a new one. This duration is also known as **time-to-idle (TTI)**.
* `setExpireAfterWrite(expireAfterWrite: Duration)` sets the maximum time an entry can live in the
cache since the last write, where "write" means adding a new cache entry and replacing an existing
entry with a new one. This duration is also known as **time-to-live (TTL)**.
Note that `setExpireAfterAccess` and `setExpireAfterWrite` **cannot** both be set at the same time.
@ -264,7 +327,8 @@ store.clearAll()
#### Store with sourceOfTruth
When store has a sourceOfTruth, you'll need to provide the `delete` and `deleteAll` functions for `clear(key)` and `clearAll()` to work:
When store has a sourceOfTruth, you'll need to provide the `delete` and `deleteAll` functions
for `clear(key)` and `clearAll()` to work:
```kotlin
StoreBuilder
@ -279,7 +343,8 @@ StoreBuilder
).build()
```
The following will clear the entry associated with the key from both the in-memory cache and the sourceOfTruth:
The following will clear the entry associated with the key from both the in-memory cache and the
sourceOfTruth:
```kotlin
store.clear("myKey")
@ -293,16 +358,9 @@ store.clearAll()
## License
Copyright (c) 2021 Dropbox, Inc.
```text
Copyright (c) 2022 Mobile Native Foundation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
```
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,23 +1,28 @@
Releasing
========
1. Change the version in top level `gradle.properties` to a non-SNAPSHOT verson.
2. Update the `CHANGELOG.md` for the impending release.
3. Update the `README.md` with the new version.
4. `git commit -am "Prepare for release X.Y.Z."` (where X.Y.Z is the new version)
5. `git tag -a X.Y.X -m "Version X.Y.Z"` (where X.Y.Z is the new version)
1. Change the version in top level `gradle.properties` to a non-SNAPSHOT version.
2. Update the `cocoapods` version in `build.gradle.kts` in `:store`.
3. Modify `create_swift_package.yml` workflow to run on `store5` push.
* https://github.com/MobileNativeFoundation/Store/blob/e526400cdf51aa2f78b6b7e9e87f4a6845e6dcea/.github/workflows/create_swift_package.yml
4. Update the `CHANGELOG.md` for the impending release.
5. Update the `README.md` with the new version.
6. `git commit -sam "Prepare for release X.Y.Z."` (where X.Y.Z is the new version)
7. `git tag -a X.Y.X -m "Version X.Y.Z"` (where X.Y.Z is the new version)
* Run `git tag` to verify it.
6. `git push && git push --tags`
8. `git push && git push --tags`
* This should be pushed to your fork.
7. Create a PR with this commit and merge it.
8. Update the top level `build.gradle` to the next SNAPSHOT version.
9. `git commit -am "Prepare next development version."`
10. Create a PR with this commit and merge it.
11. Login to Sonatype to promote the artifacts https://central.sonatype.org/pages/releasing-the-deployment.html
9. Create a PR with this commit and merge it.
10. Update the top level `build.gradle` to the next SNAPSHOT version.
11. Modify `create_swift_package.yml` workflow to only run manually.
* https://github.com/MobileNativeFoundation/Store/blob/de9ed1764408eeaafe5e58fe602205c875a8b0b0/.github/workflows/create_swift_package.yml
12. `git commit -am "Prepare next development version."`
13. Create a PR with this commit and merge it.
14. Login to Sonatype to promote the artifacts https://central.sonatype.org/pages/releasing-the-deployment.html
* This part is automated. If it fails in CI, follow the steps below.
* Click on Staging Repositories under Build Promotion
* Select all the Repositories that contain the content you want to release
* Click on Close and refresh until the Release button is active
* Click Release and submit
12. Update the sample module's `build.gradle` to point to the newly released version. (It may take ~2 hours for artifact to be available after release)
15. Update the sample module's `build.gradle` to point to the newly released version. (It may take ~2 hours for artifact to be available after release)

1
app/.gitignore vendored
View file

@ -1 +0,0 @@
/build

View file

@ -1,79 +0,0 @@
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'org.jetbrains.kotlin.plugin.serialization'
}
android {
compileSdkVersion versions.compileSdk
buildToolsVersion versions.buildTools
defaultConfig {
applicationId "com.dropbox.android.store.sample"
minSdkVersion 19
compileSdkVersion versions.compileSdk
targetSdkVersion versions.targetSdk
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
lint {
abortOnError false
disable 'InvalidPackage'
}
namespace 'com.dropbox.android.sample'
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {
kotlinOptions {
jvmTarget = "1.8"
freeCompilerArgs += [
'-Xopt-in=kotlin.Experimental',
]
}
}
dependencies {
testImplementation libraries.junit
testImplementation libraries.mockito
testImplementation libraries.coroutinesTest
implementation libraries.recyclerView
implementation libraries.swipeRefreshLayout
implementation libraries.appCompat
implementation libraries.fragment
implementation libraries.lifecycle
implementation libraries.material
implementation libraries.retrofit
implementation libraries.roomRuntime
implementation libraries.coreKtx
implementation libraries.lifecycleExtensions
implementation libraries.navigationFragment
implementation libraries.navigationUi
implementation libraries.constraintLayout
implementation libraries.cache
implementation libraries.kotlinSerialization
implementation libraries.okHttp
implementation libraries.picasso
implementation libraries.retrofitSerializerConverter
kapt(libraries.roomCompiler)
implementation libraries.store
implementation libraries.filesystem
implementation libraries.coroutinesCore
implementation libraries.coroutinesAndroid
debugImplementation libraries.leakcanary
}

View file

@ -1,17 +0,0 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/206847/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View file

@ -1,22 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="com.dropbox.android.sample.SampleApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.dropbox.android.sample.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View file

@ -1,155 +0,0 @@
package com.dropbox.android.sample
import android.content.Context
import android.text.Html
import androidx.room.Room
import com.dropbox.android.external.fs3.FileSystemPersister
import com.dropbox.android.external.fs3.PathResolver
import com.dropbox.android.external.fs3.Persister
import com.dropbox.android.external.fs3.SourcePersisterFactory
import com.dropbox.android.external.fs3.filesystem.FileSystemFactory
import com.dropbox.android.external.store4.Fetcher
import com.dropbox.android.external.store4.MemoryPolicy
import com.dropbox.android.external.store4.SourceOfTruth
import com.dropbox.android.external.store4.Store
import com.dropbox.android.external.store4.StoreBuilder
import com.dropbox.android.sample.data.model.Children
import com.dropbox.android.sample.data.model.Post
import com.dropbox.android.sample.data.model.RedditDb
import com.dropbox.android.sample.data.remote.Api
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okio.Buffer
import okio.BufferedSource
import retrofit2.Retrofit
import java.io.File
import java.io.IOException
import java.nio.charset.StandardCharsets
import kotlin.time.ExperimentalTime
import kotlin.time.seconds
@OptIn(
ExperimentalTime::class,
ExperimentalStdlibApi::class
)
object Graph {
private val serializer = Json { ignoreUnknownKeys = true }
fun provideRoomStore(context: SampleApp): Store<String, List<Post>> {
val db = provideRoom(context)
return StoreBuilder
.from(
Fetcher.of { key: String ->
provideRetrofit().fetchSubreddit(key, 10).data.children.map(::toPosts)
},
sourceOfTruth = SourceOfTruth.of(
reader = db.postDao()::loadPosts,
writer = db.postDao()::insertPosts,
delete = db.postDao()::clearFeedBySubredditName,
deleteAll = db.postDao()::clearAllFeeds
)
)
.build()
}
fun provideRoomStoreMultiParam(context: SampleApp): Store<Pair<String, RedditConfig>, List<Post>> {
val db = provideRoom(context)
return StoreBuilder
.from<Pair<String, RedditConfig>, List<Post>, List<Post>>(
Fetcher.of { (query, config) ->
provideRetrofit().fetchSubreddit(query, config.limit)
.data.children.map(::toPosts)
},
sourceOfTruth = SourceOfTruth.of(
reader = { (query, _) -> db.postDao().loadPosts(query) },
writer = { (query, _), posts -> db.postDao().insertPosts(query, posts) },
delete = { (query, _) -> db.postDao().clearFeedBySubredditName(query) },
deleteAll = db.postDao()::clearAllFeeds
)
)
.build()
}
private fun provideRoom(context: SampleApp): RedditDb {
return Room.inMemoryDatabaseBuilder(context, RedditDb::class.java)
.build()
}
/**
* Returns a new Persister with the cache as the root.
*/
@Throws(IOException::class)
fun newPersister(cacheDir: File): Persister<BufferedSource, Pair<String, String>> {
return SourcePersisterFactory.create(cacheDir)
}
fun provideConfigStore(context: Context): Store<Unit, RedditConfig> {
val fileSystem = FileSystemFactory.create(context.cacheDir)
val fileSystemPersister =
FileSystemPersister.create(
fileSystem,
object : PathResolver<Unit> {
override fun resolve(key: Unit) = "config.json"
}
)
return StoreBuilder
.from<Unit, RedditConfig, RedditConfig>(
Fetcher.of {
delay(500)
RedditConfig(10)
},
sourceOfTruth = SourceOfTruth.of(
nonFlowReader = {
runCatching {
fileSystemPersister.read(Unit)
?.readString(StandardCharsets.UTF_8)
?.let { Json.decodeFromString<RedditConfig>(it) }
}.getOrNull()
},
writer = { _, config ->
val buffer = Buffer()
withContext(Dispatchers.IO) {
buffer.writeUtf8(Json.encodeToString(config))
}
fileSystemPersister.write(Unit, buffer)
}
)
)
.cachePolicy(
MemoryPolicy.builder<Any, Any>().setExpireAfterWrite(10.seconds).build()
)
.build()
}
private fun provideRetrofit(): Api {
return Retrofit.Builder()
.baseUrl("https://reddit.com/")
.addConverterFactory(serializer.asConverterFactory(contentType = "application/json".toMediaType()))
.build()
.create(Api::class.java)
}
private fun toPosts(it: Children): Post {
return it.data.copy(
preview = it.data.preview?.let {
it.copy(
images = it.images.map { image ->
@Suppress("DEPRECATION")
image.copy(
source = image.source.copy(
// preview urls are html encoded, need to escape
url = Html.fromHtml(image.source.url).toString()
)
)
}
)
}
)
}
}

View file

@ -1,20 +0,0 @@
package com.dropbox.android.sample
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.mainNavHostFragment) as NavHostFragment
val navController = navHostFragment.navController
// Setup bottom navigation with navigation controller
findViewById<BottomNavigationView>(R.id.bottomNavigationView).setupWithNavController(navController)
}
}

View file

@ -1,6 +0,0 @@
package com.dropbox.android.sample
import kotlinx.serialization.Serializable
@Serializable
data class RedditConfig(val limit: Int)

View file

@ -1,34 +0,0 @@
package com.dropbox.android.sample
import android.app.Application
import com.dropbox.android.external.fs3.Persister
import com.dropbox.android.external.store4.Store
import com.dropbox.android.sample.data.model.Post
import okio.BufferedSource
import java.io.IOException
class SampleApp : Application() {
lateinit var roomStore: Store<String, List<Post>>
lateinit var storeMultiParam: Store<Pair<String, RedditConfig>, List<Post>>
lateinit var configStore: Store<Unit, RedditConfig>
lateinit var persister: Persister<BufferedSource, Pair<String, String>>
override fun onCreate() {
super.onCreate()
initPersister()
roomStore = Graph.provideRoomStore(this)
storeMultiParam = Graph.provideRoomStoreMultiParam(this)
configStore = Graph.provideConfigStore(this)
}
private fun initPersister() {
try {
persister = Graph.newPersister(this.cacheDir)
} catch (exception: IOException) {
throw RuntimeException(exception)
}
}
}

View file

@ -1,111 +0,0 @@
package com.dropbox.android.sample.data.model
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.Index
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.RoomDatabase
import androidx.room.Transaction
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import kotlinx.coroutines.flow.Flow
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
/**
* Keeps the association between a Post and a feed
*/
@Entity(
primaryKeys = ["subredditName", "postOrder", "postId"],
indices = [Index("postId", unique = false)]
)
data class FeedEntity(
val subredditName: String,
val postOrder: Int,
val postId: String
)
// this wrapper usually doesn't make sense but we do here to avoid leaking room into the Model file
@Entity(
primaryKeys = ["id"]
)
data class PostEntity(
@Embedded
val post: Post
)
class RedditTypeConverters {
@TypeConverter
fun previewToString(preview: Preview?) = preview?.let {
Json.encodeToString(preview)
}
@TypeConverter
fun stringToPreview(preview: String?) = preview?.let {
Json.decodeFromString<Preview>(preview)
}
}
@Dao
abstract class PostDao {
@Transaction
open suspend fun insertPosts(subredditName: String, posts: List<Post>) {
// first clear the feed
clearFeedBySubredditName(subredditName)
// convert them into database models
val feedEntities = posts.mapIndexed { index: Int, post: Post ->
FeedEntity(
subredditName = subredditName,
postOrder = index,
postId = post.id
)
}
val postEntities = posts.map {
PostEntity(it)
}
// save them into the database
insertPosts(feedEntities, postEntities)
// delete posts that are not part of any feed
clearObseletePosts()
}
@Query("DELETE FROM FeedEntity WHERE subredditName = :subredditName")
abstract suspend fun clearFeedBySubredditName(subredditName: String)
@Query("DELETE FROM FeedEntity")
abstract suspend fun clearAllFeeds()
@Insert(onConflict = OnConflictStrategy.REPLACE)
protected abstract suspend fun insertPosts(
feedEntries: List<FeedEntity>,
posts: List<PostEntity>
)
@Query("DELETE FROM PostEntity WHERE id NOT IN (SELECT DISTINCT(postId) FROM FeedEntity)")
protected abstract suspend fun clearObseletePosts()
@Query(
"""
SELECT PostEntity.* FROM FeedEntity
LEFT JOIN PostEntity ON FeedEntity.postId = PostEntity.id
WHERE subredditName = :subredditName
ORDER BY FeedEntity.postOrder ASC
"""
)
abstract fun loadPosts(subredditName: String): Flow<List<Post>>
}
@Database(
version = 1,
exportSchema = false,
entities = [PostEntity::class, FeedEntity::class]
)
@TypeConverters(RedditTypeConverters::class)
abstract class RedditDb : RoomDatabase() {
abstract fun postDao(): PostDao
}

View file

@ -1,50 +0,0 @@
package com.dropbox.android.sample.data.model
import kotlinx.serialization.Serializable
@Serializable
data class RedditData(
val data: Data,
val kind: String
)
@Serializable
data class Children(
val data: Post
)
@Serializable
data class Data(
val children: List<Children>
)
@Serializable
data class Post(
val id: String,
val preview: Preview? = null,
val title: String,
val url: String,
val height: Int? = null,
val width: Int? = null,
) {
fun nestedThumbnail(): Image? {
return preview?.images?.getOrNull(0)?.source
}
}
@Serializable
data class Preview(
val images: List<Images>
)
@Serializable
data class Images(
val source: Image
)
@Serializable
data class Image(
val url: String,
val height: Int,
val width: Int
)

View file

@ -1,22 +0,0 @@
package com.dropbox.android.sample.data.remote
import com.dropbox.android.sample.data.model.RedditData
import okhttp3.ResponseBody
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface Api {
@GET("r/{subredditName}/new/.json")
suspend fun fetchSubreddit(
@Path("subredditName") subredditName: String,
@Query("limit") limit: Int
): RedditData
@GET("r/{subredditName}/new/.json")
suspend fun fetchSubredditForPersister(
@Path("subredditName") subredditName: String,
@Query("limit") limit: Int
): ResponseBody
}

View file

@ -1,31 +0,0 @@
package com.dropbox.android.sample.reddit
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.dropbox.android.sample.R
import com.dropbox.android.sample.data.model.Post
class PostAdapter : ListAdapter<Post, PostViewHolder>(PostDiffCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
val itemView = LayoutInflater.from(
parent.context
).inflate(R.layout.article_item, parent, false)
return PostViewHolder(itemView)
}
override fun onBindViewHolder(holder: PostViewHolder, position: Int) {
holder.onBind(getItem(position))
}
}
private object PostDiffCallback : DiffUtil.ItemCallback<Post>() {
override fun areItemsTheSame(oldItem: Post, newItem: Post): Boolean {
return oldItem.url == newItem.url
}
override fun areContentsTheSame(oldItem: Post, newItem: Post): Boolean {
return oldItem == newItem
}
}

View file

@ -1,31 +0,0 @@
package com.dropbox.android.sample.reddit
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.dropbox.android.sample.R
import com.dropbox.android.sample.data.model.Post
import com.squareup.picasso.Picasso
class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val title: TextView get() = itemView.findViewById(R.id.title)
private val thumbnail: ImageView get() = itemView.findViewById(R.id.thumbnail)
fun onBind(article: Post) {
title.text = article.title
val url = article.nestedThumbnail()?.url
thumbnail.isVisible = url != null
url?.let { showImage(it) }
}
private fun showImage(url: String) {
Picasso.with(itemView.context)
.load(url)
.placeholder(R.color.gray80)
.into(thumbnail)
}
}

View file

@ -1,84 +0,0 @@
package com.dropbox.android.sample.ui.reddit
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.dropbox.android.sample.R
import com.dropbox.android.sample.data.model.Post
import com.dropbox.android.sample.reddit.PostAdapter
import com.dropbox.android.sample.utils.Lce
import com.google.android.material.snackbar.Snackbar
class RedditFragment : Fragment() {
private val viewModel: RedditViewModel by viewModels()
private val adapter = PostAdapter()
private val pullToRefresh: SwipeRefreshLayout get() = requireView().findViewById(R.id.pullToRefresh)
private val subredditInput: EditText get() = requireView().findViewById(R.id.subredditInput)
private val fetchButton: Button get() = requireView().findViewById(R.id.fetchButton)
private val postRecyclerView: RecyclerView get() = requireView().findViewById(R.id.postRecyclerView)
private val root: CoordinatorLayout get() = requireView().findViewById(R.id.root)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_room_store, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel.liveData.observe(
viewLifecycleOwner,
Observer { lce: Lce<List<Post>> ->
pullToRefresh.isRefreshing = lce is Lce.Loading
when (lce) {
is Lce.Error -> showErrorMessage(lce.message)
is Lce.Success -> updateData(lce.data)
}
}
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pullToRefresh.setOnRefreshListener {
viewModel.refresh(subredditInput.text.toString())
}
fetchButton.setOnClickListener {
viewModel.refresh(subredditInput.text.toString())
}
}
private fun updateData(data: List<Post>) {
// lazily set the adapter when we have data the first time so that RecyclerView can
// restore position
if (postRecyclerView.adapter == null) {
postRecyclerView.adapter = adapter
}
adapter.submitList(data)
}
private fun showErrorMessage(message: String) {
Snackbar.make(root, message, Snackbar.LENGTH_INDEFINITE).setAction(
"refresh"
) {
viewModel.refresh(subredditInput.text.toString())
}.show()
}
}

View file

@ -1,34 +0,0 @@
package com.dropbox.android.sample.ui.reddit
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.dropbox.android.external.store4.fresh
import com.dropbox.android.external.store4.get
import com.dropbox.android.sample.SampleApp
import com.dropbox.android.sample.data.model.Post
import com.dropbox.android.sample.utils.Lce
import kotlinx.coroutines.launch
class RedditViewModel(
app: Application
) : AndroidViewModel(app) {
private val store = (app as SampleApp).storeMultiParam
private val configStore = (app as SampleApp).configStore
val liveData = MutableLiveData<Lce<List<Post>>>(Lce.Success(emptyList()))
fun refresh(key: String) {
liveData.value = Lce.Loading
viewModelScope.launch {
liveData.value = try {
val config = configStore.get(Unit)
val data = store.fresh(key to config)
Lce.Success(data)
} catch (e: Exception) {
Lce.Error(e)
}
}
}
}

View file

@ -1,149 +0,0 @@
package com.dropbox.android.sample.ui.room
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.dropbox.android.external.store4.ResponseOrigin
import com.dropbox.android.external.store4.Store
import com.dropbox.android.external.store4.StoreRequest
import com.dropbox.android.external.store4.StoreResponse
import com.dropbox.android.sample.R
import com.dropbox.android.sample.SampleApp
import com.dropbox.android.sample.reddit.PostAdapter
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.launch
class RoomFragment : Fragment() {
private val postRecyclerView: RecyclerView get() = requireView().findViewById(R.id.postRecyclerView)
private val subredditInput: EditText get() = requireView().findViewById(R.id.subredditInput)
private val pullToRefresh: SwipeRefreshLayout get() = requireView().findViewById(R.id.pullToRefresh)
private val root: ConstraintLayout get() = requireView().findViewById(R.id.root)
private val fetchButton: Button get() = requireView().findViewById(R.id.fetchButton)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_room_store, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initUI()
}
private fun initUI() {
val adapter = PostAdapter()
// lazily set the adapter when we have data the first time so that RecyclerView can
// restore position
fun setAdapterIfNotSet() {
if (postRecyclerView.adapter == null) {
postRecyclerView.adapter = adapter
}
}
val storeState = StoreState((activity?.application as SampleApp).roomStore)
lifecycleScope.launchWhenStarted {
fun refresh() {
launch {
storeState.setKey(subredditInput.text.toString())
}
}
pullToRefresh.setOnRefreshListener {
refresh()
}
launch {
storeState.loading.collect {
pullToRefresh.isRefreshing = it
}
}
launch {
storeState.errors.collect {
if (it != "") {
Snackbar.make(root, it, Snackbar.LENGTH_INDEFINITE).setAction(
"refresh"
) {
refresh()
}.show()
}
}
}
if (subredditInput.text.toString().trim() == "") {
subredditInput.setText("aww")
}
fetchButton.setOnClickListener {
refresh()
}
refresh()
storeState.data.collect {
setAdapterIfNotSet()
adapter.submitList(it)
}
}
}
}
/**
* This class should possibly be moved to a helper library but needs more API work before that.
*/
internal class StoreState<Key : Any, Output : Any>(
private val store: Store<Key, Output>
) {
private val keyFlow = Channel<Key>(capacity = Channel.CONFLATED)
private val _errors = Channel<String>(capacity = Channel.CONFLATED)
val errors
get() = _errors.consumeAsFlow()
private val _loading = Channel<Boolean>(capacity = Channel.CONFLATED)
val loading
get() = _loading.consumeAsFlow()
suspend fun setKey(key: Key) {
_errors.send("")
_loading.send(true)
keyFlow.send(key)
}
val data = keyFlow.consumeAsFlow().flatMapLatest { key ->
store.stream(
StoreRequest.cached(
key = key,
refresh = true
)
).onEach {
if (it.origin == ResponseOrigin.Fetcher) {
_loading.send(
it is StoreResponse.Loading
)
}
when (it) {
is StoreResponse.Error.Exception -> _errors.send(it.error.localizedMessage!!)
is StoreResponse.Error.Message -> _errors.send(it.message)
}
}.transform {
if (it is StoreResponse.Data) {
emit(it.value)
}
}
}
}

View file

@ -1,126 +0,0 @@
package com.dropbox.android.sample.ui.stream
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.dropbox.android.external.store4.Fetcher
import com.dropbox.android.external.store4.MemoryPolicy
import com.dropbox.android.external.store4.StoreBuilder
import com.dropbox.android.external.store4.StoreRequest
import com.dropbox.android.external.store4.fresh
import com.dropbox.android.external.store4.get
import com.dropbox.android.sample.R
import kotlin.coroutines.CoroutineContext
import kotlin.time.ExperimentalTime
import kotlin.time.seconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flattenMerge
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
@ExperimentalTime
class StreamFragment : Fragment(), CoroutineScope {
private val get_1: Button get() = requireView().findViewById(R.id.get_1)
private val get_2: Button get() = requireView().findViewById(R.id.get_2)
private val fresh_1: Button get() = requireView().findViewById(R.id.fresh_1)
private val fresh_2: Button get() = requireView().findViewById(R.id.fresh_2)
private val stream_1: TextView get() = requireView().findViewById(R.id.stream_1)
private val stream_2: TextView get() = requireView().findViewById(R.id.stream_2)
private val stream: TextView get() = requireView().findViewById(R.id.stream)
override val coroutineContext: CoroutineContext = Job() + Dispatchers.Main
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_stream, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var counter = 0
val store = StoreBuilder
.from(
Fetcher.of { key: Int ->
(key * 1000 + counter++).also { delay(1_000) }
}
)
.cachePolicy(
MemoryPolicy
.builder<Any, Any>()
.setExpireAfterWrite(10.seconds)
.build()
)
.build()
get_1.onClick {
store.get(1)
}
fresh_1.onClick {
store.fresh(1)
}
get_2.onClick {
store.get(2)
}
fresh_2.onClick {
store.fresh(2)
}
launch {
store.stream(StoreRequest.cached(1, refresh = false)).collect {
stream_1.text = "Stream 1 $it"
}
}
launch {
store.stream(StoreRequest.cached(2, refresh = false)).collect {
stream_2.text = "Stream 2 $it"
}
}
launch {
flowOf(
store.stream(StoreRequest.cached(1, refresh = false)),
store.stream(StoreRequest.cached(2, refresh = false))
)
.flattenMerge()
.collect {
stream.text = "Stream $it"
}
}
}
fun View.onClick(f: suspend () -> Unit) {
setOnClickListener {
launch {
f()
}
}
}
override fun onDestroy() {
super.onDestroy()
coroutineContext.cancel()
}
}

View file

@ -1,28 +0,0 @@
package com.dropbox.android.sample.utils
sealed class Lce<out T> {
open val data: T? = null
abstract fun <R> map(f: (T) -> R): Lce<R>
inline fun doOnData(f: (T) -> Unit) {
if (this is Success) {
f(data)
}
}
data class Success<out T>(override val data: T) : Lce<T>() {
override fun <R> map(f: (T) -> R): Lce<R> = Success(f(data))
}
data class Error(val message: String) : Lce<Nothing>() {
constructor(t: Throwable) : this(t.message ?: "")
override fun <R> map(f: (Nothing) -> R): Lce<R> = this
}
object Loading : Lce<Nothing>() {
override fun <R> map(f: (Nothing) -> R): Lce<R> = this
}
}

View file

@ -1,12 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="512dp"
android:height="512dp"
android:viewportWidth="60"
android:viewportHeight="60">
<path
android:fillColor="#FF000000"
android:pathData="m34.943,28.237 l-7.043,-4.025c-0.6203,-0.3126 -1.3584,-0.2809 -1.9496,0.0836 -0.5913,0.3645 -0.951,1.0098 -0.9504,1.7044v8c-0,1.0984 0.8857,1.9912 1.984,2 0.77,0 0.461,0.049 7.911,-4.208 0.67,-0.334 1.0973,-1.0143 1.1074,-1.7629s-0.3987,-1.4401 -1.0594,-1.7921zM27,34v-8l6.951,4.023z"/>
<path
android:fillColor="#FF000000"
android:pathData="m55,25c-2.3751,0.003 -4.4216,1.6736 -4.9,4h-7.151c-0.2088,-2.748 -1.2904,-5.3573 -3.087,-7.447l5.059,-5.06c2.1419,1.4145 5.0069,0.9774 6.6295,-1.0115 1.6226,-1.9888 1.4757,-4.8833 -0.3399,-6.6976 -1.8156,-1.8143 -4.7102,-1.9592 -6.6979,-0.3351 -1.9877,1.624 -2.4228,4.4894 -1.0068,6.6302l-5.059,5.059c-2.0897,-1.7966 -4.699,-2.8782 -7.447,-3.087v-7.151c2.515,-0.5134 4.2327,-2.8477 3.9747,-5.4015 -0.258,-2.5538 -2.4079,-4.4975 -4.9747,-4.4975s-4.7167,1.9436 -4.9747,4.4975c-0.258,2.5538 1.4597,4.8882 3.9747,5.4015v7.152c-2.748,0.2088 -5.3573,1.2904 -7.447,3.087l-5.059,-5.059c1.416,-2.1409 0.9809,-5.0062 -1.0068,-6.6302 -1.9877,-1.624 -4.8822,-1.4792 -6.6979,0.3351 -1.8156,1.8143 -1.9625,4.7088 -0.3399,6.6976 1.6226,1.9888 4.4876,2.4259 6.6295,1.0115l5.059,5.06c-1.7964,2.0895 -2.878,4.6984 -3.087,7.446h-7.151c-0.5134,-2.515 -2.8477,-4.2327 -5.4015,-3.9747 -2.5538,0.258 -4.4975,2.4079 -4.4975,4.9747s1.9436,4.7167 4.4975,4.9747c2.5538,0.258 4.8882,-1.4597 5.4015,-3.9747h7.152c0.2088,2.748 1.2904,5.3573 3.087,7.447l-5.059,5.059c-2.1409,-1.416 -5.0062,-0.9809 -6.6302,1.0068 -1.624,1.9877 -1.4792,4.8822 0.3351,6.6979 1.8143,1.8156 4.7088,1.9625 6.6976,0.3399 1.9888,-1.6226 2.4259,-4.4876 1.0115,-6.6295l5.059,-5.059c2.0897,1.7966 4.699,2.8782 7.447,3.087v7.151c-2.515,0.5134 -4.2327,2.8477 -3.9747,5.4015 0.258,2.5538 2.4079,4.4975 4.9747,4.4975s4.7167,-1.9436 4.9747,-4.4975c0.258,-2.5538 -1.4597,-4.8882 -3.9747,-5.4015v-7.151c2.748,-0.2088 5.3573,-1.2904 7.447,-3.087l5.059,5.059c-1.416,2.1409 -0.9809,5.0062 1.0068,6.6302 1.9877,1.624 4.8822,1.4792 6.6979,-0.3351s1.9625,-4.7088 0.3399,-6.6976c-1.6226,-1.9888 -4.4876,-2.4259 -6.6295,-1.0115l-5.059,-5.06c1.7966,-2.0897 2.8782,-4.699 3.087,-7.447h7.151c0.5262,2.578 2.9603,4.307 5.5678,3.9551 2.6075,-0.352 4.4961,-2.6645 4.3199,-5.2897 -0.1761,-2.6252 -2.3566,-4.6648 -4.9878,-4.6653zM45.556,10.2c1.1716,-1.1714 3.071,-1.1713 4.2425,0.0002 1.1715,1.1716 1.1715,3.071 0,4.2425 -1.1715,1.1716 -3.0709,1.1717 -4.2425,0.0002 -0.5627,-0.5626 -0.8789,-1.3258 -0.8789,-2.1215s0.3161,-1.5589 0.8789,-2.1215zM27,5c0,-1.6569 1.3431,-3 3,-3s3,1.3431 3,3 -1.3431,3 -3,3 -3,-1.3431 -3,-3zM10.2,14.444c-1.1714,-1.1716 -1.1713,-3.071 0.0002,-4.2425 1.1716,-1.1715 3.071,-1.1715 4.2425,0 1.1716,1.1715 1.1717,3.0709 0.0002,4.2425 -0.5626,0.5627 -1.3258,0.8789 -2.1215,0.8789s-1.5589,-0.3161 -2.1215,-0.8789zM5,33c-1.6569,0 -3,-1.3431 -3,-3s1.3431,-3 3,-3 3,1.3431 3,3 -1.3431,3 -3,3zM14.444,49.8c-0.9598,0.961 -2.4456,1.1573 -3.622,0.4784s-1.75,-2.0634 -1.3983,-3.3753c0.3517,-1.3119 1.541,-2.2238 2.8993,-2.2231 1.2044,0.0177 2.2829,0.7498 2.7439,1.8626s0.2161,2.3932 -0.6229,3.2574zM33,55c0,1.6569 -1.3431,3 -3,3s-3,-1.3431 -3,-3 1.3431,-3 3,-3 3,1.3431 3,3zM49.8,45.556c0.5627,0.5626 0.8789,1.3258 0.8789,2.1215s-0.3161,1.5589 -0.8789,2.1215c-1.1872,1.1336 -3.0558,1.1336 -4.243,0 -0.7579,-0.7579 -1.0539,-1.8627 -0.7765,-2.898s1.0861,-1.8441 2.1215,-2.1215 2.1401,0.0186 2.898,0.7765zM30,41c-6.0751,0 -11,-4.9249 -11,-11s4.9249,-11 11,-11 11,4.9249 11,11c-0.0072,6.0722 -4.9278,10.9928 -11,11zM55,33c-1.6569,0 -3,-1.3431 -3,-3s1.3431,-3 3,-3 3,1.3431 3,3 -1.3431,3 -3,3z"/>
</vector>

View file

@ -1,12 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="430.23dp"
android:height="430.23dp"
android:viewportWidth="430.23"
android:viewportHeight="430.23">
<path
android:fillColor="#FF000000"
android:pathData="M217.875,159.668c-24.237,0 -43.886,19.648 -43.886,43.886c0,24.237 19.648,43.886 43.886,43.886c24.237,0 43.886,-19.648 43.886,-43.886C261.761,179.316 242.113,159.668 217.875,159.668zM217.875,226.541c-12.696,0 -22.988,-10.292 -22.988,-22.988c0,-12.696 10.292,-22.988 22.988,-22.988h0c12.696,0 22.988,10.292 22.988,22.988C240.863,216.249 230.571,226.541 217.875,226.541z"/>
<path
android:fillColor="#FF000000"
android:pathData="M392.896,59.357L107.639,26.966c-11.071,-1.574 -22.288,1.658 -30.824,8.882c-8.535,6.618 -14.006,16.428 -15.151,27.167l-5.224,42.841H40.243c-22.988,0 -40.229,20.375 -40.229,43.363V362.9c-0.579,21.921 16.722,40.162 38.644,40.741c0.528,0.014 1.057,0.017 1.585,0.01h286.824c22.988,0 43.886,-17.763 43.886,-40.751v-8.359c7.127,-1.377 13.888,-4.224 19.853,-8.359c8.465,-7.127 13.885,-17.22 15.151,-28.212l24.033,-212.114C432.44,82.815 415.905,62.088 392.896,59.357zM350.055,362.9c0,11.494 -11.494,19.853 -22.988,19.853H40.243c-10.383,0.305 -19.047,-7.865 -19.352,-18.248c-0.016,-0.535 -0.009,-1.07 0.021,-1.605v-38.661l80.98,-59.559c9.728,-7.469 23.43,-6.805 32.392,1.567l56.947,50.155c8.648,7.261 19.534,11.32 30.825,11.494c8.828,0.108 17.511,-2.243 25.078,-6.792l102.922,-59.559V362.9zM350.055,236.99l-113.894,66.351c-9.78,5.794 -22.159,4.745 -30.825,-2.612l-57.469,-50.678c-16.471,-14.153 -40.545,-15.021 -57.992,-2.09l-68.963,50.155V149.219c0,-11.494 7.837,-22.465 19.331,-22.465h286.824c12.28,0.509 22.197,10.201 22.988,22.465V236.99zM409.112,103.035c-0.007,0.069 -0.013,0.139 -0.021,0.208l-24.555,212.114c0.042,5.5 -2.466,10.709 -6.792,14.106c-2.09,2.09 -6.792,3.135 -6.792,4.18V149.219c-0.825,-23.801 -20.077,-42.824 -43.886,-43.363H77.337l4.702,-40.751c1.02,-5.277 3.779,-10.059 7.837,-13.584c4.582,-3.168 10.122,-4.645 15.674,-4.18l284.735,32.914C401.773,81.346 410.203,91.545 409.112,103.035z"/>
</vector>

View file

@ -1,18 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="512dp"
android:height="512dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="m17.631,2.782c0.034,1.32 0.952,2.631 2.685,2.631 1.621,0 2.691,-1.216 2.691,-2.706 0,-1.345 -0.925,-2.707 -2.692,-2.707 -0.958,0 -1.836,0.428 -2.335,1.321l-4.297,-1.289c-0.414,-0.123 -0.835,0.123 -0.941,0.527l-1.923,7.31c-2.236,0.16 -4.278,0.777 -5.951,1.709 -2.77,-2.595 -6.557,1.633 -4.091,4.562 -1.774,5.542 4.594,9.86 11.223,9.86 6.681,0 12.974,-4.39 11.223,-9.86 2.458,-2.919 -1.301,-7.154 -4.095,-4.564 -1.87,-1.04 -4.206,-1.678 -6.75,-1.736l1.617,-6.148zM20.315,1.5c0.879,0 1.191,0.65 1.191,1.208 0,0.667 -0.409,1.206 -1.191,1.206 -0.88,0 -1.191,-0.65 -1.191,-1.208 0,-0.674 0.412,-1.206 1.191,-1.206zM3.531,10.455c-0.793,0.607 -1.455,1.297 -1.957,2.052 -0.38,-1.412 0.839,-2.632 1.957,-2.052zM12,22.5c-8.943,0 -13.396,-7.182 -6.982,-11.298 0.422,-0.194 2.664,-1.876 6.982,-1.876 3.756,0 5.474,1.184 6.98,1.875 6.39,4.099 2.018,11.299 -6.98,11.299zM22.426,12.508c-0.502,-0.756 -1.164,-1.446 -1.958,-2.053 1.141,-0.589 2.335,0.654 1.958,2.053z"/>
<path
android:fillColor="#FF000000"
android:pathData="m10.305,14.935c0,-1.321 -0.998,-2.206 -2.217,-2.206 -1.076,0 -2.219,0.773 -2.219,2.206 0,1.32 0.996,2.206 2.217,2.206 1.076,0 2.219,-0.773 2.219,-2.206zM7.369,14.935c0,-0.655 0.55,-0.706 0.719,-0.706 0.403,0 0.717,0.229 0.717,0.706 0,0.655 -0.55,0.706 -0.719,0.706 -0.168,0 -0.717,-0.051 -0.717,-0.706z"/>
<path
android:fillColor="#FF000000"
android:pathData="m15.914,12.729c-1.076,0 -2.219,0.773 -2.219,2.206 0,1.32 0.996,2.206 2.217,2.206 1.076,0 2.219,-0.773 2.219,-2.206 0,-1.321 -0.998,-2.206 -2.217,-2.206zM15.912,15.641c-0.168,0 -0.717,-0.051 -0.717,-0.706s0.55,-0.706 0.719,-0.706c0.403,0 0.717,0.229 0.717,0.706 0,0.655 -0.55,0.706 -0.719,0.706z"/>
<path
android:fillColor="#FF000000"
android:pathData="m15.297,18.42c-1.106,1.517 -5.454,1.536 -6.593,0.001 -0.56,-0.812 -1.786,0.023 -1.241,0.842 1.591,2.402 7.483,2.403 9.074,0 0.536,-0.803 -0.667,-1.64 -1.24,-0.843z"/>
</vector>

View file

@ -1,34 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@id/bottomNavigationView"
app:layout_constraintTop_toTopOf="parent">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/mainNavHostFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/main_nav_graph" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNavigationView"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:background="@color/white"
app:menu="@menu/bottom_navigation_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>

View file

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:layout_scrollFlags="scroll|enterAlways"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/postRecyclerView"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray70"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:visibility="gone"
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View file

@ -1,46 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/post_horizontal_margin"
android:layout_marginTop="@dimen/post_horizontal_margin_half"
android:layout_marginRight="@dimen/post_horizontal_margin"
android:layout_marginBottom="@dimen/post_horizontal_margin_half"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="7dp"
card_view:cardUseCompatPadding="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:id="@+id/topSpacer"
android:layout_width="match_parent"
android:layout_height="@dimen/post_horizontal_margin" />
<ImageView
android:id="@+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:adjustViewBounds="true"
android:scaleType="fitStart" />
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/post_horizontal_margin_half"
android:layout_marginRight="@dimen/post_horizontal_margin_half"
android:gravity="center"
android:padding="10dp"
android:textColor="@android:color/black"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>

View file

@ -1,64 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:title="@string/toolbar_title" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/subredditInput"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="@+id/fetchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fetch_subreddit" />
</LinearLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/pullToRefresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/postRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray70"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email"
android:visibility="gone" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View file

@ -1,45 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/get_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="get1" />
<Button
android:id="@+id/fresh_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="fresh1" />
<TextView
android:id="@+id/stream_1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/get_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="get2" />
<Button
android:id="@+id/fresh_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="fresh2" />
<TextView
android:id="@+id/stream_2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/stream"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

View file

@ -1,15 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/redditFragment"
android:icon="@drawable/ic_reddit"
android:title="@string/bottom_navigation_menu_title_reddit" />
<item
android:id="@+id/roomFragment"
android:icon="@drawable/ic_photo"
android:title="@string/bottom_navigation_menu_title_room" />
<item
android:id="@+id/streamFragment"
android:icon="@drawable/ic_distribution"
android:title="@string/bottom_navigation_menu_title_stream" />
</menu>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

View file

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_nav_graph"
app:startDestination="@id/redditFragment">
<fragment
android:id="@+id/redditFragment"
android:name="com.dropbox.android.sample.ui.reddit.RedditFragment"
android:label="RedditFragment" />
<fragment
android:id="@+id/roomFragment"
android:name="com.dropbox.android.sample.ui.room.RoomFragment"
android:label="RoomFragment" />
<fragment
android:id="@+id/streamFragment"
android:name="com.dropbox.android.sample.ui.stream.StreamFragment"
android:label="StreamFragment" />
</navigation>

View file

@ -1,46 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="primary">#222222</color>
<color name="primary_dark">#000000</color>
<color name="accent">#FFFFFF</color>
<color name="gray">#ffdfdfdf</color>
<color name="transparent">@android:color/transparent</color>
<color name="black">#000</color>
<color name="black_10_percent">#1A000000</color>
<color name="black_15_percent">#26000000</color>
<color name="black_40_percent">#66000000</color>
<color name="black_50_percent">#80000000</color>
<color name="black_75_percent">#BF000000</color>
<color name="black_80_percent">#CC000000</color>
<color name="black_85_percent">#CF000000</color>
<color name="black_90_percent">#E6000000</color>
<color name="gray10">#1a1a1a</color>
<color name="gray10_90">#E61a1a1a</color>
<color name="gray15">#222</color>
<color name="gray15_85">#CF222222</color>
<color name="gray20">#333</color>
<color name="gray25">#505050</color>
<color name="gray30">#666</color>
<color name="gray35">#808080</color>
<color name="gray40">#999</color>
<color name="gray45">#b3b3b3</color>
<color name="gray50">#ccc</color>
<color name="gray60">#e3e3e3</color>
<color name="gray70">#ebebeb</color>
<color name="gray80">#f3f3f3</color>
<color name="gray90">#f7f7f7</color>
<color name="gray95">#fafafa</color>
<color name="gray100">#a5a5a5</color>
<color name="gray246">#f6f6f6</color>
<color name="grey240">#cccccc</color>
<color name="white">#fff</color>
<color name="white50">#80ffffff</color>
</resources>

View file

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="horizontal_margin">16dp</dimen>
<dimen name="vertical_margin">16dp</dimen>
<dimen name="text_headline">24sp</dimen>
<dimen name="text_large_title">22sp</dimen>
<dimen name="text_title">20sp</dimen>
<dimen name="text_large_body">18sp</dimen>
<dimen name="text_body">16sp</dimen>
<dimen name="text_small_body">14sp</dimen>
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="fab_margin">16dp</dimen>
<dimen name="post_horizontal_margin">15dp</dimen>
<dimen name="post_horizontal_margin_half">5dp</dimen>
</resources>

View file

@ -1,8 +0,0 @@
<resources>
<string name="app_name">Sample</string>
<string name="fetch_subreddit">Read</string>
<string name="toolbar_title">Sample</string>
<string name="bottom_navigation_menu_title_reddit">Reddit</string>
<string name="bottom_navigation_menu_title_stream">Stream</string>
<string name="bottom_navigation_menu_title_room">Room</string>
</resources>

View file

@ -1,17 +0,0 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
</resources>

View file

@ -1 +0,0 @@
version=0.1

View file

@ -1,60 +0,0 @@
buildscript {
repositories {
mavenCentral()
gradlePluginPortal()
google()
}
apply from: 'buildsystem/dependencies.gradle'
dependencies {
classpath "com.android.tools.build:gradle:${versions.androidGradlePlugin}"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}"
classpath "org.jetbrains.kotlin:kotlin-serialization:${versions.kotlin}"
classpath "org.jetbrains.kotlinx:binary-compatibility-validator:${versions.binaryCompatibilityValidator}"
classpath "org.jetbrains.dokka:dokka-gradle-plugin:${versions.dokkaGradlePlugin}"
classpath "org.jlleitschuh.gradle:ktlint-gradle:${versions.ktlintGradle}"
classpath "com.diffplug.spotless:spotless-plugin-gradle:${versions.spotlessGradlePlugin}"
classpath "org.jacoco:org.jacoco.core:${versions.jacocoGradlePlugin}"
classpath "org.jetbrains.kotlinx:atomicfu-gradle-plugin:${versions.atomicFuPlugin}"
classpath "com.vanniktech:gradle-maven-publish-plugin:${versions.mavenPublishPlugin}"
}
}
apply from: 'buildsystem/dependencies.gradle'
apply plugin: 'binary-compatibility-validator'
apiValidation {
ignoredProjects += ["app"]
}
allprojects {
repositories {
mavenCentral()
google()
jcenter()
}
apply plugin: 'org.jlleitschuh.gradle.ktlint'
ktlint {
version = versions.ktlint
disabledRules = ["import-ordering"]
}
// Workaround to prevent Gradle from stealing focus from other apps during tests run/etc.
// https://gist.github.com/artem-zinnatullin/4c250e04636e25797165
tasks.withType(JavaForkOptions) {
jvmArgs '-Djava.awt.headless=true'
}
}
subprojects {
apply plugin: 'com.diffplug.spotless'
spotless {
kotlin {
target 'src/**/*.kt'
}
}
}

62
build.gradle.kts Normal file
View file

@ -0,0 +1,62 @@
plugins {
id("org.jlleitschuh.gradle.ktlint") version "11.0.0"
id("com.diffplug.spotless") version "6.4.1"
}
buildscript {
repositories {
mavenCentral()
gradlePluginPortal()
google()
}
dependencies {
classpath("com.android.tools.build:gradle:${Version.androidGradlePlugin}")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${Version.baseKotlin}")
classpath("org.jetbrains.kotlin:kotlin-serialization:${Version.baseKotlin}")
classpath("org.jetbrains.dokka:dokka-gradle-plugin:${Version.dokkaGradlePlugin}")
classpath("org.jlleitschuh.gradle:ktlint-gradle:${Version.ktlintGradle}")
classpath("com.diffplug.spotless:spotless-plugin-gradle:${Version.spotlessPluginGradle}")
classpath("org.jacoco:org.jacoco.core:${Version.jacocoGradlePlugin}")
classpath("com.vanniktech:gradle-maven-publish-plugin:${Version.mavenPublishPlugin}")
classpath("org.jetbrains.kotlinx:kover:${Version.kover}")
classpath("com.squareup.anvil:gradle-plugin:${Version.anvilGradlePlugin}")
classpath("com.squareup.sqldelight:gradle-plugin:${Version.sqlDelightGradlePlugin}")
classpath("org.jetbrains.kotlinx:atomicfu-gradle-plugin:${Version.atomicFuGradlePlugin}")
}
}
allprojects {
repositories {
mavenCentral()
google()
}
}
subprojects {
apply(plugin = "org.jlleitschuh.gradle.ktlint")
apply(plugin = "com.diffplug.spotless")
ktlint {
disabledRules.add("import-ordering")
}
spotless {
kotlin {
target("src/**/*.kt")
}
}
}
tasks {
withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
jvmTarget = "11"
}
}
withType<JavaCompile>().configureEach {
sourceCompatibility = JavaVersion.VERSION_11.name
targetCompatibility = JavaVersion.VERSION_11.name
}
}

View file

@ -0,0 +1,7 @@
plugins {
`kotlin-dsl`
}
repositories {
mavenCentral()
}

View file

@ -0,0 +1,64 @@
object Deps {
object Androidx {
const val lifecycleRuntimeKtx = "androidx.lifecycle:lifecycle-runtime-ktx:${Version.lifecycleRuntimeKtx}"
const val lifecycleViewmodelKtx = "androidx.lifecycle:lifecycle-viewmodel-ktx:${Version.lifecycleViewmodelKtx}"
const val activityCompose = "androidx.activity:activity-compose:${Version.activityCompose}"
const val appCompat = "androidx.appcompat:appcompat:1.4.1"
const val coreKtx = "androidx.core:core-ktx:1.7.0"
const val navigationCompose = "androidx.navigation:navigation-compose:${Version.navigationCompose}"
}
object Coil {
const val compose = "io.coil-kt:coil-compose:2.2.2"
}
object Compose {
const val compiler = "androidx.compose.compiler:compiler:${Version.composeCompiler}"
const val runtime = "androidx.compose.runtime:runtime:${Version.composeAndroidX}"
const val ui = "androidx.compose.ui:ui:${Version.composeAndroidX}"
const val uiGraphics = "androidx.compose.ui:ui-graphics:${Version.composeAndroidX}"
const val uiTooling = "androidx.compose.ui:ui-tooling:${Version.composeAndroidX}"
const val foundationLayout = "androidx.compose.foundation:foundation-layout:${Version.composeAndroidX}"
const val material = "androidx.compose.material:material:${Version.composeAndroidX}"
}
object Dagger {
const val dagger = "com.google.dagger:dagger:${Version.dagger}"
const val daggerCompiler = "com.google.dagger:dagger-compiler:${Version.dagger}"
}
object Kotlin {
const val gradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Version.baseKotlin}"
}
object Kotlinx {
const val stdLib = "org.jetbrains.kotlin:kotlin-stdlib:${Version.baseKotlin}"
const val serializationCore = "org.jetbrains.kotlinx:kotlinx-serialization-core:${Version.kotlinxSerialization}"
const val serializationJson = "org.jetbrains.kotlinx:kotlinx-serialization-json:${Version.kotlinxSerialization}"
const val coroutinesAndroid = "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Version.kotlinxCoroutines}"
const val coroutinesCore = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Version.kotlinxCoroutines}"
const val dateTime = "org.jetbrains.kotlinx:kotlinx-datetime:0.4.0"
}
object Ktor {
const val clientCore = "io.ktor:ktor-client-core:${Version.ktor}"
const val clientCio = "io.ktor:ktor-client-cio:${Version.ktor}"
}
object SqlDelight {
const val gradlePlugin = "com.squareup.sqldelight:gradle-plugin:${Version.sqlDelight}"
const val driverAndroid = "com.squareup.sqldelight:android-driver:${Version.sqlDelight}"
const val driverNative = "com.squareup.sqldelight:native-driver:${Version.sqlDelight}"
const val driverSqlite = "com.squareup.sqldelight:sqlite-driver:${Version.sqlDelight}"
const val runtime = "com.squareup.sqldelight:runtime:${Version.sqlDelight}"
const val coroutineExtensions = "com.squareup.sqldelight:coroutines-extensions:${Version.sqlDelight}"
const val driverNativeMacOS = "com.squareup.sqldelight:native-driver-macosx64:${Version.sqlDelight}"
}
object Test {
const val core = "androidx.test:core:${Version.testCore}"
const val coroutinesTest = "org.jetbrains.kotlinx:kotlinx-coroutines-test:${Version.kotlinxCoroutines}"
const val junit = "junit:junit:${Version.junit}"
}
}

View file

@ -0,0 +1,35 @@
object Version {
const val activityCompose = "1.4.0-beta01"
const val androidMinSdk = 24
const val androidCompileSdk = 33
const val androidGradlePlugin = "7.2.2"
const val androidTargetSdk = androidCompileSdk
const val anvilGradlePlugin = "2.4.2"
const val atomicFuGradlePlugin = "0.18.5"
const val baseKotlin = "1.7.21"
const val binaryCompatibilityValidator = "0.12.1"
const val composeAndroidX = "1.3.0-beta02"
const val composeJetbrains = "1.2.0-alpha01-dev755"
const val composeCompiler = "1.4.0-alpha02"
const val dagger = "2.44"
const val dokkaGradlePlugin = "1.6.0"
const val ktlintGradle = "10.2.1"
const val ktor = "2.1.1"
const val lifecycleKtx = "2.4.0-rc01"
const val lifecycleRuntimeKtx = lifecycleKtx
const val lifecycleViewmodelKtx = lifecycleKtx
const val jacocoGradlePlugin = "0.8.7"
const val mavenPublishPlugin = "0.22.0"
const val spotlessPluginGradle = "6.4.1"
const val junit = "4.13.2"
const val kotlinxCoroutines = "1.6.4"
const val kotlinxSerialization = "1.4.0"
const val testCore = "1.4.0"
const val kmmBridge = "0.3.2"
const val ktlint = "0.39.0"
const val kover = "0.6.0"
const val navigationCompose = "2.5.2"
const val sqlDelight = "1.5.4"
const val sqlDelightGradlePlugin = sqlDelight
const val store = "5.0.0-alpha03"
}

View file

@ -1,99 +0,0 @@
ext.versions = [
minSdk : 16,
targetSdk : 29,
compileSdk : 31,
buildTools : '30.0.3',
kotlin : '1.6.20',
ktlint : '0.39.0',
// Plugins
androidGradlePlugin : '7.2.2',
dokkaGradlePlugin : '1.6.0',
ktlintGradle : '10.2.1',
spotlessGradlePlugin : '6.4.1',
jacocoGradlePlugin : '0.8.7',
binaryCompatibilityValidator: '0.4.0',
atomicFuPlugin : '0.15.1',
mavenPublishPlugin : "0.22.0",
cache : '3.1.1',
store : '4.0.7',
// UI libs.
picasso : '2.5.2',
// Others.
appCompat : '1.3.1',
constraintLayout : '2.1.3',
coreKtx : '1.6.0',
coroutines : '1.5.2',
fragment : '1.3.6',
jsr305 : '3.0.2',
kotlinSerialization : '1.3.2',
leakcanary : '2.8.1',
lifecycle : '2.2.0',
material : '1.6.0',
navigation : '2.3.5',
okHttp : '4.9.3',
okio : '3.0.0',
recyclerView : '1.2.1',
retrofit : '2.9.0',
retrofitSerializerConverter : '0.8.0',
room : '2.4.2',
rx2 : '2.2.21',
rx3 : '3.1.3',
swipeRefreshLayout : '1.1.0',
// Testing.
junit : '4.13.2',
truth : '1.1.3',
mockito : '4.4.0',
mockitoKotlin : '2.2.0',
]
ext.libraries = [
store : "org.mobilenativefoundation.store:store4:$versions.store",
filesystem : "org.mobilenativefoundation.store:filesystem4:$versions.store",
// depend on cache via jar to avoid building java code
cache : "com.nytimes.android:cache3:$versions.cache",
// UI libs.
constraintLayout : "androidx.constraintlayout:constraintlayout:$versions.constraintLayout",
appCompat : "androidx.appcompat:appcompat:${versions.appCompat}",
lifecycle : "androidx.lifecycle:lifecycle-runtime-ktx:$versions.lifecycle",
lifecycleExtensions : "androidx.lifecycle:lifecycle-extensions:$versions.lifecycle",
navigationFragment : "androidx.navigation:navigation-fragment-ktx:$versions.navigation",
navigationUi : "androidx.navigation:navigation-ui-ktx:$versions.navigation",
material : "com.google.android.material:material:${versions.material}",
recyclerView : "androidx.recyclerview:recyclerview:${versions.recyclerView}",
swipeRefreshLayout : "androidx.swiperefreshlayout:swiperefreshlayout:${versions.swipeRefreshLayout}",
fragment : "androidx.fragment:fragment-ktx:${versions.fragment}",
picasso : "com.squareup.picasso:picasso:$versions.picasso",
// Others.
coreKtx : "androidx.core:core-ktx:$versions.coreKtx",
jsr305 : "com.google.code.findbugs:jsr305:$versions.jsr305",
kotlinSerialization : "org.jetbrains.kotlinx:kotlinx-serialization-json:$versions.kotlinSerialization",
leakcanary : "com.squareup.leakcanary:leakcanary-android:$versions.leakcanary",
okHttp : "com.squareup.okhttp3:okhttp:$versions.okHttp",
okio : "com.squareup.okio:okio:$versions.okio",
retrofit : "com.squareup.retrofit2:retrofit:$versions.retrofit",
retrofitSerializerConverter: "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:$versions.retrofitSerializerConverter",
roomCompiler : "androidx.room:room-compiler:$versions.room",
roomRuntime : "androidx.room:room-ktx:$versions.room",
rx2 : "io.reactivex.rxjava2:rxjava:$versions.rx2",
rx3 : "io.reactivex.rxjava3:rxjava:$versions.rx3",
// Testing.
junit : "junit:junit:$versions.junit",
truth : "com.google.truth:truth:$versions.truth",
mockito : "org.mockito:mockito-core:$versions.mockito",
mockitoKotlin : "com.nhaarman.mockitokotlin2:mockito-kotlin:$versions.mockitoKotlin",
coroutinesCore : "org.jetbrains.kotlinx:kotlinx-coroutines-core:$versions.coroutines",
coroutinesRx2 : "org.jetbrains.kotlinx:kotlinx-coroutines-rx2:$versions.coroutines",
coroutinesRx3 : "org.jetbrains.kotlinx:kotlinx-coroutines-rx3:$versions.coroutines",
coroutinesReactive : "org.jetbrains.kotlinx:kotlinx-coroutines-reactive:$versions.coroutines",
coroutinesAndroid : "org.jetbrains.kotlinx:kotlinx-coroutines-android:$versions.coroutines",
coroutinesTest : "org.jetbrains.kotlinx:kotlinx-coroutines-test:$versions.coroutines",
kotlinTest : "org.jetbrains.kotlin:kotlin-test:$versions.kotlin",
kotlinTestJunit : "org.jetbrains.kotlin:kotlin-test-junit:$versions.kotlin",
]

1
cache/.gitignore vendored
View file

@ -1 +0,0 @@
/build

60
cache/README.md vendored
View file

@ -1,38 +1,48 @@
Cache
===================
# Cache
Store depends on a subset of Guava, we have extracted these parts into a shaded Cache artifact.
Feel free to use Cache anytime you need an in memory cache implementation optimized for Android.
Store depends on a subset of [Guava](https://github.com/google/guava).
This is a shaded artifact that is Kotlin Multiplatform compatible.
## Usage
To use, first build a cache instance.
```java
memCache = CacheBuilder.newBuilder()
.maximumSize(getCacheSize())
.expireAfterAccess(getCacheTTL(), TimeUnit.SECONDS)
.build();
```kotlin
implementation("org.mobilenativefoundation.store:cache:${STORE_VERSION}")
```
You can then use your cache as regular cache or one that knows how to load itself (with blocking) when empty
```java
memCache.get(key, new Callable<T>() {
@Override
public Observable<T> call() throws Exception {
return getCachedValue(key);
}
});
## Implementation
### Model the key
```kotlin
data class Key(
val id: String
)
```
Please refer to Guava's Cache documentation for additional features/configurations
### Model the value
```kotlin
data class Post(
val title: String
)
```
### Build the cache
```kotlin
val cache = CacheBuilder<Key, Post>()
.maximumSize(100)
.expireAfterWrite(1.day)
.build()
```
## See Also
https://github.com/google/guava/wiki/CachesExplained
```groovy
implementation "org.mobilenativefoundation.store:store4:${store_version}"
```
Please refer to the [Store Readme](https://github.com/dropbox/Store/blob/main/README.md#latest-version) for the latest version.
## License
```
```text
Copyright (c) 2017 The New York Times Company
Copyright (c) 2010 The Guava Authors

238
cache/api/cache.api vendored
View file

@ -1,238 +0,0 @@
public abstract class com/dropbox/android/external/cache3/AbstractFuture : com/dropbox/android/external/cache3/ListenableFuture {
protected fun <init> ()V
public fun addListener (Ljava/lang/Runnable;Ljava/util/concurrent/Executor;)V
public fun cancel (Z)Z
public fun get ()Ljava/lang/Object;
public fun get (JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;
protected fun interruptTask ()V
public fun isCancelled ()Z
public fun isDone ()Z
protected fun set (Ljava/lang/Object;)Z
protected fun setException (Ljava/lang/Throwable;)Z
protected fun setFuture (Lcom/dropbox/android/external/cache3/ListenableFuture;)Z
protected final fun wasInterrupted ()Z
}
public abstract class com/dropbox/android/external/cache3/AbstractFuture$TrustedFuture : com/dropbox/android/external/cache3/AbstractFuture {
public fun <init> ()V
public final fun addListener (Ljava/lang/Runnable;Ljava/util/concurrent/Executor;)V
public final fun get ()Ljava/lang/Object;
public final fun get (JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;
public final fun isCancelled ()Z
public final fun isDone ()Z
}
public abstract class com/dropbox/android/external/cache3/AbstractSequentialIterator : com/dropbox/android/external/cache3/UnmodifiableIterator {
protected fun <init> (Ljava/lang/Object;)V
protected abstract fun computeNext (Ljava/lang/Object;)Ljava/lang/Object;
public final fun hasNext ()Z
public final fun next ()Ljava/lang/Object;
}
public final class com/dropbox/android/external/cache3/Ascii {
public static fun isUpperCase (C)Z
public static fun toLowerCase (Ljava/lang/String;)Ljava/lang/String;
}
public abstract interface class com/dropbox/android/external/cache3/Cache {
public abstract fun asMap ()Ljava/util/concurrent/ConcurrentMap;
public abstract fun cleanUp ()V
public abstract fun get (Ljava/lang/Object;Ljava/util/concurrent/Callable;)Ljava/lang/Object;
public abstract fun getAllPresent (Ljava/lang/Iterable;)Ljava/util/Map;
public abstract fun getIfPresent (Ljava/lang/Object;)Ljava/lang/Object;
public abstract fun invalidate (Ljava/lang/Object;)V
public abstract fun invalidateAll ()V
public abstract fun invalidateAll (Ljava/lang/Iterable;)V
public abstract fun put (Ljava/lang/Object;Ljava/lang/Object;)V
public abstract fun putAll (Ljava/util/Map;)V
public abstract fun size ()J
}
public final class com/dropbox/android/external/cache3/CacheBuilder {
public fun build ()Lcom/dropbox/android/external/cache3/Cache;
public fun build (Lcom/dropbox/android/external/cache3/CacheLoader;)Lcom/dropbox/android/external/cache3/LoadingCache;
public fun concurrencyLevel (I)Lcom/dropbox/android/external/cache3/CacheBuilder;
public fun expireAfterAccess (JLjava/util/concurrent/TimeUnit;)Lcom/dropbox/android/external/cache3/CacheBuilder;
public fun expireAfterWrite (JLjava/util/concurrent/TimeUnit;)Lcom/dropbox/android/external/cache3/CacheBuilder;
public fun maximumSize (J)Lcom/dropbox/android/external/cache3/CacheBuilder;
public fun maximumWeight (J)Lcom/dropbox/android/external/cache3/CacheBuilder;
public static fun newBuilder ()Lcom/dropbox/android/external/cache3/CacheBuilder;
public fun removalListener (Lcom/dropbox/android/external/cache3/RemovalListener;)Lcom/dropbox/android/external/cache3/CacheBuilder;
public fun ticker (Lcom/dropbox/android/external/cache3/Ticker;)Lcom/dropbox/android/external/cache3/CacheBuilder;
public fun toString ()Ljava/lang/String;
public fun weigher (Lcom/dropbox/android/external/cache3/Weigher;)Lcom/dropbox/android/external/cache3/CacheBuilder;
}
public abstract class com/dropbox/android/external/cache3/CacheLoader {
protected fun <init> ()V
public static fun from (Lcom/dropbox/android/external/cache3/Function;)Lcom/dropbox/android/external/cache3/CacheLoader;
public static fun from (Lcom/dropbox/android/external/cache3/Supplier;)Lcom/dropbox/android/external/cache3/CacheLoader;
public abstract fun load (Ljava/lang/Object;)Ljava/lang/Object;
public fun loadAll (Ljava/lang/Iterable;)Ljava/util/Map;
public fun reload (Ljava/lang/Object;Ljava/lang/Object;)Lcom/dropbox/android/external/cache3/ListenableFuture;
}
public final class com/dropbox/android/external/cache3/CacheLoader$InvalidCacheLoadException : java/lang/RuntimeException {
public fun <init> (Ljava/lang/String;)V
}
public final class com/dropbox/android/external/cache3/CacheLoader$UnsupportedLoadingOperationException : java/lang/UnsupportedOperationException {
}
public abstract class com/dropbox/android/external/cache3/Equivalence {
protected fun <init> ()V
protected abstract fun doEquivalent (Ljava/lang/Object;Ljava/lang/Object;)Z
protected abstract fun doHash (Ljava/lang/Object;)I
public static fun equals ()Lcom/dropbox/android/external/cache3/Equivalence;
public final fun equivalent (Ljava/lang/Object;Ljava/lang/Object;)Z
public final fun hash (Ljava/lang/Object;)I
public static fun identity ()Lcom/dropbox/android/external/cache3/Equivalence;
}
public class com/dropbox/android/external/cache3/ExecutionError : java/lang/Error {
public fun <init> (Ljava/lang/Error;)V
}
public abstract class com/dropbox/android/external/cache3/ForwardingCache : com/dropbox/android/external/cache3/ForwardingObject, com/dropbox/android/external/cache3/Cache {
protected fun <init> ()V
public fun asMap ()Ljava/util/concurrent/ConcurrentMap;
public fun cleanUp ()V
protected abstract fun delegate ()Lcom/dropbox/android/external/cache3/Cache;
protected synthetic fun delegate ()Ljava/lang/Object;
public fun get (Ljava/lang/Object;Ljava/util/concurrent/Callable;)Ljava/lang/Object;
public fun getAllPresent (Ljava/lang/Iterable;)Ljava/util/Map;
public fun getIfPresent (Ljava/lang/Object;)Ljava/lang/Object;
public fun invalidate (Ljava/lang/Object;)V
public fun invalidateAll ()V
public fun invalidateAll (Ljava/lang/Iterable;)V
public fun put (Ljava/lang/Object;Ljava/lang/Object;)V
public fun putAll (Ljava/util/Map;)V
public fun size ()J
}
public abstract class com/dropbox/android/external/cache3/ForwardingObject {
protected fun <init> ()V
protected abstract fun delegate ()Ljava/lang/Object;
public fun toString ()Ljava/lang/String;
}
public abstract interface class com/dropbox/android/external/cache3/Function {
public abstract fun apply (Ljava/lang/Object;)Ljava/lang/Object;
public abstract fun equals (Ljava/lang/Object;)Z
}
public final class com/dropbox/android/external/cache3/Futures {
public static fun getChecked (Ljava/util/concurrent/Future;Ljava/lang/Class;)Ljava/lang/Object;
public static fun getChecked (Ljava/util/concurrent/Future;Ljava/lang/Class;JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;
public static fun immediateFailedFuture (Ljava/lang/Throwable;)Lcom/dropbox/android/external/cache3/ListenableFuture;
public static fun immediateFuture (Ljava/lang/Object;)Lcom/dropbox/android/external/cache3/ListenableFuture;
public static fun transform (Lcom/dropbox/android/external/cache3/ListenableFuture;Lcom/dropbox/android/external/cache3/Function;)Lcom/dropbox/android/external/cache3/ListenableFuture;
}
public abstract interface class com/dropbox/android/external/cache3/ListenableFuture : java/util/concurrent/Future {
public abstract fun addListener (Ljava/lang/Runnable;Ljava/util/concurrent/Executor;)V
}
public abstract interface class com/dropbox/android/external/cache3/LoadingCache : com/dropbox/android/external/cache3/Cache, com/dropbox/android/external/cache3/Function {
public abstract fun apply (Ljava/lang/Object;)Ljava/lang/Object;
public abstract fun asMap ()Ljava/util/concurrent/ConcurrentMap;
public abstract fun get (Ljava/lang/Object;)Ljava/lang/Object;
public abstract fun getAll (Ljava/lang/Iterable;)Ljava/util/Map;
public abstract fun getUnchecked (Ljava/lang/Object;)Ljava/lang/Object;
public abstract fun refresh (Ljava/lang/Object;)V
}
public final class com/dropbox/android/external/cache3/MoreObjects {
public static fun firstNonNull (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
public static fun toStringHelper (Ljava/lang/Object;)Lcom/dropbox/android/external/cache3/MoreObjects$ToStringHelper;
}
public final class com/dropbox/android/external/cache3/MoreObjects$ToStringHelper {
public fun add (Ljava/lang/String;I)Lcom/dropbox/android/external/cache3/MoreObjects$ToStringHelper;
public fun add (Ljava/lang/String;J)Lcom/dropbox/android/external/cache3/MoreObjects$ToStringHelper;
public fun add (Ljava/lang/String;Ljava/lang/Object;)Lcom/dropbox/android/external/cache3/MoreObjects$ToStringHelper;
public fun addValue (Ljava/lang/Object;)Lcom/dropbox/android/external/cache3/MoreObjects$ToStringHelper;
public fun toString ()Ljava/lang/String;
}
public final class com/dropbox/android/external/cache3/Objects {
public static fun equal (Ljava/lang/Object;Ljava/lang/Object;)Z
}
public final class com/dropbox/android/external/cache3/Preconditions {
public static fun checkArgument (Z)V
public static fun checkArgument (ZLjava/lang/Object;)V
public static fun checkArgument (ZLjava/lang/String;[Ljava/lang/Object;)V
public static fun checkNotNull (Ljava/lang/Object;)Ljava/lang/Object;
public static fun checkNotNull (Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;
public static fun checkState (Z)V
public static fun checkState (ZLjava/lang/Object;)V
public static fun checkState (ZLjava/lang/String;[Ljava/lang/Object;)V
}
public abstract class com/dropbox/android/external/cache3/RemovalCause : java/lang/Enum {
public static final field COLLECTED Lcom/dropbox/android/external/cache3/RemovalCause;
public static final field EXPIRED Lcom/dropbox/android/external/cache3/RemovalCause;
public static final field EXPLICIT Lcom/dropbox/android/external/cache3/RemovalCause;
public static final field REPLACED Lcom/dropbox/android/external/cache3/RemovalCause;
public static final field SIZE Lcom/dropbox/android/external/cache3/RemovalCause;
public static fun valueOf (Ljava/lang/String;)Lcom/dropbox/android/external/cache3/RemovalCause;
public static fun values ()[Lcom/dropbox/android/external/cache3/RemovalCause;
}
public abstract interface class com/dropbox/android/external/cache3/RemovalListener {
public abstract fun onRemoval (Lcom/dropbox/android/external/cache3/RemovalNotification;)V
}
public final class com/dropbox/android/external/cache3/RemovalNotification : java/util/Map$Entry {
public static fun create (Ljava/lang/Object;Ljava/lang/Object;Lcom/dropbox/android/external/cache3/RemovalCause;)Lcom/dropbox/android/external/cache3/RemovalNotification;
public fun equals (Ljava/lang/Object;)Z
public fun getKey ()Ljava/lang/Object;
public fun getValue ()Ljava/lang/Object;
public fun hashCode ()I
public final fun setValue (Ljava/lang/Object;)Ljava/lang/Object;
public fun toString ()Ljava/lang/String;
}
public final class com/dropbox/android/external/cache3/SettableFuture : com/dropbox/android/external/cache3/AbstractFuture$TrustedFuture {
public static fun create ()Lcom/dropbox/android/external/cache3/SettableFuture;
public fun set (Ljava/lang/Object;)Z
public fun setException (Ljava/lang/Throwable;)Z
public fun setFuture (Lcom/dropbox/android/external/cache3/ListenableFuture;)Z
}
public final class com/dropbox/android/external/cache3/Stopwatch {
public static fun createStarted ()Lcom/dropbox/android/external/cache3/Stopwatch;
public static fun createUnstarted ()Lcom/dropbox/android/external/cache3/Stopwatch;
public fun start ()Lcom/dropbox/android/external/cache3/Stopwatch;
public fun stop ()Lcom/dropbox/android/external/cache3/Stopwatch;
public fun toString ()Ljava/lang/String;
}
public abstract interface class com/dropbox/android/external/cache3/Supplier {
public abstract fun get ()Ljava/lang/Object;
}
public abstract class com/dropbox/android/external/cache3/Ticker {
protected fun <init> ()V
public abstract fun read ()J
public static fun systemTicker ()Lcom/dropbox/android/external/cache3/Ticker;
}
public class com/dropbox/android/external/cache3/UncheckedExecutionException : java/lang/RuntimeException {
public fun <init> (Ljava/lang/Throwable;)V
}
public final class com/dropbox/android/external/cache3/Uninterruptibles {
public static fun getUninterruptibly (Ljava/util/concurrent/Future;)Ljava/lang/Object;
}
public abstract class com/dropbox/android/external/cache3/UnmodifiableIterator : java/util/Iterator {
protected fun <init> ()V
public final fun remove ()V
}
public abstract interface class com/dropbox/android/external/cache3/Weigher {
public abstract fun weigh (Ljava/lang/Object;Ljava/lang/Object;)I
}

43
cache/build.gradle vendored
View file

@ -1,43 +0,0 @@
import com.vanniktech.maven.publish.SonatypeHost
buildscript {
tasks.withType(JavaCompile) {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm'
id 'org.jetbrains.dokka'
}
dependencies {
compileOnly libraries.jsr305
testImplementation libraries.junit
testImplementation libraries.truth
}
apply from: rootProject.file("gradle/jacoco.gradle")
apply plugin: 'com.vanniktech.maven.publish'
targetCompatibility = 1.8
sourceCompatibility = 1.8
compileKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
mavenPublishing {
publishToMavenCentral(SonatypeHost.S01)
signAllPublications()
}

111
cache/build.gradle.kts vendored Normal file
View file

@ -0,0 +1,111 @@
@file:Suppress("UnstableApiUsage")
import com.vanniktech.maven.publish.SonatypeHost.S01
import org.jetbrains.dokka.gradle.DokkaTask
plugins {
kotlin("multiplatform")
kotlin("plugin.serialization")
id("com.android.library")
id("com.vanniktech.maven.publish")
id("org.jetbrains.dokka")
id("org.jetbrains.kotlinx.kover")
id("co.touchlab.faktory.kmmbridge") version Version.kmmBridge
`maven-publish`
kotlin("native.cocoapods")
id("kotlinx-atomicfu")
}
kotlin {
android()
jvm()
iosArm64()
iosX64()
js {
browser()
nodejs()
}
cocoapods {
summary = "Cache5"
homepage = "https://github.com/MobileNativeFoundation/Store"
ios.deploymentTarget = "13"
version = Version.store
}
sourceSets {
all {
languageSettings.apply {
optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
optIn("kotlin.RequiresOptIn")
}
}
val commonMain by getting
val jvmMain by getting
val androidMain by getting
val nativeMain by creating {
dependsOn(commonMain)
}
}
}
android {
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
compileSdk = 33
defaultConfig {
minSdk = 24
targetSdk = 33
}
lint {
disable += "ComposableModifierFactory"
disable += "ModifierFactoryExtensionFunction"
disable += "ModifierFactoryReturnType"
disable += "ModifierFactoryUnreferencedReceiver"
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
}
tasks.withType<DokkaTask>().configureEach {
dokkaSourceSets.configureEach {
reportUndocumented.set(false)
skipDeprecated.set(true)
jdkVersion.set(8)
}
}
mavenPublishing {
publishToMavenCentral(S01)
signAllPublications()
}
addGithubPackagesRepository()
kmmbridge {
githubReleaseArtifacts()
githubReleaseVersions()
versionPrefix.set("5.0.0-alpha")
spm()
}
koverMerged {
enable()
xmlReport {
onCheck.set(true)
reportFile.set(layout.projectDirectory.file("kover/coverage.xml"))
}
htmlReport {
onCheck.set(true)
reportDir.set(layout.projectDirectory.dir("kover/html"))
}
verify {
onCheck.set(true)
}
}

View file

@ -1,3 +1,3 @@
POM_NAME=org.mobilenativefoundation.store
POM_ARTIFACT_ID=cache4
POM_ARTIFACT_ID=cache5
POM_PACKAGING=jar

View file

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest package="org.mobilenativefoundation.store.cache5" />

View file

@ -0,0 +1,57 @@
package org.mobilenativefoundation.store.cache5
interface Cache<Key : Any, Value : Any> {
/**
* @return [Value] associated with [key] or `null` if there is no cached value for [key].
*/
fun getIfPresent(key: Key): Value?
/**
* @return [Value] associated with [key], obtaining the value from [valueProducer] if necessary.
* No observable state associated with this cache is modified until loading completes.
* @param [valueProducer] Must not return `null`. It may either return a non-null value or throw an exception.
* @throws ExecutionExeption If a checked exception was thrown while loading the value.
* @throws UncheckedExecutionException If an unchecked exception was thrown while loading the value.
* @throws ExecutionError If an error was thrown while loading the value.
*/
fun getOrPut(key: Key, valueProducer: () -> Value): Value
/**
* @return Map of the [Value] associated with each [Key] in [keys]. Returned map only contains entries already present in the cache.
*/
fun getAllPresent(keys: List<*>): Map<Key, Value>
/**
* Associates [value] with [key].
* If the cache previously contained a value associated with [key], the old value is replaced by [value].
* Prefer [getOrPut] when using the conventional "If cached, then return. Otherwise create, cache, and then return" pattern.
*/
fun put(key: Key, value: Value)
/**
* Copies all of the mappings from the specified map to the cache. The effect of this call is
* equivalent to that of calling [put] on this map once for each mapping from [Key] to [Value] in the specified map.
* The behavior of this operation is undefined if the specified map is modified while the operation is in progress.
*/
fun putAll(map: Map<Key, Value>)
/**
* Discards any cached value associated with [key].
*/
fun invalidate(key: Key)
/**
* Discards any cached value associated for [keys].
*/
fun invalidateAll(keys: List<Key>)
/**
* Discards all entries in the cache.
*/
fun invalidateAll()
/**
* @return Approximate number of entries in the cache.
*/
fun size(): Long
}

View file

@ -0,0 +1,70 @@
package org.mobilenativefoundation.store.cache5
import kotlin.time.Duration
class CacheBuilder<Key : Any, Value : Any> {
internal var concurrencyLevel = 4
private set
internal val initialCapacity = 16
internal var maximumSize = UNSET
private set
internal var maximumWeight = UNSET
private set
internal var expireAfterAccess: Duration = Duration.INFINITE
private set
internal var expireAfterWrite: Duration = Duration.INFINITE
private set
internal var weigher: Weigher<Key, Value>? = null
private set
internal var ticker: Ticker? = null
private set
fun concurrencyLevel(producer: () -> Int): CacheBuilder<Key, Value> = apply {
concurrencyLevel = producer.invoke()
}
fun maximumSize(maximumSize: Long): CacheBuilder<Key, Value> = apply {
if (maximumSize < 0) {
throw IllegalArgumentException("Maximum size must be non-negative.")
}
this.maximumSize = maximumSize
}
fun expireAfterAccess(duration: Duration): CacheBuilder<Key, Value> = apply {
if (duration.isNegative()) {
throw IllegalArgumentException("Duration must be non-negative.")
}
expireAfterAccess = duration
}
fun expireAfterWrite(duration: Duration): CacheBuilder<Key, Value> = apply {
if (duration.isNegative()) {
throw IllegalArgumentException("Duration must be non-negative.")
}
expireAfterWrite = duration
}
fun ticker(ticker: Ticker): CacheBuilder<Key, Value> = apply {
this.ticker = ticker
}
fun weigher(maximumWeight: Long, weigher: Weigher<Key, Value>): CacheBuilder<Key, Value> = apply {
if (maximumWeight < 0) {
throw IllegalArgumentException("Maximum weight must be non-negative.")
}
this.maximumWeight = maximumWeight
this.weigher = weigher
}
fun build(): Cache<Key, Value> {
if (maximumSize != -1L && weigher != null) {
throw IllegalStateException("Maximum size cannot be combined with weigher.")
}
return LocalCache.LocalManualCache(this)
}
companion object {
private const val UNSET = -1L
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,7 @@
package org.mobilenativefoundation.store.cache5
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
@OptIn(ExperimentalTime::class)
internal val MonotonicTicker: Ticker = TimeSource.Monotonic.markNow().let { timeMark -> { timeMark.elapsedNow().inWholeNanoseconds } }

View file

@ -0,0 +1,15 @@
package org.mobilenativefoundation.store.cache5
/**
* The reason why a cached entry was removed.
* @param wasEvicted True if entry removal was automatic due to eviction. That is, the cause of removal is neither [EXPLICIT] or [REPLACED].
* @author Charles Fry
* @since 10.0
*/
internal enum class RemovalCause(val wasEvicted: Boolean) {
EXPLICIT(false),
REPLACED(false),
COLLECTED(true),
EXPIRED(true),
SIZE(true);
}

View file

@ -0,0 +1,6 @@
package org.mobilenativefoundation.store.cache5
/**
* @return Number of nanoseconds elapsed since the ticker's fixed point of reference.
*/
typealias Ticker = () -> Long

View file

@ -0,0 +1,6 @@
package org.mobilenativefoundation.store.cache5
/**
* @return Weight of a cache entry. Must be non-negative. There is no unit for entry weights. Rather, they are simply relative to each other.
*/
typealias Weigher <Key, Value> = (key: Key, value: Value) -> Int

View file

@ -1,921 +0,0 @@
package com.dropbox.android.external.cache3;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.LockSupport;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
public abstract class AbstractFuture<V> implements ListenableFuture<V> {
private static final boolean GENERATE_CANCELLATION_CAUSES =
Boolean.parseBoolean(
System.getProperty("guava.concurrent.generate_cancellation_cause", "false"));
/**
* A less abstract subclass of AbstractFuture. This can be used to optimize setFuture by ensuring
* that {@link #get} calls exactly the implementation of {@link AbstractFuture#get}.
*/
public abstract static class TrustedFuture<V> extends AbstractFuture<V> {
// N.B. cancel is not overridden to be final, because many future utilities need to override
// cancel in order to propagate cancellation to other futures.
// TODO(lukes): with maybePropagateCancellation this is no longer really true. Track down the
// final few cases and eliminate their overrides of cancel()
@Nullable
@Override public final V get() throws InterruptedException, ExecutionException {
return super.get();
}
@Nullable
@Override public final V get(long timeout, @Nonnull TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return super.get(timeout, unit);
}
@Override public final boolean isDone() {
return super.isDone();
}
@Override public final boolean isCancelled() {
return super.isCancelled();
}
@Override public final void addListener(@Nonnull Runnable listener, @Nonnull Executor executor) {
super.addListener(listener, executor);
}
}
// Logger to log exceptions caught when running listeners.
private static final Logger log = Logger.getLogger(AbstractFuture.class.getName());
// A heuristic for timed gets. If the remaining timeout is less than this, spin instead of
// blocking. This value is what AbstractQueuedSynchronizer uses.
private static final long SPIN_THRESHOLD_NANOS = 1000L;
private static final AtomicHelper ATOMIC_HELPER;
static {
AtomicHelper helper;
// catch absolutely everything and fall through to our 'SafeAtomicHelper'
// The access control checks that ARFU does means the caller class has to be AbstractFuture
// instead of SafeAtomicHelper, so we annoyingly define these here
try {
helper = new SafeAtomicHelper(
newUpdater(Waiter.class, Thread.class, "thread"),
newUpdater(Waiter.class, Waiter.class, "next"),
newUpdater(AbstractFuture.class, Waiter.class, "waiters"),
newUpdater(AbstractFuture.class, Listener.class, "listeners"),
newUpdater(AbstractFuture.class, Object.class, "value"));
} catch (Throwable atomicReferenceFieldUpdaterFailure) {
// Some Android 5.0.x Samsung devices have bugs in JDK reflection APIs that cause
// getDeclaredField to throw a NoSuchFieldException when the field is definitely there.
// For these users fallback to a suboptimal implementation, based on synchronized. This
// will be a definite performance hit to those users.
log.log(Level.SEVERE, "UnsafeAtomicHelper is broken!");
log.log(Level.SEVERE, "SafeAtomicHelper is broken!", atomicReferenceFieldUpdaterFailure);
helper = new SynchronizedHelper();
}
ATOMIC_HELPER = helper;
// Prevent rare disastrous classloading in first call to LockSupport.park.
// See: https://bugs.openjdk.java.net/browse/JDK-8074773
@SuppressWarnings("unused")
Class<?> ensureLoaded = LockSupport.class;
}
/**
* Waiter links form a Treiber stack, in the {@link #waiters} field.
*/
private static final class Waiter {
static final Waiter TOMBSTONE = new Waiter(false /* ignored param */);
@Nullable
volatile Thread thread;
volatile Waiter next;
// Constructor for the TOMBSTONE, avoids use of ATOMIC_HELPER in case this class is loaded
// before the ATOMIC_HELPER. Apparently this is possible on some android platforms.
Waiter(boolean unused) {}
Waiter() {
// avoid volatile write, write is made visible by subsequent CAS on waiters field
ATOMIC_HELPER.putThread(this, Thread.currentThread());
}
// non-volatile write to the next field. Should be made visible by subsequent CAS on waiters
// field.
void setNext(Waiter next) {
ATOMIC_HELPER.putNext(this, next);
}
void unpark() {
// This is racy with removeWaiter. The consequence of the race is that we may spuriously
// call unpark even though the thread has already removed itself from the list. But even if
// we did use a CAS, that race would still exist (it would just be ever so slightly smaller).
Thread w = thread;
if (w != null) {
thread = null;
LockSupport.unpark(w);
}
}
}
/**
* Marks the given node as 'deleted' (null waiter) and then scans the list to unlink all deleted
* nodes. This is an O(n) operation in the common case (and O(n^2) in the worst), but we are
* saved by two things.
* <ul>
* <li>This is only called when a waiting thread times out or is interrupted. Both of which
* should be rare.
* <li>The waiters list should be very short.
* </ul>
*/
private void removeWaiter(@Nonnull Waiter node) {
node.thread = null; // mark as 'deleted'
restart: while (true) {
Waiter pred = null;
Waiter curr = waiters;
if (curr == Waiter.TOMBSTONE) {
return; // give up if someone is calling complete
}
Waiter succ;
while (curr != null) {
succ = curr.next;
if (curr.thread != null) { // we aren't unlinking this node, update pred.
pred = curr;
} else if (pred != null) { // We are unlinking this node and it has a predecessor.
pred.next = succ;
if (pred.thread == null) { // We raced with another node that unlinked pred. Restart.
continue restart;
}
} else if (!ATOMIC_HELPER.casWaiters(this, curr, succ)) { // We are unlinking head
continue restart; // We raced with an add or complete
}
curr = succ;
}
break;
}
}
/** Listeners also form a stack through the {@link #listeners} field. */
private static final class Listener {
@Nullable
static final Listener TOMBSTONE = new Listener(null, null);
final Runnable task;
final Executor executor;
// writes to next are made visible by subsequent CAS's on the listeners field
@Nullable
Listener next;
Listener(Runnable task, Executor executor) {
this.task = task;
this.executor = executor;
}
}
/** A special value to represent {@code null}. */
private static final Object NULL = new Object();
/** A special value to represent failure, when {@link #setException} is called successfully. */
private static final class Failure {
static final Failure FALLBACK_INSTANCE = new Failure(
new Throwable("Failure occurred while trying to finish a future.") {
@Nonnull
@Override public synchronized Throwable fillInStackTrace() {
return this; // no stack trace
}
});
@Nullable
final Throwable exception;
Failure(Throwable exception) {
this.exception = Preconditions.checkNotNull(exception);
}
}
/** A special value to represent cancellation and the 'wasInterrupted' bit. */
private static final class Cancellation {
final boolean wasInterrupted;
final Throwable cause;
Cancellation(boolean wasInterrupted, Throwable cause) {
this.wasInterrupted = wasInterrupted;
this.cause = cause;
}
}
/** A special value that encodes the 'setFuture' state. */
private final class SetFuture implements Runnable {
final ListenableFuture<? extends V> future;
SetFuture(ListenableFuture<? extends V> future) {
this.future = future;
}
@Override public void run() {
if (value != this) {
// nothing to do, we must have been cancelled
return;
}
completeWithFuture(future, this);
}
}
// TODO(lukes): investigate using the @Contended annotation on these fields when jdk8 is
// available.
/**
* This field encodes the current state of the future.
*
* <p>The valid values are:
* <ul>
* <li>{@code null} initial state, nothing has happened.
* <li>{@link Cancellation} terminal state, {@code cancel} was called.
* <li>{@link Failure} terminal state, {@code setException} was called.
* <li>{@link SetFuture} intermediate state, {@code setFuture} was called.
* <li>{@link #NULL} terminal state, {@code set(null)} was called.
* <li>Any other non-null value, terminal state, {@code set} was called with a non-null
* argument.
* </ul>
*/
private volatile Object value;
/** All listeners. */
private volatile Listener listeners;
/** All waiting threads. */
private volatile Waiter waiters;
/**
* Constructor for use by subclasses.
*/
protected AbstractFuture() {}
/*
* Improve the documentation of when InterruptedException is thrown. Our
* behavior matches the JDK's, but the JDK's documentation is misleading.
*/
// Gets and Timed Gets
//
// * Be responsive to interruption
// * Don't create Waiter nodes if you aren't going to park, this helps reduce contention on the
// waiters field.
// * Future completion is defined by when #value becomes non-null/non SetFuture
// * Future completion can be observed if the waiters field contains a TOMBSTONE
// Timed Get
// There are a few design constraints to consider
// * We want to be responsive to small timeouts, unpark() has non trivial latency overheads (I
// have observed 12 micros on 64 bit linux systems to wake up a parked thread). So if the
// timeout is small we shouldn't park(). This needs to be traded off with the cpu overhead of
// spinning, so we use SPIN_THRESHOLD_NANOS which is what AbstractQueuedSynchronizer uses for
// similar purposes.
// * We want to behave reasonably for timeouts of 0
// * We are more responsive to completion than timeouts. This is because parkNanos depends on
// system scheduling and as such we could either miss our deadline, or unpark() could be delayed
// so that it looks like we timed out even though we didn't. For comparison FutureTask respects
// completion preferably and AQS is non-deterministic (depends on where in the queue the waiter
// is). If we wanted to be strict about it, we could store the unpark() time in the Waiter
// node and we could use that to make a decision about whether or not we timed out prior to
// being unparked.
/**
* {@inheritDoc}
*
* <p>The default {@link AbstractFuture} implementation throws {@code
* InterruptedException} if the current thread is interrupted before or during
* the call, even if the value is already available.
*
* @throws InterruptedException if the current thread was interrupted before
* or during the call (optional but recommended).
* @throws CancellationException {@inheritDoc}
*/
@Nullable
@Override
public V get(long timeout, @Nonnull TimeUnit unit)
throws InterruptedException, TimeoutException, ExecutionException {
// NOTE: if timeout < 0, remainingNanos will be < 0 and we will fall into the while(true) loop
// at the bottom and throw a timeoutexception.
long remainingNanos = unit.toNanos(timeout); // we rely on the implicit null check on unit.
if (Thread.interrupted()) {
throw new InterruptedException();
}
Object localValue = value;
if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
return getDoneValue(localValue);
}
// we delay calling nanoTime until we know we will need to either park or spin
final long endNanos = remainingNanos > 0 ? System.nanoTime() + remainingNanos : 0;
long_wait_loop: if (remainingNanos >= SPIN_THRESHOLD_NANOS) {
Waiter oldHead = waiters;
if (oldHead != Waiter.TOMBSTONE) {
Waiter node = new Waiter();
do {
node.setNext(oldHead);
if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
while (true) {
LockSupport.parkNanos(this, remainingNanos);
// Check interruption first, if we woke up due to interruption we need to honor that.
if (Thread.interrupted()) {
removeWaiter(node);
throw new InterruptedException();
}
// Otherwise re-read and check doneness. If we loop then it must have been a spurious
// wakeup
localValue = value;
if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
return getDoneValue(localValue);
}
// timed out?
remainingNanos = endNanos - System.nanoTime();
if (remainingNanos < SPIN_THRESHOLD_NANOS) {
// Remove the waiter, one way or another we are done parking this thread.
removeWaiter(node);
break long_wait_loop; // jump down to the busy wait loop
}
}
}
oldHead = waiters; // re-read and loop.
} while (oldHead != Waiter.TOMBSTONE);
}
// re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
// waiter.
return getDoneValue(value);
}
// If we get here then we have remainingNanos < SPIN_THRESHOLD_NANOS and there is no node on the
// waiters list
while (remainingNanos > 0) {
localValue = value;
if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
return getDoneValue(localValue);
}
if (Thread.interrupted()) {
throw new InterruptedException();
}
remainingNanos = endNanos - System.nanoTime();
}
throw new TimeoutException();
}
/*
* Improve the documentation of when InterruptedException is thrown. Our
* behavior matches the JDK's, but the JDK's documentation is misleading.
*/
/**
* {@inheritDoc}
*
* <p>The default {@link AbstractFuture} implementation throws {@code
* InterruptedException} if the current thread is interrupted before or during
* the call, even if the value is already available.
*
* @throws InterruptedException if the current thread was interrupted before
* or during the call (optional but recommended).
* @throws CancellationException {@inheritDoc}
*/
@Nullable
@Override public V get() throws InterruptedException, ExecutionException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
Object localValue = value;
if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
return getDoneValue(localValue);
}
Waiter oldHead = waiters;
if (oldHead != Waiter.TOMBSTONE) {
Waiter node = new Waiter();
do {
node.setNext(oldHead);
if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
// we are on the stack, now wait for completion.
while (true) {
LockSupport.park(this);
// Check interruption first, if we woke up due to interruption we need to honor that.
if (Thread.interrupted()) {
removeWaiter(node);
throw new InterruptedException();
}
// Otherwise re-read and check doneness. If we loop then it must have been a spurious
// wakeup
localValue = value;
if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
return getDoneValue(localValue);
}
}
}
oldHead = waiters; // re-read and loop.
} while (oldHead != Waiter.TOMBSTONE);
}
// re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
// waiter.
return getDoneValue(value);
}
/**
* Unboxes {@code obj}. Assumes that obj is not {@code null} or a {@link SetFuture}.
*/
private V getDoneValue(Object obj) throws ExecutionException {
// While this seems like it might be too branch-y, simple benchmarking proves it to be
// unmeasurable (comparing done AbstractFutures with immediateFuture)
if (obj instanceof Cancellation) {
throw cancellationExceptionWithCause("Task was cancelled.", ((Cancellation) obj).cause);
} else if (obj instanceof Failure) {
throw new ExecutionException(((Failure) obj).exception);
} else if (obj == NULL) {
return null;
} else {
@SuppressWarnings("unchecked") // this is the only other option
V asV = (V) obj;
return asV;
}
}
@Override
public boolean isDone() {
final Object localValue = value;
return localValue != null & !(localValue instanceof AbstractFuture.SetFuture);
}
@Override
public boolean isCancelled() {
final Object localValue = value;
return localValue instanceof Cancellation;
}
/**
* {@inheritDoc}
*
* <p>If a cancellation attempt succeeds on a {@code Future} that had previously been {@linkplain
* #setFuture set asynchronously}, then the cancellation will also be propagated to the delegate
* {@code Future} that was supplied in the {@code setFuture} call.
*/
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
Object localValue = value;
if (localValue == null | localValue instanceof AbstractFuture.SetFuture) {
// Try to delay allocating the exception. At this point we may still lose the CAS, but it is
// certainly less likely.
// TODO(lukes): this exception actually makes cancellation significantly more expensive :(
// I wonder if we should consider removing it or providing a mechanism to not do it.
Throwable cause = GENERATE_CANCELLATION_CAUSES ? newCancellationCause() : null;
Object valueToSet = new Cancellation(mayInterruptIfRunning, cause);
do {
if (ATOMIC_HELPER.casValue(this, localValue, valueToSet)) {
// We call interuptTask before calling complete(), first which is consistent with
// FutureTask
if (mayInterruptIfRunning) {
interruptTask();
}
complete();
if (localValue instanceof AbstractFuture.SetFuture) {
// propagate cancellation to the future set in setfuture, this is racy, and we don't
// care if we are successful or not.
((AbstractFuture<?>.SetFuture) localValue).future.cancel(mayInterruptIfRunning);
}
return true;
}
// obj changed, reread
localValue = value;
// obj cannot be null at this point, because value can only change from null to non-null. So
// if value changed (and it did since we lost the CAS), then it cannot be null.
} while (localValue instanceof AbstractFuture.SetFuture);
}
return false;
}
/**
* Returns an exception to be used as the cause of the CancellationException thrown by
* {@link #get}.
*
* <p>Note: this method may be called speculatively. There is no guarantee that the future will
* be cancelled if this method is called.
*/
@Nonnull
private Throwable newCancellationCause() {
return new CancellationException("Future.cancel() was called.");
}
/**
* Subclasses can override this method to implement interruption of the
* future's computation. The method is invoked automatically by a successful
* call to {@link #cancel(boolean) cancel(true)}.
*
* <p>The default implementation does nothing.
*
* @since 10.0
*/
protected void interruptTask() {
}
/**
* Returns true if this future was cancelled with {@code
* mayInterruptIfRunning} set to {@code true}.
*
* @since 14.0
*/
protected final boolean wasInterrupted() {
final Object localValue = value;
return (localValue instanceof Cancellation) && ((Cancellation) localValue).wasInterrupted;
}
/**
* {@inheritDoc}
*
* @since 10.0
*/
@Override
public void addListener(@Nonnull Runnable listener, @Nonnull Executor executor) {
Preconditions.checkNotNull(listener, "Runnable was null.");
Preconditions.checkNotNull(executor, "Executor was null.");
Listener oldHead = listeners;
if (oldHead != Listener.TOMBSTONE) {
Listener newNode = new Listener(listener, executor);
do {
newNode.next = oldHead;
if (ATOMIC_HELPER.casListeners(this, oldHead, newNode)) {
return;
}
oldHead = listeners; // re-read
} while (oldHead != Listener.TOMBSTONE);
}
// If we get here then the Listener TOMBSTONE was set, which means the future is done, call
// the listener.
executeListener(listener, executor);
}
/**
* Sets the result of this {@code Future} unless this {@code Future} has already been cancelled or
* set (including {@linkplain #setFuture set asynchronously}). When a call to this method returns,
* the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> the call was
* accepted (in which case it returns {@code true}). If it returns {@code false}, the {@code
* Future} may have previously been set asynchronously, in which case its result may not be known
* yet. That result, though not yet known, cannot by overridden by a call to a {@code set*}
* method, only by a call to {@link #cancel}.
*
* @param value the value to be used as the result
* @return true if the attempt was accepted, completing the {@code Future}
*/
protected boolean set(@Nullable V value) {
Object valueToSet = value == null ? NULL : value;
if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
complete();
return true;
}
return false;
}
/**
* Sets the failed result of this {@code Future} unless this {@code Future} has already been
* cancelled or set (including {@linkplain #setFuture set asynchronously}). When a call to this
* method returns, the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b>
* the call was accepted (in which case it returns {@code true}). If it returns {@code false}, the
* {@code Future} may have previously been set asynchronously, in which case its result may not be
* known yet. That result, though not yet known, cannot by overridden by a call to a {@code set*}
* method, only by a call to {@link #cancel}.
*
* @param throwable the exception to be used as the failed result
* @return true if the attempt was accepted, completing the {@code Future}
*/
protected boolean setException(Throwable throwable) {
Object valueToSet = new Failure(Preconditions.checkNotNull(throwable));
if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
complete();
return true;
}
return false;
}
/**
* Sets the result of this {@code Future} to match the supplied input {@code Future} once the
* supplied {@code Future} is done, unless this {@code Future} has already been cancelled or set
* (including "set asynchronously," defined below).
*
* <p>If the supplied future is {@linkplain #isDone done} when this method is called and the call
* is accepted, then this future is guaranteed to have been completed with the supplied future by
* the time this method returns. If the supplied future is not done and the call is accepted, then
* the future will be <i>set asynchronously</i>. Note that such a result, though not yet known,
* cannot by overridden by a call to a {@code set*} method, only by a call to {@link #cancel}.
*
* <p>If the call {@code setFuture(delegate)} is accepted and this {@code Future} is later
* cancelled, cancellation will be propagated to {@code delegate}. Additionally, any call to
* {@code setFuture} after any cancellation will propagate cancellation to the supplied {@code
* Future}.
*
* @param future the future to delegate to
* @return true if the attempt was accepted, indicating that the {@code Future} was not previously
* cancelled or set.
* @since 19.0
*/
protected boolean setFuture(@Nonnull ListenableFuture<? extends V> future) {
Preconditions.checkNotNull(future);
Object localValue = value;
if (localValue == null) {
if (future.isDone()) {
return completeWithFuture(future, null);
}
SetFuture valueToSet = new SetFuture(future);
if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
// the listener is responsible for calling completeWithFuture, directExecutor is appropriate
// since all we are doing is unpacking a completed future which should be fast.
try {
future.addListener(valueToSet, DirectExecutor.INSTANCE);
} catch (Throwable t) {
// addListener has thrown an exception! SetFuture.run can't throw any exceptions so this
// must have been caused by addListener itself. The most likely explanation is a
// misconfigured mock. Try to switch to Failure.
Failure failure;
try {
failure = new Failure(t);
} catch (Throwable oomMostLikely) {
failure = Failure.FALLBACK_INSTANCE;
}
// Note: The only way this CAS could fail is if cancel() has raced with us. That is ok.
ATOMIC_HELPER.casValue(this, valueToSet, failure);
}
return true;
}
localValue = value; // we lost the cas, fall through and maybe cancel
}
// The future has already been set to something. If it is cancellation we should cancel the
// incoming future.
if (localValue instanceof Cancellation) {
// we don't care if it fails, this is best-effort.
future.cancel(((Cancellation) localValue).wasInterrupted);
}
return false;
}
/**
* Called when a future passed via setFuture has completed.
*
* @param future the done future to complete this future with.
* @param expected the expected value of the {@link #value} field.
*/
private boolean completeWithFuture(ListenableFuture<? extends V> future, Object expected) {
Object valueToSet;
if (future instanceof TrustedFuture) {
// Break encapsulation for TrustedFuture instances since we know that subclasses cannot
// override .get() (since it is final) and therefore this is equivalent to calling .get()
// and unpacking the exceptions like we do below (just much faster because it is a single
// field read instead of a read, several branches and possibly creating exceptions).
valueToSet = ((AbstractFuture<?>) future).value;
} else {
// Otherwise calculate valueToSet by calling .get()
try {
V v = Uninterruptibles.getUninterruptibly(future);
valueToSet = v == null ? NULL : v;
} catch (ExecutionException exception) {
valueToSet = new Failure(exception.getCause());
} catch (CancellationException cancellation) {
valueToSet = new Cancellation(false, cancellation);
} catch (Throwable t) {
valueToSet = new Failure(t);
}
}
// The only way this can fail is if we raced with another thread calling cancel(). If we lost
// that race then there is nothing to do.
if (ATOMIC_HELPER.casValue(AbstractFuture.this, expected, valueToSet)) {
complete();
return true;
}
return false;
}
/** Unblocks all threads and runs all listeners. */
private void complete() {
for (Waiter currentWaiter = clearWaiters();
currentWaiter != null;
currentWaiter = currentWaiter.next) {
currentWaiter.unpark();
}
// We need to reverse the list to handle buggy listeners that depend on ordering.
Listener currentListener = clearListeners();
Listener reversedList = null;
while (currentListener != null) {
Listener tmp = currentListener;
currentListener = currentListener.next;
tmp.next = reversedList;
reversedList = tmp;
}
for (; reversedList != null; reversedList = reversedList.next) {
executeListener(reversedList.task, reversedList.executor);
}
// We call this after the listeners on the theory that done() will only be used for 'cleanup'
// oriented tasks (e.g. clearing fields) and so can wait behind listeners which may be executing
// more important work. A counter argument would be that done() is trusted code and therefore
// it would be safe to run before potentially slow or poorly behaved listeners. Reevaluate this
// once we have more examples of done() implementations.
done();
}
/**
* Callback method that is called immediately after the future is completed.
*
* <p>This is called exactly once, after all listeners have executed. By default it does nothing.
*/
void done() {}
/**
* Returns the exception that this {@code Future} completed with. This includes completion through
* a call to @link setException} or @link setFuture}{@code (failedFuture)} but not cancellation.
*
* @throws RuntimeException if the {@code Future} has not failed
*/
/**
* If this future has been cancelled (and possibly interrupted), cancels (and possibly interrupts)
* the given future (if available).
*
* <p>This method should be used only when this future is completed. It is designed to be called
* from {@code done}.
*/
final void maybePropagateCancellation(@Nullable Future<?> related) {
if (related != null & isCancelled()) {
related.cancel(wasInterrupted());
}
}
/** Clears the {@link #waiters} list and returns the most recently added value. */
private Waiter clearWaiters() {
Waiter head;
do {
head = waiters;
} while (!ATOMIC_HELPER.casWaiters(this, head, Waiter.TOMBSTONE));
return head;
}
/** Clears the {@link #listeners} list and returns the most recently added value. */
private Listener clearListeners() {
Listener head;
do {
head = listeners;
} while (!ATOMIC_HELPER.casListeners(this, head, Listener.TOMBSTONE));
return head;
}
/**
* Submits the given runnable to the given {@link Executor} catching and logging all
* {@linkplain RuntimeException runtime exceptions} thrown by the executor.
*/
private static void executeListener(@Nonnull Runnable runnable, @Nonnull Executor executor) {
try {
executor.execute(runnable);
} catch (RuntimeException e) {
// Log it and keep going, bad runnable and/or executor. Don't
// punish the other runnables if we're given a bad one. We only
// catch RuntimeException because we want Errors to propagate up.
log.log(Level.SEVERE, "RuntimeException while executing runnable "
+ runnable + " with executor " + executor, e);
}
}
@Nonnull
static final CancellationException cancellationExceptionWithCause(
String message, Throwable cause) {
CancellationException exception = new CancellationException(message);
exception.initCause(cause);
return exception;
}
private abstract static class AtomicHelper {
/** Non volatile write of the thread to the {@link Waiter#thread} field. */
abstract void putThread(Waiter waiter, Thread newValue);
/** Non volatile write of the waiter to the {@link Waiter#next} field. */
abstract void putNext(Waiter waiter, Waiter newValue);
/** Performs a CAS operation on the {@link #waiters} field. */
abstract boolean casWaiters(AbstractFuture<?> future, Waiter expect, Waiter update);
/** Performs a CAS operation on the {@link #listeners} field. */
abstract boolean casListeners(AbstractFuture<?> future, Listener expect, Listener update);
/** Performs a CAS operation on the {@link #value} field. */
abstract boolean casValue(AbstractFuture<?> future, Object expect, Object update);
}
/**
* {@link AtomicHelper} based on {@link sun.misc.Unsafe}.
*
* <p>Static initialization of this class will fail if the {@link sun.misc.Unsafe} object cannot
* be accessed.
*/
/** {@link AtomicHelper} based on {@link AtomicReferenceFieldUpdater}. */
private static final class SafeAtomicHelper extends AtomicHelper {
final AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater;
final AtomicReferenceFieldUpdater<Waiter, Waiter> waiterNextUpdater;
final AtomicReferenceFieldUpdater<AbstractFuture, Waiter> waitersUpdater;
final AtomicReferenceFieldUpdater<AbstractFuture, Listener> listenersUpdater;
final AtomicReferenceFieldUpdater<AbstractFuture, Object> valueUpdater;
SafeAtomicHelper(
AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater,
AtomicReferenceFieldUpdater<Waiter, Waiter> waiterNextUpdater,
AtomicReferenceFieldUpdater<AbstractFuture, Waiter> waitersUpdater,
AtomicReferenceFieldUpdater<AbstractFuture, Listener> listenersUpdater,
AtomicReferenceFieldUpdater<AbstractFuture, Object> valueUpdater) {
this.waiterThreadUpdater = waiterThreadUpdater;
this.waiterNextUpdater = waiterNextUpdater;
this.waitersUpdater = waitersUpdater;
this.listenersUpdater = listenersUpdater;
this.valueUpdater = valueUpdater;
}
@Override
void putThread(@Nonnull Waiter waiter, Thread newValue) {
waiterThreadUpdater.lazySet(waiter, newValue);
}
@Override
void putNext(@Nonnull Waiter waiter, Waiter newValue) {
waiterNextUpdater.lazySet(waiter, newValue);
}
@Override
boolean casWaiters(@Nonnull AbstractFuture<?> future, Waiter expect, Waiter update) {
return waitersUpdater.compareAndSet(future, expect, update);
}
@Override
boolean casListeners(@Nonnull AbstractFuture<?> future, Listener expect, Listener update) {
return listenersUpdater.compareAndSet(future, expect, update);
}
@Override
boolean casValue(@Nonnull AbstractFuture<?> future, Object expect, Object update) {
return valueUpdater.compareAndSet(future, expect, update);
}
}
/**
* {@link AtomicHelper} based on {@code synchronized} and volatile writes.
*
* <p>This is an implementation of last resort for when certain basic VM features are broken
* (like AtomicReferenceFieldUpdater).
*/
private static final class SynchronizedHelper extends AtomicHelper {
@Override
void putThread(@Nonnull Waiter waiter, Thread newValue) {
waiter.thread = newValue;
}
@Override
void putNext(@Nonnull Waiter waiter, Waiter newValue) {
waiter.next = newValue;
}
@Override
boolean casWaiters(@Nonnull AbstractFuture<?> future, Waiter expect, Waiter update) {
synchronized (future) {
if (future.waiters == expect) {
future.waiters = update;
return true;
}
return false;
}
}
@Override
boolean casListeners(@Nonnull AbstractFuture<?> future, Listener expect, Listener update) {
synchronized (future) {
if (future.listeners == expect) {
future.listeners = update;
return true;
}
return false;
}
}
@Override
boolean casValue(@Nonnull AbstractFuture<?> future, Object expect, Object update) {
synchronized (future) {
if (future.value == expect) {
future.value = update;
return true;
}
return false;
}
}
}
}

View file

@ -1,48 +0,0 @@
package com.dropbox.android.external.cache3;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
public abstract class AbstractSequentialIterator<T> extends UnmodifiableIterator<T> {
@Nullable
private T nextOrNull;
/**
* Creates a new iterator with the given first element, or, if {@code
* firstOrNull} is null, creates a new empty iterator.
*/
protected AbstractSequentialIterator( T firstOrNull) {
this.nextOrNull = firstOrNull;
}
/**
* Returns the element that follows {@code previous}, or returns {@code null}
* if no elements remain. This method is invoked during each call to
* {@link #next()} in order to compute the result of a <i>future</i> call to
* {@code next()}.
*/
@Nullable
protected abstract T computeNext(T previous);
@Override
public final boolean hasNext() {
return nextOrNull != null;
}
@Nullable
@Override
public final T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return nextOrNull;
} finally {
nextOrNull = computeNext(nextOrNull);
}
}
}

View file

@ -1,43 +0,0 @@
package com.dropbox.android.external.cache3;
import javax.annotation.Nonnull;
public final class Ascii {
private Ascii() {
}
/**
* Returns a copy of the input string in which all {@linkplain #isUpperCase(char) uppercase ASCII
* characters} have been converted to lowercase. All other characters are copied without
* modification.
*/
@Nonnull
public static String toLowerCase(@Nonnull String string) {
int length = string.length();
for (int i = 0; i < length; i++) {
if (isUpperCase(string.charAt(i))) {
char[] chars = string.toCharArray();
for (; i < length; i++) {
char c = chars[i];
if (isUpperCase(c)) {
chars[i] = (char) (c ^ 0x20);
}
}
return String.valueOf(chars);
}
}
return string;
}
/**
* Indicates whether {@code c} is one of the twenty-six uppercase ASCII alphabetic characters
* between {@code 'A'} and {@code 'Z'} inclusive. All others (including non-ASCII characters)
* return {@code false}.
*/
public static boolean isUpperCase(char c) {
return (c >= 'A') && (c <= 'Z');
}
}

View file

@ -1,110 +0,0 @@
package com.dropbox.android.external.cache3;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public interface Cache<K, V> {
/**
* Returns the value associated with {@code key} in this cache, or {@code null} if there is no
* cached value for {@code key}.
*
* @since 11.0
*/
@Nullable
V getIfPresent(Object key);
/**
* Returns the value associated with {@code key} in this cache, obtaining that value from
* {@code valueLoader} if necessary. No observable state associated with this cache is modified
* until loading completes. This method provides a simple substitute for the conventional
* "if cached, return; otherwise create, cache and return" pattern.
*
* <p><b>Warning:</b> as with {@link CacheLoader#load}, {@code valueLoader} <b>must not</b> return
* {@code null}; it may either return a non-null value or throw an exception.
*
* @throws ExecutionException if a checked exception was thrown while loading the value
* @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
* value
* @throws ExecutionError if an error was thrown while loading the value
*
* @since 11.0
*/
@Nonnull
V get(K key, Callable<? extends V> valueLoader) throws ExecutionException;
/**
* Returns a map of the values associated with {@code keys} in this cache. The returned map will
* only contain entries which are already present in the cache.
*
* @since 11.0
*/
Map<K, V> getAllPresent(Iterable<?> keys);
/**
* Associates {@code value} with {@code key} in this cache. If the cache previously contained a
* value associated with {@code key}, the old value is replaced by {@code value}.
*
* <p>Prefer {@link #get(Object, Callable)} when using the conventional "if cached, return;
* otherwise create, cache and return" pattern.
*
* @since 11.0
*/
void put(K key, V value);
/**
* Copies all of the mappings from the specified map to the cache. The effect of this call is
* equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key
* {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined
* if the specified map is modified while the operation is in progress.
*
* @since 12.0
*/
void putAll(Map<? extends K,? extends V> m);
/**
* Discards any cached value for key {@code key}.
*/
void invalidate(Object key);
/**
* Discards any cached values for keys {@code keys}.
*
* @since 11.0
*/
void invalidateAll(Iterable<?> keys);
/**
* Discards all entries in the cache.
*/
void invalidateAll();
/**
* Returns the approximate number of entries in this cache.
*/
long size();
/**
* Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to
* the map directly affect the cache.
*
* <p>Iterators from the returned map are at least <i>weakly consistent</i>: they are safe for
* concurrent use, but if the cache is modified (including by eviction) after the iterator is
* created, it is undefined which of the changes (if any) will be reflected in that iterator.
*/
ConcurrentMap<K, V> asMap();
/**
* Performs any pending maintenance operations needed by the cache. Exactly which activities are
* performed -- if any -- is implementation-dependent.
*/
void cleanUp();
}

View file

@ -1,553 +0,0 @@
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public final class CacheBuilder<K, V> {
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private static final int DEFAULT_CONCURRENCY_LEVEL = 4;
private static final int DEFAULT_EXPIRATION_NANOS = 0;
private static final int DEFAULT_REFRESH_NANOS = 0;
enum NullListener implements RemovalListener<Object, Object> {
INSTANCE;
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {}
}
enum OneWeigher implements Weigher<Object, Object> {
INSTANCE;
@Override
public int weigh(Object key, Object value) {
return 1;
}
}
static final Ticker NULL_TICKER = new Ticker() {
@Override
public long read() {
return 0;
}
};
private static final Logger logger = Logger.getLogger(CacheBuilder.class.getName());
static final int UNSET_INT = -1;
boolean strictParsing = true;
int initialCapacity = UNSET_INT;
int concurrencyLevel = UNSET_INT;
long maximumSize = UNSET_INT;
long maximumWeight = UNSET_INT;
Weigher<? super K, ? super V> weigher;
LocalCache.Strength keyStrength;
LocalCache.Strength valueStrength;
long expireAfterWriteNanos = UNSET_INT;
long expireAfterAccessNanos = UNSET_INT;
long refreshNanos = UNSET_INT;
Equivalence<Object> keyEquivalence;
Equivalence<Object> valueEquivalence;
RemovalListener<? super K, ? super V> removalListener;
Ticker ticker;
// TODO(fry): make constructor private and update tests to use newBuilder
CacheBuilder() {}
/**
* Constructs a new {@code CacheBuilder} instance with default settings, including strong keys,
* strong values, and no automatic eviction of any kind.
*/
@Nonnull
public static CacheBuilder<Object, Object> newBuilder() {
return new CacheBuilder<>();
}
/**
* Sets a custom {@code Equivalence} strategy for comparing keys.
*
* <p>By default, the cache uses {@link Equivalence#identity} to determine key equality when
* @link #weakKeys} is specified, and {@link Equivalence#equals()} otherwise.
*/
@Nonnull
CacheBuilder<K, V> keyEquivalence(@Nonnull Equivalence<Object> equivalence) {
Preconditions.checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
keyEquivalence = Preconditions.checkNotNull(equivalence);
return this;
}
@Nullable
Equivalence<Object> getKeyEquivalence() {
return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence());
}
/**
* Sets a custom {@code Equivalence} strategy for comparing values.
*
* <p>By default, the cache uses {@link Equivalence#identity} to determine value equality when
* @link #weakValues} or @link #softValues} is specified, and {@link Equivalence#equals()}
* otherwise.
*/
@Nonnull
CacheBuilder<K, V> valueEquivalence(@Nonnull Equivalence<Object> equivalence) {
Preconditions.checkState(valueEquivalence == null,
"value equivalence was already set to %s", valueEquivalence);
this.valueEquivalence = Preconditions.checkNotNull(equivalence);
return this;
}
@Nullable
Equivalence<Object> getValueEquivalence() {
return MoreObjects.firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence());
}
int getInitialCapacity() {
return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity;
}
/**
* Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The
* table is internally partitioned to try to permit the indicated number of concurrent updates
* without contention. Because assignment of entries to these partitions is not necessarily
* uniform, the actual concurrency observed may vary. Ideally, you should choose a value to
* accommodate as many threads as will ever concurrently modify the table. Using a significantly
* higher value than you need can waste space and time, and a significantly lower value can lead
* to thread contention. But overestimates and underestimates within an order of magnitude do not
* usually have much noticeable impact. A value of one permits only one thread to modify the cache
* at a time, but since read operations and cache loading computations can proceed concurrently,
* this still yields higher concurrency than full synchronization.
*
* <p> Defaults to 4. <b>Note:</b>The default may change in the future. If you care about this
* value, you should always choose it explicitly.
*
* <p>The current implementation uses the concurrency level to create a fixed number of hashtable
* segments, each governed by its own write lock. The segment lock is taken once for each explicit
* write, and twice for each cache loading computation (once prior to loading the new value,
* and once after loading completes). Much internal cache management is performed at the segment
* granularity. For example, access queues and write queues are kept per segment when they are
* required by the selected eviction algorithm. As such, when writing unit tests it is not
* uncommon to specify {@code concurrencyLevel(1)} in order to achieve more deterministic eviction
* behavior.
*
* <p>Note that future implementations may abandon segment locking in favor of more advanced
* concurrency controls.
*
* @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive
* @throws IllegalStateException if a concurrency level was already set
*/
@Nonnull
public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) {
Preconditions.checkState(this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s",
this.concurrencyLevel);
Preconditions.checkArgument(concurrencyLevel > 0);
this.concurrencyLevel = concurrencyLevel;
return this;
}
int getConcurrencyLevel() {
return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel;
}
/**
* Specifies the maximum number of entries the cache may contain. Note that the cache <b>may evict
* an entry before this limit is exceeded</b>. As the cache size grows close to the maximum, the
* cache evicts entries that are less likely to be used again. For example, the cache may evict an
* entry because it hasn't been used recently or very often.
*
* <p>When {@code size} is zero, elements will be evicted immediately after being loaded into the
* cache. This can be useful in testing, or to disable caching temporarily without a code change.
*
* <p>This feature cannot be used in conjunction with {@link #maximumWeight}.
*
* @param size the maximum size of the cache
* @throws IllegalArgumentException if {@code size} is negative
* @throws IllegalStateException if a maximum size or weight was already set
*/
@Nonnull
public CacheBuilder<K, V> maximumSize(long size) {
Preconditions.checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
this.maximumSize);
Preconditions.checkState(this.maximumWeight == UNSET_INT, "maximum weight was already set to %s",
this.maximumWeight);
Preconditions.checkState(this.weigher == null, "maximum size can not be combined with weigher");
Preconditions.checkArgument(size >= 0, "maximum size must not be negative");
this.maximumSize = size;
return this;
}
/**
* Specifies the maximum weight of entries the cache may contain. Weight is determined using the
* {@link Weigher} specified with {@link #weigher}, and use of this method requires a
* corresponding call to {@link #weigher} prior to calling {@link #build}.
*
* <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. As the cache
* size grows close to the maximum, the cache evicts entries that are less likely to be used
* again. For example, the cache may evict an entry because it hasn't been used recently or very
* often.
*
* <p>When {@code weight} is zero, elements will be evicted immediately after being loaded into
* cache. This can be useful in testing, or to disable caching temporarily without a code
* change.
*
* <p>Note that weight is only used to determine whether the cache is over capacity; it has no
* effect on selecting which entry should be evicted next.
*
* <p>This feature cannot be used in conjunction with {@link #maximumSize}.
*
* @param weight the maximum total weight of entries the cache may contain
* @throws IllegalArgumentException if {@code weight} is negative
* @throws IllegalStateException if a maximum weight or size was already set
* @since 11.0
*/
@Nonnull
public CacheBuilder<K, V> maximumWeight(long weight) {
Preconditions.checkState(this.maximumWeight == UNSET_INT, "maximum weight was already set to %s",
this.maximumWeight);
Preconditions.checkState(this.maximumSize == UNSET_INT, "maximum size was already set to %s",
this.maximumSize);
this.maximumWeight = weight;
Preconditions.checkArgument(weight >= 0, "maximum weight must not be negative");
return this;
}
/**
* Specifies the weigher to use in determining the weight of entries. Entry weight is taken
* into consideration by {@link #maximumWeight(long)} when determining which entries to evict, and
* use of this method requires a corresponding call to {@link #maximumWeight(long)} prior to
* calling {@link #build}. Weights are measured and recorded when entries are inserted into the
* cache, and are thus effectively static during the lifetime of a cache entry.
*
* <p>When the weight of an entry is zero it will not be considered for size-based eviction
* (though it still may be evicted by other means).
*
* <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder}
* instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the
* original reference or the returned reference may be used to complete configuration and build
* the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from
* building caches whose key or value types are incompatible with the types accepted by the
* weigher already provided; the {@code CacheBuilder} type cannot do this. For best results,
* simply use the standard method-chaining idiom, as illustrated in the documentation at top,
* configuring a {@code CacheBuilder} and building your Cache all in a single statement.
*
* <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build
* a cache whose key or value type is incompatible with the weigher, you will likely experience
* a {@link ClassCastException} at some <i>undefined</i> point in the future.
*
* @param weigher the weigher to use in calculating the weight of cache entries
* @throws IllegalArgumentException if {@code size} is negative
* @throws IllegalStateException if a maximum size was already set
* @since 11.0
*/
@Nonnull
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
@Nonnull Weigher<? super K1, ? super V1> weigher) {
Preconditions.checkState(this.weigher == null);
if (strictParsing) {
Preconditions.checkState(this.maximumSize == UNSET_INT, "weigher can not be combined with maximum size",
this.maximumSize);
}
// safely limiting the kinds of caches this can produce
@SuppressWarnings("unchecked")
CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
me.weigher = Preconditions.checkNotNull(weigher);
return me;
}
long getMaximumWeight() {
if (expireAfterWriteNanos == 0 || expireAfterAccessNanos == 0) {
return 0;
}
return (weigher == null) ? maximumSize : maximumWeight;
}
// Make a safe contravariant cast now so we don't have to do it over and over.
@Nullable
@SuppressWarnings("unchecked")
<K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() {
return (Weigher<K1, V1>) MoreObjects.firstNonNull(weigher, OneWeigher.INSTANCE);
}
@Nonnull
CacheBuilder<K, V> setKeyStrength(@Nonnull LocalCache.Strength strength) {
Preconditions.checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
keyStrength = Preconditions.checkNotNull(strength);
return this;
}
@Nullable
LocalCache.Strength getKeyStrength() {
return MoreObjects.firstNonNull(keyStrength, LocalCache.Strength.STRONG);
}
@Nonnull
CacheBuilder<K, V> setValueStrength(@Nonnull LocalCache.Strength strength) {
Preconditions.checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
valueStrength = Preconditions.checkNotNull(strength);
return this;
}
@Nullable
LocalCache.Strength getValueStrength() {
return MoreObjects.firstNonNull(valueStrength, LocalCache.Strength.STRONG);
}
/**
* Specifies that each entry should be automatically removed from the cache once a fixed duration
* has elapsed after the entry's creation, or the most recent replacement of its value.
*
* <p>When {@code duration} is zero, this method hands off to
* {@link #maximumSize(long) maximumSize}{@code (0)}, ignoring any otherwise-specificed maximum
* size or weight. This can be useful in testing, or to disable caching temporarily without a code
* change.
*
* <p>Expired entries may be counted in @link Cache#size}, but will never be visible to read or
* write operations. Expired entries are cleaned up as part of the routine maintenance described
* in the class javadoc.
*
* @param duration the length of time after an entry is created that it should be automatically
* removed
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if the time to live or time to idle was already set
*/
@Nonnull
public CacheBuilder<K, V> expireAfterWrite(long duration, @Nonnull TimeUnit unit) {
Preconditions.checkState(expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns",
expireAfterWriteNanos);
Preconditions.checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
this.expireAfterWriteNanos = unit.toNanos(duration);
return this;
}
long getExpireAfterWriteNanos() {
return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos;
}
/**
* Specifies that each entry should be automatically removed from the cache once a fixed duration
* has elapsed after the entry's creation, the most recent replacement of its value, or its last
* access. Access time is reset by all cache read and write operations (including
* {@code Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by operations
* on the collection-views of @link Cache#asMap}.
*
* <p>When {@code duration} is zero, this method hands off to
* {@link #maximumSize(long) maximumSize}{@code (0)}, ignoring any otherwise-specificed maximum
* size or weight. This can be useful in testing, or to disable caching temporarily without a code
* change.
*
* <p>Expired entries may be counted in @link Cache#size}, but will never be visible to read or
* write operations. Expired entries are cleaned up as part of the routine maintenance described
* in the class javadoc.
*
* @param duration the length of time after an entry is last accessed that it should be
* automatically removed
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is negative
* @throws IllegalStateException if the time to idle or time to live was already set
*/
@Nonnull
public CacheBuilder<K, V> expireAfterAccess(long duration, @Nonnull TimeUnit unit) {
Preconditions.checkState(expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns",
expireAfterAccessNanos);
Preconditions.checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit);
this.expireAfterAccessNanos = unit.toNanos(duration);
return this;
}
long getExpireAfterAccessNanos() {
return (expireAfterAccessNanos == UNSET_INT)
? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos;
}
long getRefreshNanos() {
return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos;
}
/**
* Specifies a nanosecond-precision time source for this cache. By default,
* {@link System#nanoTime} is used.
*
* <p>The primary intent of this method is to facilitate testing of caches with a fake or mock
* time source.
*
* @throws IllegalStateException if a ticker was already set
*/
@Nonnull
public CacheBuilder<K, V> ticker(@Nonnull Ticker ticker) {
Preconditions.checkState(this.ticker == null);
this.ticker = Preconditions.checkNotNull(ticker);
return this;
}
Ticker getTicker(boolean recordsTime) {
if (ticker != null) {
return ticker;
}
return recordsTime ? Ticker.systemTicker() : NULL_TICKER;
}
/**
* Specifies a listener instance that caches should notify each time an entry is removed for any
* {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener
* as part of the routine maintenance described in the class documentation above.
*
* <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache
* builder reference; instead use the reference this method <i>returns</i>. At runtime, these
* point to the same instance, but only the returned reference has the correct generic type
* information so as to ensure type safety. For best results, use the standard method-chaining
* idiom illustrated in the class documentation above, configuring a builder and building your
* cache in a single statement. Failure to heed this advice can result in a {@link
* ClassCastException} being thrown by a cache operation at some <i>undefined</i> point in the
* future.
*
* <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to
* the {@code Cache} user, only logged via a {@link Logger}.
*
* @return the cache builder reference that should be used instead of {@code this} for any
* remaining configuration and cache building
* @throws IllegalStateException if a removal listener was already set
*/
@Nonnull
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
@Nonnull RemovalListener<? super K1, ? super V1> listener) {
Preconditions.checkState(this.removalListener == null);
// safely limiting the kinds of caches this can produce
@SuppressWarnings("unchecked")
CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this;
me.removalListener = Preconditions.checkNotNull(listener);
return me;
}
// Make a safe contravariant cast now so we don't have to do it over and over.
@Nullable
@SuppressWarnings("unchecked")
<K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() {
return (RemovalListener<K1, V1>)
MoreObjects.firstNonNull(removalListener, NullListener.INSTANCE);
}
/**
* Builds a cache, which either returns an already-loaded value for a given key or atomically
* computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently
* loading the value for this key, simply waits for that thread to finish and returns its
* loaded value. Note that multiple threads can concurrently load values for distinct keys.
*
* <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be
* invoked again to create multiple independent caches.
*
* @param loader the cache loader used to obtain new values
* @return a cache having the requested features
*/
@Nonnull
public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
@Nonnull CacheLoader<? super K1, V1> loader) {
checkWeightWithWeigher();
return new LocalCache.LocalLoadingCache<>(this, loader);
}
@Nonnull
public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
checkWeightWithWeigher();
checkNonLoadingCache();
return new LocalCache.LocalManualCache<>(this);
}
private void checkNonLoadingCache() {
Preconditions.checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache");
}
private void checkWeightWithWeigher() {
if (weigher == null) {
Preconditions.checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher");
} else {
if (strictParsing) {
Preconditions.checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight");
} else {
if (maximumWeight == UNSET_INT) {
logger.log(Level.WARNING, "ignoring weigher specified without maximumWeight");
}
}
}
}
/**
* Returns a string representation for this CacheBuilder instance. The exact form of the returned
* string is not specified.
*/
@Override
public String toString() {
MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this);
if (initialCapacity != UNSET_INT) {
s.add("initialCapacity", initialCapacity);
}
if (concurrencyLevel != UNSET_INT) {
s.add("concurrencyLevel", concurrencyLevel);
}
if (maximumSize != UNSET_INT) {
s.add("maximumSize", maximumSize);
}
if (maximumWeight != UNSET_INT) {
s.add("maximumWeight", maximumWeight);
}
if (expireAfterWriteNanos != UNSET_INT) {
s.add("expireAfterWrite", expireAfterWriteNanos + "ns");
}
if (expireAfterAccessNanos != UNSET_INT) {
s.add("expireAfterAccess", expireAfterAccessNanos + "ns");
}
if (keyStrength != null) {
s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString()));
}
if (valueStrength != null) {
s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString()));
}
if (keyEquivalence != null) {
s.addValue("keyEquivalence");
}
if (valueEquivalence != null) {
s.addValue("valueEquivalence");
}
if (removalListener != null) {
s.addValue("removalListener");
}
return s.toString();
}
}

View file

@ -1,130 +0,0 @@
package com.dropbox.android.external.cache3;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public abstract class CacheLoader<K, V> {
/**
* Constructor for use by subclasses.
*/
protected CacheLoader() {}
/**
* Computes or retrieves the value corresponding to {@code key}.
*
* @param key the non-null key whose value should be loaded
* @return the value associated with {@code key}; <b>must not be null</b>
* @throws Exception if unable to load the result
* @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
* treated like any other {@code Exception} in all respects except that, when it is caught,
* the thread's interrupt status is set
*/
@Nullable
public abstract V load(K key) throws Exception;
@Nullable
public ListenableFuture<V> reload(@Nonnull K key, @Nonnull V oldValue) throws Exception {
Preconditions.checkNotNull(key);
Preconditions.checkNotNull(oldValue);
return Futures.immediateFuture(load(key));
}
@Nonnull
public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
// This will be caught by getAll(), causing it to fall back to multiple calls to
// LoadingCache.get
throw new UnsupportedLoadingOperationException();
}
/**
* Returns a cache loader based on an <i>existing</i> function instance. Note that there's no need
* to create a <i>new</i> function just to pass it in here; just subclass {@code CacheLoader} and
* implement {@link #load load} instead.
*
* @param function the function to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by passing each key to {@code function}
*/
@Nonnull
public static <K, V> CacheLoader<K, V> from(@Nonnull Function<K, V> function) {
return new FunctionToCacheLoader<>(function);
}
private static final class FunctionToCacheLoader<K, V>
extends CacheLoader<K, V> implements Serializable {
private final Function<K, V> computingFunction;
public FunctionToCacheLoader(@Nonnull Function<K, V> computingFunction) {
this.computingFunction = Preconditions.checkNotNull(computingFunction);
}
@Nullable
@Override
public V load(@Nonnull K key) {
return computingFunction.apply(Preconditions.checkNotNull(key));
}
private static final long serialVersionUID = 0;
}
/**
* Returns a cache loader based on an <i>existing</i> supplier instance. Note that there's no need
* to create a <i>new</i> supplier just to pass it in here; just subclass {@code CacheLoader} and
* implement {@link #load load} instead.
*
* @param supplier the supplier to be used for loading values; must never return {@code null}
* @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
* key
*/
@Nonnull
public static <V> CacheLoader<Object, V> from(@Nonnull Supplier<V> supplier) {
return new SupplierToCacheLoader<>(supplier);
}
private static final class SupplierToCacheLoader<V>
extends CacheLoader<Object, V> implements Serializable {
private final Supplier<V> computingSupplier;
public SupplierToCacheLoader(@Nonnull Supplier<V> computingSupplier) {
this.computingSupplier = Preconditions.checkNotNull(computingSupplier);
}
@Nonnull
@Override
public V load(@Nonnull Object key) {
Preconditions.checkNotNull(key);
return computingSupplier.get();
}
private static final long serialVersionUID = 0;
}
/**
* Exception thrown by {@code loadAll()} to indicate that it is not supported.
*
* @since 19.0
*/
public static final class UnsupportedLoadingOperationException
extends UnsupportedOperationException {
// Package-private because this should only be thrown by loadAll() when it is not overridden.
// Cache implementors may want to catch it but should not need to be able to throw it.
UnsupportedLoadingOperationException() {}
}
/**
* Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}.
*
* @since 11.0
*/
public static final class InvalidCacheLoadException extends RuntimeException {
public InvalidCacheLoadException(String message) {
super(message);
}
}
}

View file

@ -1,16 +0,0 @@
package com.dropbox.android.external.cache3;
import java.util.concurrent.Executor;
import javax.annotation.Nonnull;
enum DirectExecutor implements Executor {
INSTANCE;
@Override public void execute(@Nonnull Runnable command) {
command.run();
}
@Override public String toString() {
return "MoreExecutors.directExecutor()";
}
}

View file

@ -1,185 +0,0 @@
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
import java.io.Serializable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* A strategy for determining whether two instances are considered equivalent. Examples of
* equivalences are the {@linkplain #identity() identity equivalence} and {@linkplain #equals equals
* equivalence}.
*
* @author Bob Lee
* @author Ben Yu
* @author Gregory Kick
* @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility"
* >mostly source-compatible</a> since 4.0)
*/
public abstract class Equivalence<T> {
/**
* Constructor for use by subclasses.
*/
protected Equivalence() {}
/**
* Returns {@code true} if the given objects are considered equivalent.
*
* <p>The {@code equivalent} method implements an equivalence relation on object references:
*
* <ul>
* <li>It is <i>reflexive</i>: for any reference {@code x}, including null, {@code
* equivalent(x, x)} returns {@code true}.
* <li>It is <i>symmetric</i>: for any references {@code x} and {@code y}, {@code
* equivalent(x, y) == equivalent(y, x)}.
* <li>It is <i>transitive</i>: for any references {@code x}, {@code y}, and {@code z}, if
* {@code equivalent(x, y)} returns {@code true} and {@code equivalent(y, z)} returns {@code
* true}, then {@code equivalent(x, z)} returns {@code true}.
* <li>It is <i>consistent</i>: for any references {@code x} and {@code y}, multiple invocations
* of {@code equivalent(x, y)} consistently return {@code true} or consistently return {@code
* false} (provided that neither {@code x} nor {@code y} is modified).
* </ul>
*/
public final boolean equivalent( T a, T b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
return doEquivalent(a, b);
}
/**
* Returns {@code true} if {@code a} and {@code b} are considered equivalent.
*
* <p>Called by {@link #equivalent}. {@code a} and {@code b} are not the same
* object and are not nulls.
*
* @since 10.0 (previously, subclasses would override equivalent())
*/
protected abstract boolean doEquivalent(T a, T b);
/**
* Returns a hash code for {@code t}.
*
* <p>The {@code hash} has the following properties:
* <ul>
* <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of
* {@code hash(x}} consistently return the same value provided {@code x} remains unchanged
* according to the definition of the equivalence. The hash need not remain consistent from
* one execution of an application to another execution of the same application.
* <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code y},
* if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary
* that the hash be distributable across <i>inequivalence</i>. If {@code equivalence(x, y)}
* is false, {@code hash(x) == hash(y)} may still be true.
* <li>{@code hash(null)} is {@code 0}.
* </ul>
*/
public final int hash(@Nullable T t) {
if (t == null) {
return 0;
}
return doHash(t);
}
/**
* Returns a hash code for non-null object {@code t}.
*
* <p>Called by {@link #hash}.
*
* @since 10.0 (previously, subclasses would override hash())
*/
protected abstract int doHash(T t);
/**
* Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
* {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
* value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
* {@code 0} if passed a null value.
*
* @since 13.0
* @since 8.0 (in Equivalences with null-friendly behavior)
* @since 4.0 (in Equivalences)
*/
@Nonnull
public static Equivalence<Object> equals() {
return Equals.INSTANCE;
}
/**
* Returns an equivalence that uses {@code ==} to compare values and {@link
* System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent}
* returns {@code true} if {@code a == b}, including in the case that a and b are both null.
*
* @since 13.0
* @since 4.0 (in Equivalences)
*/
@Nonnull
public static Equivalence<Object> identity() {
return Identity.INSTANCE;
}
static final class Equals extends Equivalence<Object> implements Serializable {
static final Equals INSTANCE = new Equals();
@Override
protected boolean doEquivalent(@Nonnull Object a, Object b) {
return a.equals(b);
}
@Override
protected int doHash(@Nonnull Object o) {
return o.hashCode();
}
@Nonnull
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 1;
}
static final class Identity extends Equivalence<Object> implements Serializable {
static final Identity INSTANCE = new Identity();
@Override
protected boolean doEquivalent(Object a, Object b) {
return false;
}
@Override
protected int doHash(Object o) {
return System.identityHashCode(o);
}
@Nonnull
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 1;
}
}

View file

@ -1,15 +0,0 @@
package com.dropbox.android.external.cache3;
public class ExecutionError extends Error {
/**
* Creates a new instance with the given cause.
*/
public ExecutionError( Error cause) {
super(cause);
}
private static final long serialVersionUID = 0;
}

View file

@ -1,94 +0,0 @@
package com.dropbox.android.external.cache3;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nullable;
public abstract class ForwardingCache<K, V> extends ForwardingObject implements Cache<K, V> {
/** Constructor for use by subclasses. */
protected ForwardingCache() {}
@Override
protected abstract Cache<K, V> delegate();
/**
* @since 11.0
*/
@Nullable
@Override
public V getIfPresent(Object key) {
return delegate().getIfPresent(key);
}
/**
* @since 11.0
*/
@Nullable
@Override
public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException {
return delegate().get(key, valueLoader);
}
/**
* @since 11.0
*/
@Override
public Map<K, V> getAllPresent(Iterable<?> keys) {
return delegate().getAllPresent(keys);
}
/**
* @since 11.0
*/
@Override
public void put(K key, V value) {
delegate().put(key, value);
}
/**
* @since 12.0
*/
@Override
public void putAll(Map<? extends K,? extends V> m) {
delegate().putAll(m);
}
@Override
public void invalidate(Object key) {
delegate().invalidate(key);
}
/**
* @since 11.0
*/
@Override
public void invalidateAll(Iterable<?> keys) {
delegate().invalidateAll(keys);
}
@Override
public void invalidateAll() {
delegate().invalidateAll();
}
@Override
public long size() {
return delegate().size();
}
@Override
public ConcurrentMap<K, V> asMap() {
return delegate().asMap();
}
@Override
public void cleanUp() {
delegate().cleanUp();
}
}

View file

@ -1,20 +0,0 @@
package com.dropbox.android.external.cache3;
public abstract class ForwardingObject {
/** Constructor for use by subclasses. */
protected ForwardingObject() {}
protected abstract Object delegate();
/**
* Returns the string representation generated by the delegate's
* {@code toString} method.
*/
@Override
public String toString() {
return delegate().toString();
}
}

View file

@ -1,16 +0,0 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.dropbox.android.external.cache3;
import javax.annotation.Nullable;
public interface Function<F, T> {
@Nullable
T apply(F var1);
@Override
boolean equals(Object var1);
}

View file

@ -1,208 +0,0 @@
package com.dropbox.android.external.cache3;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public final class Futures {
private Futures() {
}
@Nullable
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) {
if (value == null) {
//noinspection unchecked safe because of erasure
return (ListenableFuture<V>) ImmediateSuccessfulFuture.NULL;
} else {
return new Futures.ImmediateSuccessfulFuture<>(value);
}
}
@Nonnull
public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) {
Preconditions.checkNotNull(throwable);
return new Futures.ImmediateFailedFuture<>(throwable);
}
@Nonnull
public static <I, O> ListenableFuture<O> transform(@Nonnull ListenableFuture<I> input, Function<? super I, ? extends O> function) {
Preconditions.checkNotNull(function);
Futures.ChainingFuture<I,O> output = new Futures.ChainingFuture(input, function);
input.addListener(output, DirectExecutor.INSTANCE);
return output;
}
public static <V, X extends Exception> V getChecked(@Nonnull Future<V> future, Class<X> exceptionClass) throws X {
return FuturesGetChecked.getChecked(future, exceptionClass);
}
public static <V, X extends Exception> V getChecked(@Nonnull Future<V> future, Class<X> exceptionClass, long timeout, @Nonnull TimeUnit unit) throws X {
return FuturesGetChecked.getChecked(future, exceptionClass, timeout, unit);
}
private static final class ChainingFuture<I, O> extends Futures.AbstractChainingFuture<I, O, Function<? super I, ? extends O>> {
ChainingFuture(ListenableFuture<? extends I> inputFuture, Function<? super I, ? extends O> function) {
super(inputFuture, function);
}
@Override
void doTransform(@Nonnull Function<? super I, ? extends O> function, I input) {
this.set(function.apply(input));
}
}
private abstract static class AbstractChainingFuture<I, O, F>
extends AbstractFuture.TrustedFuture<O> implements Runnable {
// In theory, this field might not be visible to a cancel() call in certain circumstances. For
// details, see the comments on the fields of TimeoutFuture.
@Nullable
ListenableFuture<? extends I> inputFuture;
@Nullable
F function;
AbstractChainingFuture(ListenableFuture<? extends I> inputFuture, F function) {
this.inputFuture = Preconditions.checkNotNull(inputFuture);
this.function = Preconditions.checkNotNull(function);
}
@Override
public final void run() {
try {
ListenableFuture<? extends I> localInputFuture = inputFuture;
F localFunction = function;
if (isCancelled() | localInputFuture == null | localFunction == null) {
return;
}
inputFuture = null;
function = null;
I sourceResult;
try {
sourceResult = Uninterruptibles.getUninterruptibly(localInputFuture);
} catch (CancellationException e) {
// Cancel this future and return.
// At this point, inputFuture is cancelled and outputFuture doesn't
// exist, so the value of mayInterruptIfRunning is irrelevant.
cancel(false);
return;
} catch (ExecutionException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
return;
}
doTransform(localFunction, sourceResult);
} catch (UndeclaredThrowableException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
} catch (Throwable t) {
// This exception is irrelevant in this thread, but useful for the
// client
setException(t);
}
}
abstract void doTransform(F function, I result) throws Exception;
@Override
final void done() {
this.maybePropagateCancellation(this.inputFuture);
this.inputFuture = null;
}
}
private static class ImmediateFailedFuture<V> extends Futures.ImmediateFuture<V> {
private final Throwable thrown;
ImmediateFailedFuture(Throwable thrown) {
super();
this.thrown = thrown;
}
@Override @Nonnull
public V get() throws ExecutionException {
throw new ExecutionException(this.thrown);
}
}
private static class ImmediateSuccessfulFuture<V> extends Futures.ImmediateFuture<V> {
@Nullable
static final Futures.ImmediateSuccessfulFuture<Object> NULL = new Futures.ImmediateSuccessfulFuture<>(null);
private final V value;
ImmediateSuccessfulFuture( V value) {
super();
this.value = value;
}
@Override
public V get() {
return this.value;
}
}
private abstract static class ImmediateFuture<V> implements ListenableFuture<V> {
private static final Logger log = Logger.getLogger(Futures.ImmediateFuture.class.getName());
private ImmediateFuture() {
}
@Override
public void addListener(@Nonnull Runnable listener, @Nonnull Executor executor) {
Preconditions.checkNotNull(listener, "Runnable was null.");
Preconditions.checkNotNull(executor, "Executor was null.");
try {
executor.execute(listener);
} catch (RuntimeException var4) {
log.log(Level.SEVERE, "RuntimeException while executing runnable " + listener + " with executor " + executor, var4);
}
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public abstract V get() throws ExecutionException;
@Override
public V get(long timeout, @Nonnull TimeUnit unit) throws ExecutionException {
Preconditions.checkNotNull(unit);
return this.get();
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
}
}

View file

@ -1,141 +0,0 @@
package com.dropbox.android.external.cache3;
import java.lang.ref.WeakReference;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nonnull;
import static java.lang.Thread.currentThread;
final class FuturesGetChecked {
static <V, X extends Exception> V getChecked(@Nonnull Future<V> future, Class<X> exceptionClass) throws X {
return getChecked(bestGetCheckedTypeValidator(), future, exceptionClass);
}
/**
* Implementation of {@link Futures#getChecked(Future, Class)}.
*/
static <V, X extends Exception> V getChecked(
@Nonnull GetCheckedTypeValidator validator, @Nonnull Future<V> future, Class<X> exceptionClass) throws X {
validator.validateClass(exceptionClass);
try {
return future.get();
} catch (InterruptedException e) {
currentThread().interrupt();
throw new RuntimeException();
} catch (ExecutionException e) {
throw new RuntimeException();
}
}
/**
* Implementation of {@link Futures#getChecked(Future, Class, long, TimeUnit)}.
*/
static <V, X extends Exception> V getChecked(
@Nonnull Future<V> future, Class<X> exceptionClass, long timeout, @Nonnull TimeUnit unit) throws X {
// TODO(cpovirk): benchmark a version of this method that accepts a GetCheckedTypeValidator
bestGetCheckedTypeValidator().validateClass(exceptionClass);
try {
return future.get(timeout, unit);
} catch (InterruptedException e) {
currentThread().interrupt();
throw new RuntimeException();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
throw new RuntimeException(e);
}
}
interface GetCheckedTypeValidator {
void validateClass(Class<? extends Exception> exceptionClass);
}
@Nonnull
private static GetCheckedTypeValidator bestGetCheckedTypeValidator() {
return GetCheckedTypeValidatorHolder.BEST_VALIDATOR;
}
@Nonnull
static GetCheckedTypeValidator weakSetValidator() {
return GetCheckedTypeValidatorHolder.WeakSetValidator.INSTANCE;
}
/**
* Provides a check of whether an exception type is valid for use with
* {@link FuturesGetChecked#getChecked(Future, Class)}, possibly using caching.
*
* <p>Uses reflection to gracefully fall back to when certain implementations aren't available.
*/
private FuturesGetChecked() {}
static class GetCheckedTypeValidatorHolder {
static final String CLASS_VALUE_VALIDATOR_NAME =
GetCheckedTypeValidatorHolder.class.getName() + "$ClassValueValidator";
static final GetCheckedTypeValidator BEST_VALIDATOR = getBestValidator();
enum WeakSetValidator implements GetCheckedTypeValidator {
INSTANCE;
/*
* Static final fields are presumed to be fastest, based on our experience with
* UnsignedBytesBenchmark. TODO(cpovirk): benchmark this
*/
/*
* A CopyOnWriteArraySet<WeakReference> is faster than a newSetFromMap of a MapMaker map with
* weakKeys() and concurrencyLevel(1), even up to at least 12 cached exception types.
*/
private static final Set<WeakReference<Class<? extends Exception>>> validClasses =
new CopyOnWriteArraySet<>();
@Override
public void validateClass(@Nonnull Class<? extends Exception> exceptionClass) {
for (WeakReference<Class<? extends Exception>> knownGood : validClasses) {
if (exceptionClass.equals(knownGood.get())) {
return;
}
// TODO(cpovirk): if reference has been cleared, remove it?
}
/*
* It's very unlikely that any loaded Futures class will see getChecked called with more
* than a handful of exceptions. But it seems prudent to set a cap on how many we'll cache.
* This avoids out-of-control memory consumption, and it keeps the cache from growing so
* large that doing the lookup is noticeably slower than redoing the work would be.
*
* Ideally we'd have a real eviction policy, but until we see a problem in practice, I hope
* that this will suffice. I have not even benchmarked with different size limits.
*/
if (validClasses.size() > 1000) {
validClasses.clear();
}
validClasses.add(new WeakReference<Class<? extends Exception>>(exceptionClass));
}
}
/**
* Returns the ClassValue-using validator, or falls back to the "weak Set" implementation if
* unable to do so.
*/
@Nonnull
static GetCheckedTypeValidator getBestValidator() {
try {
Class<?> theClass = Class.forName(CLASS_VALUE_VALIDATOR_NAME);
return (GetCheckedTypeValidator) theClass.getEnumConstants()[0];
} catch (Throwable t) { // ensure we really catch *everything*
return weakSetValidator();
}
}
}
}

View file

@ -1,25 +0,0 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
public interface ListenableFuture<V> extends Future<V> {
void addListener(Runnable listener, Executor executor);
}

View file

@ -1,132 +0,0 @@
package com.dropbox.android.external.cache3;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nullable;
public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {
/**
* Returns the value associated with {@code key} in this cache, first loading that value if
* necessary. No observable state associated with this cache is modified until loading completes.
*
* <p>If another call to {@link #get} or {@link #getUnchecked} is currently loading the value for
* {@code key}, simply waits for that thread to finish and returns its loaded value. Note that
* multiple threads can concurrently load values for distinct keys.
*
* <p>Caches loaded by a {@link CacheLoader} will call {@link CacheLoader#load} to load new values
* into the cache. Newly loaded values are added to the cache using
* {@code Cache.asMap().putIfAbsent} after loading has completed; if another value was associated
* with {@code key} while the new value was loading then a removal notification will be sent for
* the new value.
*
* <p>If the cache loader associated with this cache is known not to throw checked
* exceptions, then prefer {@link #getUnchecked} over this method.
*
* @throws ExecutionException if a checked exception was thrown while loading the value. ({@code
* ExecutionException} is thrown <a
* href="https://github.com/google/guava/wiki/CachesExplained#interruption">even if
* computation was interrupted by an {@code InterruptedException}</a>.)
* @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
* value
* @throws ExecutionError if an error was thrown while loading the value
*/
@Nullable
V get(K key) throws ExecutionException;
/**
* Returns the value associated with {@code key} in this cache, first loading that value if
* necessary. No observable state associated with this cache is modified until loading
* completes. Unlike {@link #get}, this method does not throw a checked exception, and thus should
* only be used in situations where checked exceptions are not thrown by the cache loader.
*
* <p>If another call to {@link #get} or {@link #getUnchecked} is currently loading the value for
* {@code key}, simply waits for that thread to finish and returns its loaded value. Note that
* multiple threads can concurrently load values for distinct keys.
*
* <p>Caches loaded by a {@link CacheLoader} will call {@link CacheLoader#load} to load new values
* into the cache. Newly loaded values are added to the cache using
* {@code Cache.asMap().putIfAbsent} after loading has completed; if another value was associated
* with {@code key} while the new value was loading then a removal notification will be sent for
* the new value.
*
* <p><b>Warning:</b> this method silently converts checked exceptions to unchecked exceptions,
* and should not be used with cache loaders which throw checked exceptions. In such cases use
* {@link #get} instead.
*
* @throws UncheckedExecutionException if an exception was thrown while loading the value. (As
* explained in the last paragraph above, this should be an unchecked exception only.)
* @throws ExecutionError if an error was thrown while loading the value
*/
@Nullable
V getUnchecked(K key);
/**
* Returns a map of the values associated with {@code keys}, creating or retrieving those values
* if necessary. The returned map contains entries that were already cached, combined with newly
* loaded entries; it will never contain null keys or values.
*
* <p>Caches loaded by a {@link CacheLoader} will issue a single request to
* {@link CacheLoader#loadAll} for all keys which are not already present in the cache. All
* entries returned by {@link CacheLoader#loadAll} will be stored in the cache, over-writing
* any previously cached values. This method will throw an exception if
* {@link CacheLoader#loadAll} returns {@code null}, returns a map containing null keys or values,
* or fails to return an entry for each requested key.
*
* <p>Note that duplicate elements in {@code keys}, as determined by {@link Object#equals}, will
* be ignored.
*
* @throws ExecutionException if a checked exception was thrown while loading the value. ({@code
* ExecutionException} is thrown <a
* href="https://github.com/google/guava/wiki/CachesExplained#interruption">even if
* computation was interrupted by an {@code InterruptedException}</a>.)
* @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
* values
* @throws ExecutionError if an error was thrown while loading the values
* @since 11.0
*/
Map<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException;
/**
* @deprecated Provided to satisfy the {@code Function} interface; use {@link #get} or
* {@link #getUnchecked} instead.
* @throws UncheckedExecutionException if an exception was thrown while loading the value. (As
* described in the documentation for {@link #getUnchecked}, {@code LoadingCache} should be
* used as a {@code Function} only with cache loaders that throw only unchecked exceptions.)
*/
@Nullable
@Deprecated
@Override
V apply(K key);
/**
* Loads a new value for key {@code key}, possibly asynchronously. While the new value is loading
* the previous value (if any) will continue to be returned by {@code get(key)} unless it is
* evicted. If the new value is loaded successfully it will replace the previous value in the
* cache; if an exception is thrown while refreshing the previous value will remain, <i>and the
* exception will be logged (using {@link java.util.logging.Logger}) and swallowed</i>.
*
* <p>Caches loaded by a {@link CacheLoader} will call {@link CacheLoader#reload} if the
* cache currently contains a value for {@code key}, and {@link CacheLoader#load} otherwise.
* Loading is asynchronous only if {@link CacheLoader#reload} was overridden with an
* asynchronous implementation.
*
* <p>Returns without doing anything if another thread is currently loading the value for
* {@code key}. If the cache loader associated with this cache performs refresh asynchronously
* then this method may return before refresh completes.
*
* @since 11.0
*/
void refresh(K key);
/**
* {@inheritDoc}
*
* <p><b>Note that although the view <i>is</i> modifiable, no method on the returned map will ever
* cause entries to be automatically loaded.</b>
*/
@Override
ConcurrentMap<K, V> asMap();
}

File diff suppressed because it is too large Load diff

View file

@ -1,384 +0,0 @@
/*
* Copyright (C) 2014 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
import java.util.Arrays;
import javax.annotation.Nonnull;
public final class MoreObjects {
public static <T> T firstNonNull(T first, T second) {
return first != null ? first : Preconditions.checkNotNull(second);
}
/**
* Creates an instance of {@link ToStringHelper}.
*
* <p>This is helpful for implementing {@link Object#toString()}.
* Specification by example: <pre> {@code
* // Returns "ClassName{}"
* MoreObjects.toStringHelper(this)
* .toString();
*
* // Returns "ClassName{x=1}"
* MoreObjects.toStringHelper(this)
* .add("x", 1)
* .toString();
*
* // Returns "MyObject{x=1}"
* MoreObjects.toStringHelper("MyObject")
* .add("x", 1)
* .toString();
*
* // Returns "ClassName{x=1, y=foo}"
* MoreObjects.toStringHelper(this)
* .add("x", 1)
* .add("y", "foo")
* .toString();
*
* // Returns "ClassName{x=1}"
* MoreObjects.toStringHelper(this)
* .omitNullValues()
* .add("x", 1)
* .add("y", null)
* .toString();
* }}</pre>
*
* <p>Note that in GWT, class names are often obfuscated.
*
* @param self the object to generate the string for (typically {@code this}), used only for its
* class name
* @since 18.0 (since 2.0 as {@code Objects.toStringHelper()}).
*/
@Nonnull
public static ToStringHelper toStringHelper(@Nonnull Object self) {
return new ToStringHelper(self.getClass().getSimpleName());
}
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Creates an instance of {@link ToStringHelper} in the same manner as {@link
// * #toStringHelper(Object)}, but using the simple name of {@code clazz} instead of using an
// * instance's {@link Object#getClass()}.
// *
// * <p>Note that in GWT, class names are often obfuscated.
// *
// * @param clazz the {@link Class} of the instance
// * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
// */
// public static ToStringHelper toStringHelper(Class<?> clazz) {
// return new ToStringHelper(clazz.getSimpleName());
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Creates an instance of {@link ToStringHelper} in the same manner as {@link
// * #toStringHelper(Object)}, but using {@code className} instead of using an instance's {@link
// * Object#getClass()}.
// *
// * @param className the name of the instance type
// * @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
// */
// public static ToStringHelper toStringHelper(String className) {
// return new ToStringHelper(className);
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
/**
* Support class for {@link MoreObjects#toStringHelper}.
*
* @author Jason Lee
* @since 18.0 (since 2.0 as {@code Objects.ToStringHelper}).
*/
public static final class ToStringHelper {
private final String className;
@Nonnull
private ValueHolder holderHead = new ValueHolder();
@Nonnull
private ValueHolder holderTail = holderHead;
private boolean omitNullValues = false;
/**
* Use {@link MoreObjects#toStringHelper(Object)} to create an instance.
*/
private ToStringHelper(@Nonnull String className) {
this.className = Preconditions.checkNotNull(className);
}
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Configures the {@link ToStringHelper} so {@link #toString()} will ignore
// * properties with null value. The order of calling this method, relative
// * to the {@code add()}/{@code addValue()} methods, is not significant.
// *
// * @since 18.0 (since 12.0 as {@code Objects.ToStringHelper.omitNullValues()}).
// */
// public ToStringHelper omitNullValues() {
// omitNullValues = true;
// return this;
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format. If {@code value} is {@code null}, the string {@code "null"}
* is used, unless {@link #omitNullValues()} is called, in which case this
* name/value pair will not be added.
*/
@Nonnull
public ToStringHelper add(@Nonnull String name, Object value) {
return addHolder(name, value);
}
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds a name/value pair to the formatted output in {@code name=value}
// * format.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
// */
// public ToStringHelper add(String name, boolean value) {
// return addHolder(name, String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds a name/value pair to the formatted output in {@code name=value}
// * format.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
// */
// public ToStringHelper add(String name, char value) {
// return addHolder(name, String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds a name/value pair to the formatted output in {@code name=value}
// * format.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
// */
// public ToStringHelper add(String name, double value) {
// return addHolder(name, String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds a name/value pair to the formatted output in {@code name=value}
// * format.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
// */
// public ToStringHelper add(String name, float value) {
// return addHolder(name, String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@Nonnull
public ToStringHelper add(@Nonnull String name, int value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@Nonnull
public ToStringHelper add(@Nonnull String name, long value) {
return addHolder(name, String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, Object)} instead
* and give value a readable name.
*/
@Nonnull
public ToStringHelper addValue(Object value) {
return addHolder(value);
}
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds an unnamed value to the formatted output.
// *
// * <p>It is strongly encouraged to use {@link #add(String, boolean)} instead
// * and give value a readable name.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
// */
// public ToStringHelper addValue(boolean value) {
// return addHolder(String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds an unnamed value to the formatted output.
// *
// * <p>It is strongly encouraged to use {@link #add(String, char)} instead
// * and give value a readable name.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
// */
// public ToStringHelper addValue(char value) {
// return addHolder(String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds an unnamed value to the formatted output.
// *
// * <p>It is strongly encouraged to use {@link #add(String, double)} instead
// * and give value a readable name.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
// */
// public ToStringHelper addValue(double value) {
// return addHolder(String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds an unnamed value to the formatted output.
// *
// * <p>It is strongly encouraged to use {@link #add(String, float)} instead
// * and give value a readable name.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
// */
// public ToStringHelper addValue(float value) {
// return addHolder(String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds an unnamed value to the formatted output.
// *
// * <p>It is strongly encouraged to use {@link #add(String, int)} instead
// * and give value a readable name.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
// */
// public ToStringHelper addValue(int value) {
// return addHolder(String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Adds an unnamed value to the formatted output.
// *
// * <p>It is strongly encouraged to use {@link #add(String, long)} instead
// * and give value a readable name.
// *
// * @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
// */
// public ToStringHelper addValue(long value) {
// return addHolder(String.valueOf(value));
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
/**
* Returns a string in the format specified by
* {@link MoreObjects#toStringHelper(Object)}.
*
* <p>After calling this method, you can keep adding more properties to later
* call toString() again and get a more complete representation of the
* same object; but properties cannot be removed, so this only allows
* limited reuse of the helper instance. The helper allows duplication of
* properties (multiple name/value pairs with the same name can be added).
*/
@Override
public String toString() {
// create a copy to keep it consistent in case value changes
boolean omitNullValuesSnapshot = omitNullValues;
String nextSeparator = "";
StringBuilder builder = new StringBuilder(32).append(className).append('{');
for (ValueHolder valueHolder = holderHead.next;
valueHolder != null;
valueHolder = valueHolder.next) {
Object value = valueHolder.value;
if (!omitNullValuesSnapshot || value != null) {
builder.append(nextSeparator);
nextSeparator = ", ";
if (valueHolder.name != null) {
builder.append(valueHolder.name).append('=');
}
if (value != null && value.getClass().isArray()) {
Object[] objectArray = {value};
String arrayString = Arrays.deepToString(objectArray);
builder.append(arrayString.substring(1, arrayString.length() - 1));
} else {
builder.append(value);
}
}
}
return builder.append('}').toString();
}
@Nonnull
private ValueHolder addHolder() {
ValueHolder valueHolder = new ValueHolder();
holderTail = holderTail.next = valueHolder;
return valueHolder;
}
@Nonnull
private ToStringHelper addHolder(Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
return this;
}
@Nonnull
private ToStringHelper addHolder(@Nonnull String name, Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
valueHolder.name = Preconditions.checkNotNull(name);
return this;
}
private static final class ValueHolder {
String name;
Object value;
ValueHolder next;
}
}
private MoreObjects() {}
}

View file

@ -1,53 +0,0 @@
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
/**
* Helper functions that can operate on any {@code Object}.
*
* <p>See the Guava User Guide on <a
* href="https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained">writing
* {@code Object} methods with {@code Objects}</a>.
*
* @author Laurence Gonsalves
* @since 2.0
*/
public final class Objects {
private Objects() {}
/**
* Determines whether two possibly-null objects are equal. Returns:
*
* <ul>
* <li>{@code true} if {@code a} and {@code b} are both null.
* <li>{@code true} if {@code a} and {@code b} are both non-null and they are
* equal according to {@link Object#equals(Object)}.
* <li>{@code false} in all other situations.
* </ul>
*
* <p>This assumes that any non-null objects passed to this function conform
* to the {@code equals()} contract.
*
* <p><b>Note for Java 7 and later:</b> This method should be treated as
* deprecated; use {@link java.util.Objects#equals} instead.
*/
public static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
}

View file

@ -1,31 +0,0 @@
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* @author Jesse Wilson
*/
final class Platform {
private Platform() {}
/** Calls {@link System#nanoTime()}. */
static long systemNanoTime() {
return System.nanoTime();
}
}

View file

@ -1,150 +0,0 @@
/*
* Copyright (C) 2016 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
import static java.lang.String.format;
/**
* An adaptation of Guava's {@code com.google.common.base.Preconditions} that is specially tailored
* to support checks applied in Dagger's generated code.
*/
public final class Preconditions {
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, String errorMessage) {
if (reference == null) {
throw new NullPointerException(errorMessage);
}
return reference;
}
private Preconditions() {}
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
* in square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
* {@code errorMessageArgs} is null (don't let this happen)
*/
public static void checkArgument(
boolean expression,
String errorMessageTemplate,
Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
}
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
* string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the check fail. The
* message is formed by replacing each {@code %s} placeholder in the template with an
* argument. These are matched by position - the first {@code %s} gets {@code
* errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
* in square braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message template. Arguments
* are converted to strings using {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
* {@code errorMessageArgs} is null (don't let this happen)
*/
public static void checkState(
boolean expression,
String errorMessageTemplate,
Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs));
}
}
}

View file

@ -1,69 +0,0 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
/**
* The reason why a cached entry was removed.
*
* @author Charles Fry
* @since 10.0
*/
public enum RemovalCause {
EXPLICIT {
@Override
boolean wasEvicted() {
return false;
}
},
REPLACED {
@Override
boolean wasEvicted() {
return false;
}
},
COLLECTED {
@Override
boolean wasEvicted() {
return true;
}
},
EXPIRED {
@Override
boolean wasEvicted() {
return true;
}
},
SIZE {
@Override
boolean wasEvicted() {
return true;
}
};
/**
* Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
* {@link #EXPLICIT} nor {@link #REPLACED}).
*/
abstract boolean wasEvicted();
}

View file

@ -1,13 +0,0 @@
package com.dropbox.android.external.cache3;
public interface RemovalListener<K, V> {
/**
* Notifies the listener that a removal occurred at some point in the past.
*
* <p>This does not always signify that the key is now absent from the cache,
* as it may have already been re-added.
*/
// Technically should accept RemovalNotification<? extends K, ? extends V>, but because
// RemovalNotification is guaranteed covariant, let's make users' lives simpler.
void onRemoval(RemovalNotification<K, V> notification);
}

View file

@ -1,93 +0,0 @@
package com.dropbox.android.external.cache3;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static com.dropbox.android.external.cache3.Preconditions.checkNotNull;
public final class RemovalNotification<K, V> implements Map.Entry<K, V> {
private final K key;
private final V value;
@Nullable
private final RemovalCause cause;
/**
* Creates a new {@code RemovalNotification} for the given {@code key}/{@code value} pair, with
* the given {@code cause} for the removal. The {@code key} and/or {@code value} may be
* {@code null} if they were already garbage collected.
*
* @since 19.0
*/
@Nonnull
public static <K, V> RemovalNotification<K, V> create(
K key, V value, @Nonnull RemovalCause cause) {
return new RemovalNotification(key, value, cause);
}
private RemovalNotification( K key, V value, @Nonnull RemovalCause cause) {
this.key = key;
this.value = value;
this.cause = checkNotNull(cause);
}
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Returns the cause for which the entry was removed.
// */
// public RemovalCause getCause() {
// return cause;
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither
// * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}).
// */
// public boolean wasEvicted() {
// return cause.wasEvicted();
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
@Override public K getKey() {
return key;
}
@Override public V getValue() {
return value;
}
@Nonnull
@Override public final V setValue(V value) {
throw new UnsupportedOperationException();
}
@Override public boolean equals( Object object) {
if (object instanceof Map.Entry) {
Map.Entry<?, ?> that = (Map.Entry<?, ?>) object;
return Objects.equal(this.getKey(), that.getKey())
&& Objects.equal(this.getValue(), that.getValue());
}
return false;
}
@Override public int hashCode() {
K k = getKey();
V v = getValue();
return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
}
/**
* Returns a string representation of the form <code>{key}={value}</code>.
*/
@Nonnull
@Override public String toString() {
return getKey() + "=" + getValue();
}
// --Commented out by Inspection (11/29/16, 5:04 PM):private static final long serialVersionUID = 0;
}

View file

@ -1,34 +0,0 @@
package com.dropbox.android.external.cache3;
import javax.annotation.Nonnull;
public final class SettableFuture<V> extends AbstractFuture.TrustedFuture<V> {
/**
* Creates a new {@code SettableFuture} in the default state.
*/
@Nonnull
public static <V> SettableFuture<V> create() {
return new SettableFuture<>();
}
/**
* Explicit private constructor, use the {@link #create} factory method to
* create instances of {@code SettableFuture}.
*/
private SettableFuture() {}
@Override public boolean set( V value) {
return super.set(value);
}
@Override public boolean setException(Throwable throwable) {
return super.setException(throwable);
}
@Override
public boolean setFuture(@Nonnull ListenableFuture<? extends V> future) {
return super.setFuture(future);
}
}

View file

@ -1,213 +0,0 @@
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import static com.dropbox.android.external.cache3.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* An object that measures elapsed time in nanoseconds. It is useful to measure
* elapsed time using this class instead of direct calls to {@link
* System#nanoTime} for a few reasons:
* <p>
* <ul>
* <li>An alternate time source can be substituted, for testing or performance
* reasons.
* <li>As documented by {@code nanoTime}, the value returned has no absolute
* meaning, and can only be interpreted as relative to another timestamp
* returned by {@code nanoTime} at a different time. {@code Stopwatch} is a
* more effective abstraction because it exposes only these relative values,
* not the absolute ones.
* </ul>
* <p>
* <p>Basic usage:
* <pre>
* Stopwatch stopwatch = Stopwatch.{@link #createStarted createStarted}();
* doSomething();
* stopwatch.{@link #stop stop}(); // optional
*
* long millis = stopwatch.elapsed(MILLISECONDS);
*
* log.info("time: " + stopwatch); // formatted string like "12.3 ms"</pre>
* <p>
* <p>Stopwatch methods are not idempotent; it is an error to start or stop a
* stopwatch that is already in the desired state.
* <p>
* <p>When testing code that uses this class, use
* {@link #createUnstarted(Ticker)} or {@link #createStarted(Ticker)} to
* supply a fake or mock ticker.
* <!-- TODO(kevinb): restore the "such as" --> This allows you to
* simulate any valid behavior of the stopwatch.
* <p>
* <p><b>Note:</b> This class is not thread-safe.
*
* @author Kevin Bourrillion
* @since 10.0
*/
public final class Stopwatch {
@Nonnull
private final Ticker ticker;
private boolean isRunning;
private long elapsedNanos;
private long startTick;
/**
* Creates (but does not start) a new stopwatch using {@link System#nanoTime}
* as its time source.
*
* @since 15.0
*/
@Nonnull
public static Stopwatch createUnstarted() {
return new Stopwatch();
}
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Creates (but does not start) a new stopwatch, using the specified time
// * source.
// *
// * @since 15.0
// */
// public static Stopwatch createUnstarted(Ticker ticker) {
// return new Stopwatch(ticker);
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
/**
* Creates (and starts) a new stopwatch using {@link System#nanoTime}
* as its time source.
*
* @since 15.0
*/
@Nonnull
public static Stopwatch createStarted() {
return new Stopwatch().start();
}
Stopwatch() {
this.ticker = Ticker.systemTicker();
}
/**
* Starts the stopwatch.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already running.
*/
@Nonnull
public Stopwatch start() {
checkState(!isRunning, "This stopwatch is already running.");
isRunning = true;
startTick = ticker.read();
return this;
}
/**
* Stops the stopwatch. Future reads will return the fixed duration that had
* elapsed up to this point.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already stopped.
*/
@Nonnull
public Stopwatch stop() {
long tick = ticker.read();
checkState(isRunning, "This stopwatch is already stopped.");
isRunning = false;
elapsedNanos += tick - startTick;
return this;
}
private long elapsedNanos() {
return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos;
}
/**
* Returns a string representation of the current elapsed time.
*/
@Override
public String toString() {
long nanos = elapsedNanos();
TimeUnit unit = chooseUnit(nanos);
double value = (double) nanos / NANOSECONDS.convert(1, unit);
// Too bad this functionality is not exposed as a regular method call
return String.format(Locale.ROOT, "%.4g %s", value, abbreviate(unit));
}
@Nonnull
private static TimeUnit chooseUnit(long nanos) {
if (DAYS.convert(nanos, NANOSECONDS) > 0) {
return DAYS;
}
if (HOURS.convert(nanos, NANOSECONDS) > 0) {
return HOURS;
}
if (MINUTES.convert(nanos, NANOSECONDS) > 0) {
return MINUTES;
}
if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
return SECONDS;
}
if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
return MILLISECONDS;
}
if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
return MICROSECONDS;
}
return NANOSECONDS;
}
private static String abbreviate(@Nonnull TimeUnit unit) {
switch (unit) {
case NANOSECONDS:
return "ns";
case MICROSECONDS:
return "\u03bcs"; // μs
case MILLISECONDS:
return "ms";
case SECONDS:
return "s";
case MINUTES:
return "min";
case HOURS:
return "h";
case DAYS:
return "d";
default:
throw new AssertionError();
}
}
}

View file

@ -1,13 +0,0 @@
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.dropbox.android.external.cache3;
import javax.annotation.Nonnull;
public interface Supplier<T> {
@Nonnull
T get();
}

View file

@ -1,51 +0,0 @@
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dropbox.android.external.cache3;
import javax.annotation.Nonnull;
public abstract class Ticker {
/**
* Constructor for use by subclasses.
*/
protected Ticker() {}
/**
* Returns the number of nanoseconds elapsed since this ticker's fixed
* point of reference.
*/
public abstract long read();
/**
* A ticker that reads the current time using {@link System#nanoTime}.
*
* @since 10.0
*/
@Nonnull
public static Ticker systemTicker() {
return SYSTEM_TICKER;
}
private static final Ticker SYSTEM_TICKER =
new Ticker() {
@Override
public long read() {
return Platform.systemNanoTime();
}
};
}

View file

@ -1,37 +0,0 @@
package com.dropbox.android.external.cache3;
public class UncheckedExecutionException extends RuntimeException {
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Creates a new instance with {@code null} as its detail message.
// */
// protected UncheckedExecutionException() {}
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Creates a new instance with the given detail message.
// */
// protected UncheckedExecutionException( String message) {
// super(message);
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
// --Commented out by Inspection START (11/29/16, 5:04 PM):
// /**
// * Creates a new instance with the given detail message and cause.
// */
// public UncheckedExecutionException( String message, Throwable cause) {
// super(message, cause);
// }
// --Commented out by Inspection STOP (11/29/16, 5:04 PM)
/**
* Creates a new instance with the given cause.
*/
public UncheckedExecutionException( Throwable cause) {
super(cause);
}
private static final long serialVersionUID = 0;
}

View file

@ -1,41 +0,0 @@
package com.dropbox.android.external.cache3;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.annotation.Nonnull;
public final class Uninterruptibles {
/**
* Invokes {@code future.}{@link Future#get() get()} uninterruptibly.
* To get uninterruptibility and remove checked exceptions, see
* @link Futures#getUnchecked}.
*
* <p>If instead, you wish to treat {@link InterruptedException} uniformly
* with other exceptions, see @link Futures#getChecked(Future, Class)
* Futures.getChecked}.
*
* @throws ExecutionException if the computation threw an exception
*/
public static <V> V getUninterruptibly(@Nonnull Future<V> future)
throws ExecutionException {
boolean interrupted = false;
try {
while (true) {
try {
return future.get();
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
private Uninterruptibles() {}
}

View file

@ -1,20 +0,0 @@
package com.dropbox.android.external.cache3;
import java.util.Iterator;
public abstract class UnmodifiableIterator<E> implements Iterator<E> {
/** Constructor for use by subclasses. */
protected UnmodifiableIterator() {}
/**
* Guaranteed to throw an exception and leave the underlying data unmodified.
*
* @throws UnsupportedOperationException always
* @deprecated Unsupported operation.
*/
@Deprecated
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
}

View file

@ -1,12 +0,0 @@
package com.dropbox.android.external.cache3;
public interface Weigher<K, V> {
/**
* Returns the weight of a cache entry. There is no unit for entry weights; rather they are simply
* relative to each other.
*
* @return the weight of the entry; must be non-negative
*/
int weigh(K key, V value);
}

View file

@ -1 +0,0 @@
/build

View file

@ -1,249 +0,0 @@
public abstract interface class com/dropbox/android/external/fs3/AllPersister : com/dropbox/android/external/fs3/DiskAllErase, com/dropbox/android/external/fs3/DiskAllRead, com/dropbox/android/external/fs3/Persister {
public abstract fun deleteAll (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public abstract fun read (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public abstract fun readAll (Lkotlinx/coroutines/CoroutineScope;Ljava/lang/String;)Lkotlinx/coroutines/channels/ReceiveChannel;
public abstract fun write (Ljava/lang/Object;Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public abstract interface class com/dropbox/android/external/fs3/BufferedSourceAdapter {
public abstract fun toJson (Ljava/lang/Object;)Lokio/BufferedSource;
}
public abstract interface class com/dropbox/android/external/fs3/DiskAllErase {
public abstract fun deleteAll (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public abstract interface class com/dropbox/android/external/fs3/DiskAllRead {
public abstract fun readAll (Lkotlinx/coroutines/CoroutineScope;Ljava/lang/String;)Lkotlinx/coroutines/channels/ReceiveChannel;
}
public abstract interface class com/dropbox/android/external/fs3/DiskErase {
public abstract fun delete (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public abstract interface class com/dropbox/android/external/fs3/DiskRead {
public abstract fun read (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public abstract interface class com/dropbox/android/external/fs3/DiskWrite {
public abstract fun write (Ljava/lang/Object;Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public final class com/dropbox/android/external/fs3/FSAllEraser : com/dropbox/android/external/fs3/DiskAllErase {
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)V
public fun deleteAll (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public final fun getFileSystem$filesystem ()Lcom/dropbox/android/external/fs3/filesystem/FileSystem;
}
public final class com/dropbox/android/external/fs3/FSAllReader : com/dropbox/android/external/fs3/DiskAllRead {
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)V
public final fun getFileSystem$filesystem ()Lcom/dropbox/android/external/fs3/filesystem/FileSystem;
public fun readAll (Lkotlinx/coroutines/CoroutineScope;Ljava/lang/String;)Lkotlinx/coroutines/channels/ReceiveChannel;
}
public final class com/dropbox/android/external/fs3/FSEraser : com/dropbox/android/external/fs3/DiskErase {
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;)V
public fun delete (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public final fun getFileSystem$filesystem ()Lcom/dropbox/android/external/fs3/filesystem/FileSystem;
public final fun getPathResolver$filesystem ()Lcom/dropbox/android/external/fs3/PathResolver;
}
public class com/dropbox/android/external/fs3/FSReader : com/dropbox/android/external/fs3/DiskRead {
public static final field Companion Lcom/dropbox/android/external/fs3/FSReader$Companion;
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;)V
public final fun getFileSystem$filesystem ()Lcom/dropbox/android/external/fs3/filesystem/FileSystem;
public fun read (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public final class com/dropbox/android/external/fs3/FSReader$Companion {
}
public class com/dropbox/android/external/fs3/FSWriter : com/dropbox/android/external/fs3/DiskWrite {
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;)V
public final fun getFileSystem$filesystem ()Lcom/dropbox/android/external/fs3/filesystem/FileSystem;
public synthetic fun write (Ljava/lang/Object;Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public fun write (Ljava/lang/Object;Lokio/BufferedSource;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public final class com/dropbox/android/external/fs3/FileSystemPersister : com/dropbox/android/external/fs3/Persister {
public static final field Companion Lcom/dropbox/android/external/fs3/FileSystemPersister$Companion;
public synthetic fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;Lkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun read (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public synthetic fun write (Ljava/lang/Object;Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public fun write (Ljava/lang/Object;Lokio/BufferedSource;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public final class com/dropbox/android/external/fs3/FileSystemPersister$Companion {
public final fun create (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;)Lcom/dropbox/android/external/fs3/Persister;
}
public final class com/dropbox/android/external/fs3/FileSystemRecordPersister : com/dropbox/android/external/fs3/Persister, com/dropbox/android/external/fs3/RecordProvider {
public static final field Companion Lcom/dropbox/android/external/fs3/FileSystemRecordPersister$Companion;
public synthetic fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;JLkotlin/jvm/internal/DefaultConstructorMarker;)V
public fun getRecordState (Ljava/lang/Object;)Lcom/dropbox/android/external/fs3/RecordState;
public fun read (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public synthetic fun write (Ljava/lang/Object;Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public fun write (Ljava/lang/Object;Lokio/BufferedSource;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public final class com/dropbox/android/external/fs3/FileSystemRecordPersister$Companion {
public final fun create-SxA4cEA (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;J)Lcom/dropbox/android/external/fs3/FileSystemRecordPersister;
}
public abstract interface class com/dropbox/android/external/fs3/PathResolver {
public abstract fun resolve (Ljava/lang/Object;)Ljava/lang/String;
}
public abstract interface class com/dropbox/android/external/fs3/Persister : com/dropbox/android/external/fs3/DiskRead, com/dropbox/android/external/fs3/DiskWrite {
public abstract fun read (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public abstract fun write (Ljava/lang/Object;Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public final class com/dropbox/android/external/fs3/RecordPersister : com/dropbox/android/external/fs3/SourcePersister, com/dropbox/android/external/fs3/RecordProvider {
public static final field Companion Lcom/dropbox/android/external/fs3/RecordPersister$Companion;
public synthetic fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;JLkotlin/jvm/internal/DefaultConstructorMarker;)V
public synthetic fun getRecordState (Ljava/lang/Object;)Lcom/dropbox/android/external/fs3/RecordState;
public fun getRecordState (Lkotlin/Pair;)Lcom/dropbox/android/external/fs3/RecordState;
}
public final class com/dropbox/android/external/fs3/RecordPersister$Companion {
public final fun create-HG0u8IE (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;J)Lcom/dropbox/android/external/fs3/RecordPersister;
}
public final class com/dropbox/android/external/fs3/RecordPersisterFactory {
public static final field INSTANCE Lcom/dropbox/android/external/fs3/RecordPersisterFactory;
public final fun create-HG0u8IE (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;J)Lcom/dropbox/android/external/fs3/Persister;
public final fun create-HG0u8IE (Ljava/io/File;J)Lcom/dropbox/android/external/fs3/Persister;
}
public abstract interface class com/dropbox/android/external/fs3/RecordProvider {
public abstract fun getRecordState (Ljava/lang/Object;)Lcom/dropbox/android/external/fs3/RecordState;
}
public final class com/dropbox/android/external/fs3/RecordState : java/lang/Enum {
public static final field FRESH Lcom/dropbox/android/external/fs3/RecordState;
public static final field MISSING Lcom/dropbox/android/external/fs3/RecordState;
public static final field STALE Lcom/dropbox/android/external/fs3/RecordState;
public static fun valueOf (Ljava/lang/String;)Lcom/dropbox/android/external/fs3/RecordState;
public static fun values ()[Lcom/dropbox/android/external/fs3/RecordState;
}
public final class com/dropbox/android/external/fs3/SourceAllPersister : com/dropbox/android/external/fs3/AllPersister {
public static final field Companion Lcom/dropbox/android/external/fs3/SourceAllPersister$Companion;
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)V
public fun deleteAll (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public final fun getSourceFileAllEraser$filesystem ()Lcom/dropbox/android/external/fs3/FSAllEraser;
public final fun getSourceFileAllReader$filesystem ()Lcom/dropbox/android/external/fs3/FSAllReader;
public final fun getSourceFileReader$filesystem ()Lcom/dropbox/android/external/fs3/FSReader;
public final fun getSourceFileWriter$filesystem ()Lcom/dropbox/android/external/fs3/FSWriter;
public synthetic fun read (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public fun read (Lkotlin/Pair;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public fun readAll (Lkotlinx/coroutines/CoroutineScope;Ljava/lang/String;)Lkotlinx/coroutines/channels/ReceiveChannel;
public synthetic fun write (Ljava/lang/Object;Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public fun write (Lkotlin/Pair;Lokio/BufferedSource;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public final class com/dropbox/android/external/fs3/SourceAllPersister$Companion {
public final fun create (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)Lcom/dropbox/android/external/fs3/SourceAllPersister;
}
public final class com/dropbox/android/external/fs3/SourceFileReader : com/dropbox/android/external/fs3/FSReader, com/dropbox/android/external/fs3/DiskRead {
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)V
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;)V
public synthetic fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
public final fun getRecordState-HG0u8IE (Lkotlin/Pair;J)Lcom/dropbox/android/external/fs3/RecordState;
}
public final class com/dropbox/android/external/fs3/SourceFileWriter : com/dropbox/android/external/fs3/FSWriter, com/dropbox/android/external/fs3/DiskWrite {
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)V
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;)V
public synthetic fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;Lcom/dropbox/android/external/fs3/PathResolver;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
}
public class com/dropbox/android/external/fs3/SourcePersister : com/dropbox/android/external/fs3/Persister {
public static final field Companion Lcom/dropbox/android/external/fs3/SourcePersister$Companion;
public fun <init> (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)V
protected final fun getSourceFileReader ()Lcom/dropbox/android/external/fs3/SourceFileReader;
protected final fun getSourceFileWriter ()Lcom/dropbox/android/external/fs3/SourceFileWriter;
public synthetic fun read (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public fun read (Lkotlin/Pair;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public synthetic fun write (Ljava/lang/Object;Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public fun write (Lkotlin/Pair;Lokio/BufferedSource;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
}
public final class com/dropbox/android/external/fs3/SourcePersister$Companion {
public final fun create (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)Lcom/dropbox/android/external/fs3/SourcePersister;
public final fun pathForBarcode$filesystem (Lkotlin/Pair;)Ljava/lang/String;
}
public final class com/dropbox/android/external/fs3/SourcePersisterFactory {
public static final field INSTANCE Lcom/dropbox/android/external/fs3/SourcePersisterFactory;
public final fun create (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)Lcom/dropbox/android/external/fs3/Persister;
public final fun create (Ljava/io/File;)Lcom/dropbox/android/external/fs3/Persister;
public final fun create-HG0u8IE (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;J)Lcom/dropbox/android/external/fs3/Persister;
public final fun create-HG0u8IE (Ljava/io/File;J)Lcom/dropbox/android/external/fs3/Persister;
public final fun createAll (Lcom/dropbox/android/external/fs3/filesystem/FileSystem;)Lcom/dropbox/android/external/fs3/Persister;
public final fun createAll (Ljava/io/File;)Lcom/dropbox/android/external/fs3/Persister;
}
public final class com/dropbox/android/external/fs3/StringPairPathResolver : com/dropbox/android/external/fs3/PathResolver {
public static final field INSTANCE Lcom/dropbox/android/external/fs3/StringPairPathResolver;
public synthetic fun resolve (Ljava/lang/Object;)Ljava/lang/String;
public fun resolve (Lkotlin/Pair;)Ljava/lang/String;
}
public final class com/dropbox/android/external/fs3/StringPairReadAllPathResolver : com/dropbox/android/external/fs3/PathResolver {
public static final field INSTANCE Lcom/dropbox/android/external/fs3/StringPairReadAllPathResolver;
public synthetic fun resolve (Ljava/lang/Object;)Ljava/lang/String;
public fun resolve (Lkotlin/Pair;)Ljava/lang/String;
}
public final class com/dropbox/android/external/fs3/Util {
public static final field INSTANCE Lcom/dropbox/android/external/fs3/Util;
public final fun createParentDirs (Ljava/io/File;)V
public final fun simplifyPath (Ljava/lang/String;)Ljava/lang/String;
}
public final class com/dropbox/android/external/fs3/filesystem/BreadthFirstFileTreeIterator : java/util/Iterator, kotlin/jvm/internal/markers/KMappedMarker {
public fun <init> (Ljava/io/File;)V
public fun hasNext ()Z
public fun next ()Ljava/lang/Object;
public fun remove ()V
}
public final class com/dropbox/android/external/fs3/filesystem/FSFile {
public fun <init> (Ljava/io/File;Ljava/lang/String;)V
public final fun delete ()V
public final fun exists ()Z
public final fun lastModified ()J
public final fun path ()Ljava/lang/String;
public final fun source ()Lokio/BufferedSource;
public final fun write (Lokio/BufferedSource;)V
}
public abstract interface class com/dropbox/android/external/fs3/filesystem/FileSystem {
public abstract fun delete (Ljava/lang/String;)V
public abstract fun deleteAll (Ljava/lang/String;)V
public abstract fun exists (Ljava/lang/String;)Z
public abstract fun getRecordState-VtjQ1oo (JLjava/lang/String;)Lcom/dropbox/android/external/fs3/RecordState;
public abstract fun list (Ljava/lang/String;)Ljava/util/Collection;
public abstract fun read (Ljava/lang/String;)Lokio/BufferedSource;
public abstract fun write (Ljava/lang/String;Lokio/BufferedSource;)V
}
public final class com/dropbox/android/external/fs3/filesystem/FileSystemFactory {
public static final field INSTANCE Lcom/dropbox/android/external/fs3/filesystem/FileSystemFactory;
public final fun create (Ljava/io/File;)Lcom/dropbox/android/external/fs3/filesystem/FileSystem;
}
public final class com/dropbox/android/external/fs3/filesystem/FileSystemImpl : com/dropbox/android/external/fs3/filesystem/FileSystem {
public fun <init> (Ljava/io/File;)V
public fun delete (Ljava/lang/String;)V
public fun deleteAll (Ljava/lang/String;)V
public fun exists (Ljava/lang/String;)Z
public fun getRecordState-VtjQ1oo (JLjava/lang/String;)Lcom/dropbox/android/external/fs3/RecordState;
public fun list (Ljava/lang/String;)Ljava/util/Collection;
public fun read (Ljava/lang/String;)Lokio/BufferedSource;
public fun write (Ljava/lang/String;Lokio/BufferedSource;)V
}

Some files were not shown because too many files have changed in this diff Show more