initial
This commit is contained in:
parent
7b86dae1b8
commit
9badd11494
236 changed files with 10617 additions and 600 deletions
48
.gitignore
vendored
48
.gitignore
vendored
|
@ -1,9 +1,41 @@
|
|||
# Built application files
|
||||
*.apk
|
||||
*.ap_
|
||||
|
||||
# Files for the ART/Dalvik VM
|
||||
*.dex
|
||||
|
||||
# Java class files
|
||||
*.class
|
||||
|
||||
# Generated files
|
||||
bin/
|
||||
gen/
|
||||
out/
|
||||
|
||||
# Gradle files
|
||||
.gradle/
|
||||
build/
|
||||
|
||||
# Local configuration file (sdk path, etc)
|
||||
local.properties
|
||||
grade.properties
|
||||
|
||||
# Proguard folder generated by Eclipse
|
||||
proguard/
|
||||
|
||||
# Log Files
|
||||
*.log
|
||||
|
||||
# Android Studio Navigation editor temp files
|
||||
.navigation/
|
||||
|
||||
# Android Studio captures folder
|
||||
captures/
|
||||
|
||||
# Intellij
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/workspace.xml
|
||||
/.idea/libraries
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.idea/
|
||||
|
||||
# Keystore files
|
||||
*.jks
|
||||
|
|
|
@ -1,22 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<resourceExtensions />
|
||||
<wildcardResourcePatterns>
|
||||
<entry name="!?*.java" />
|
||||
<entry name="!?*.form" />
|
||||
<entry name="!?*.class" />
|
||||
<entry name="!?*.groovy" />
|
||||
<entry name="!?*.scala" />
|
||||
<entry name="!?*.flex" />
|
||||
<entry name="!?*.kt" />
|
||||
<entry name="!?*.clj" />
|
||||
<entry name="!?*.aj" />
|
||||
</wildcardResourcePatterns>
|
||||
<annotationProcessing>
|
||||
<profile default="true" name="Default" enabled="false">
|
||||
<processorPath useClasspath="true" />
|
||||
</profile>
|
||||
</annotationProcessing>
|
||||
</component>
|
||||
</project>
|
|
@ -1,3 +0,0 @@
|
|||
<component name="CopyrightManager">
|
||||
<settings default="" />
|
||||
</component>
|
|
@ -1,20 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="distributionType" value="DEFAULT_WRAPPED" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
<option value="$PROJECT_DIR$/app" />
|
||||
<option value="$PROJECT_DIR$/middleware" />
|
||||
<option value="$PROJECT_DIR$/store" />
|
||||
</set>
|
||||
</option>
|
||||
<option name="resolveModulePerSourceSet" value="false" />
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
|
@ -1,46 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="EntryPointsManager">
|
||||
<entry_points version="2.0" />
|
||||
</component>
|
||||
<component name="NullableNotNullManager">
|
||||
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
|
||||
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
|
||||
<option name="myNullables">
|
||||
<value>
|
||||
<list size="4">
|
||||
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.Nullable" />
|
||||
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nullable" />
|
||||
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.Nullable" />
|
||||
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.Nullable" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
<option name="myNotNulls">
|
||||
<value>
|
||||
<list size="4">
|
||||
<item index="0" class="java.lang.String" itemvalue="org.jetbrains.annotations.NotNull" />
|
||||
<item index="1" class="java.lang.String" itemvalue="javax.annotation.Nonnull" />
|
||||
<item index="2" class="java.lang.String" itemvalue="edu.umd.cs.findbugs.annotations.NonNull" />
|
||||
<item index="3" class="java.lang.String" itemvalue="android.support.annotation.NonNull" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
|
||||
<OptionsSetting value="true" id="Add" />
|
||||
<OptionsSetting value="true" id="Remove" />
|
||||
<OptionsSetting value="true" id="Checkout" />
|
||||
<OptionsSetting value="true" id="Update" />
|
||||
<OptionsSetting value="true" id="Status" />
|
||||
<OptionsSetting value="true" id="Edit" />
|
||||
<ConfirmationsSetting value="0" id="Add" />
|
||||
<ConfirmationsSetting value="0" id="Remove" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" default="true" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||
</component>
|
||||
<component name="ProjectType">
|
||||
<option name="id" value="Android" />
|
||||
</component>
|
||||
</project>
|
|
@ -1,11 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/Store.iml" filepath="$PROJECT_DIR$/Store.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/middleware/middleware.iml" filepath="$PROJECT_DIR$/middleware/middleware.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/store/store.iml" filepath="$PROJECT_DIR$/store/store.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
|
@ -1,12 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RunConfigurationProducerService">
|
||||
<option name="ignoredProducers">
|
||||
<set>
|
||||
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
|
||||
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
|
||||
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
|
||||
</set>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
|
@ -1,6 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
BIN
Images/store-1.jpg
Normal file
BIN
Images/store-1.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 94 KiB |
BIN
Images/store-2.jpg
Normal file
BIN
Images/store-2.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 71 KiB |
BIN
Images/store-3.jpg
Normal file
BIN
Images/store-3.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 146 KiB |
BIN
Images/store-4.jpg
Normal file
BIN
Images/store-4.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 288 KiB |
BIN
Images/store-5.jpg
Normal file
BIN
Images/store-5.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 195 KiB |
9
License.md
Normal file
9
License.md
Normal file
|
@ -0,0 +1,9 @@
|
|||
Copyright (c) 2017 The New York Times Company
|
||||
|
||||
Copyright (c) 2010 The Guava Authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this library except in compliance with the License. You may obtain a copy of the License at
|
||||
|
||||
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.
|
265
README.md
Normal file
265
README.md
Normal file
|
@ -0,0 +1,265 @@
|
|||
# Store
|
||||
|
||||
Android library for async data loading from multiple sources
|
||||
|
||||
### The Problems:
|
||||
|
||||
+ Modern Android Apps need their 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 a social, news, or business-to-business app, users expect a seamless experience both online and offline.
|
||||
+ International users expect minimal data downloads as mbs of download can quickly turn into astronomical phone bills.
|
||||
|
||||
A Store is a class that simplifies fetching, parsing, 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](https://msdn.microsoft.com/en-us/library/ff649690.aspx)] while exposing a Reactive API built with RxJava that adheres to a unidirectional data flow.
|
||||
|
||||
Store provides a level of abstraction between our UI elements and data operations.
|
||||
|
||||
### Overview
|
||||
|
||||
A Store is responsible for managing a particular data request in an application. When you create an implementation of a Store, you provide it with a Fetcher<link>. Additionally, you can define how your Store will cache data in-memory and on-disk, as well as how to parse it. Since you'll be getting back an Observable of your data, threading is a breeze! Once a store is built, it will handle 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. Stores can be customized to work with your own implementations or use our included middleware.
|
||||
|
||||
Store leverages RxJava and multiple request throttling to prevent excessive calls to the network and disk cache. By utilizing our library, you eliminate the possibility of flooding your network with the same request while adding 2 layers of caching (memory + disk).
|
||||
|
||||
### Fully Configured Store
|
||||
Let's start by looking at what a fully configured store looks like, we will then walk through simpler examples building up functionality:
|
||||
```java
|
||||
Store<Foo> Store = ParsingStoreBuilder.<BufferedSource, String>builder()
|
||||
.fetcher(this::ResponseAsSource) //responseBody.source()
|
||||
.persister(new SourcePersister(new FileSystemImpl(context.getFilesDir())))
|
||||
.parser(new GsonSourceParser<>(gson, Foo.class))
|
||||
.open();
|
||||
|
||||
```
|
||||
|
||||
With the above setup you have:
|
||||
+ In Memory Caching
|
||||
+ Disk caching
|
||||
+ Parsing through streaming api
|
||||
+ Ability to get cached data or bust through your caches
|
||||
|
||||
And now for the details:
|
||||
|
||||
### Creating a Store
|
||||
|
||||
Create a store using a builder, the only requirement is to include a `.fetcher()`.
|
||||
|
||||
|
||||
``` java
|
||||
Store<Article> ArticleStore = StoreBuilder.<String>builder()
|
||||
.nonObservableFetcher(barCode -> api.getArticle(barcode.getValue()))
|
||||
.open();
|
||||
|
||||
|
||||
Store<Article> ArticleStore = StoreBuilder.<String>builder()
|
||||
.fetcher(barCode -> retrofitApi.getArticleObservable(barcode.getValue()))
|
||||
.open();
|
||||
```
|
||||
|
||||
### Barcodes
|
||||
|
||||
``` java
|
||||
Barcode barcode = new Barcode("Article", "42");
|
||||
```
|
||||
|
||||
Stores use Barcodes as identifiers for data. A Barcode is a class that holds two strings, type and value. The two values act as unique identifiers for your data. When your Fetcher function is called, it will be passed the Barcode. Similarly, the barcode will be used as a key in your cache(s).
|
||||
|
||||
|
||||
### Public Interfaces for Accessing Data - Get, Fresh, Stream
|
||||
|
||||
```java
|
||||
Observable<Article> article= store.get(barCode);
|
||||
```
|
||||
|
||||
The first time you subscribe to `store.get(barcode)`, the response will be stored in an in-memory cache using the Barcode as a key. All subsequent calls to `store.get(barcode)` 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 get recreated after a rotation, they will be able to request the cached data from your store. Having your data available has helped us retain less without or view layer
|
||||
|
||||
|
||||
So far our Store’s data flow looks like this:
|
||||
![Simple Store Flow](https://github.com/nytm/Store/blob/master/Images/store-1.jpg)
|
||||
`store.get()` -> return memory cached version if exists, otherwise -> fetch new networkResponse -> save in memory -> return newly cached response from memory
|
||||
|
||||
|
||||
By default 100 items will be cached in memory for 24 hours. You may pass in your own instance of a Guava Cache to override the default policy.
|
||||
|
||||
|
||||
### Busting through the cache
|
||||
|
||||
Alternatively you can call `store.fresh(barcode)` to get an Observable that skips the memory (and optional disk cache).
|
||||
|
||||
|
||||
Fresh data call will look like: `store.fresh()`
|
||||
![Simple Store Flow](https://github.com/nytm/Store/blob/master/Images/store-2.jpg)
|
||||
|
||||
|
||||
Overnight background updates within our app us fresh to make sure that calls to `store.get()` will not have to hit network during normal usage. Another good use case for fresh is pull to refresh.
|
||||
|
||||
|
||||
Calls to both `fresh()` and `get()` emit one value and then call `onCompleted()` or throw an error
|
||||
|
||||
|
||||
### Stream
|
||||
You may also call `store.stream(barcode)` which returns an Observable emitting the response for your barcode and then stays subscribed to receive any new items emitted for any calls to that store (for any barcode). Think of stream as an Event Bus-like feature that allows you to know when any new network hits happen for a particular store. You can leverage the Rx operator `filter()` to only subscribe to a subset of emissions.
|
||||
|
||||
|
||||
### Inflight Debouncer
|
||||
|
||||
There is an inflight debouncer as well to prevent duplicative requests for the same data. If same request is made within a minute of a previous identical request, the same response will be returned (useful for when your app has many async calls for the same data at startup or for when users are obsessively pulling to refresh). As an example, on start our app asynchronously calls `ConfigStore.get()` from 12 different places. The first call blocks while all others wait for the data to arrive. We have seen dramatic decrease in the data usage of our app since implementing the above in flight logic.
|
||||
|
||||
|
||||
### Adding a Parser
|
||||
|
||||
Since it is rare that data comes from the network in the format that your views need, Stores can delegate to a parser. by using a `ParsingStoreBuilder<T,V>` rather than a `StoreBuilder<T>.` ParsingStoreBuilder has an additional method `parser()` which can take a Parser<Raw, Parsed>
|
||||
|
||||
```
|
||||
Store<Article> Store =
|
||||
ParsingStoreBuilder.<BufferedSource, String>builder()
|
||||
.nonObservableFetcher(barCode -> source)) //okhttp responseBody.source()
|
||||
.parser(source -> {
|
||||
try (InputStreamReader reader = new InputStreamReader(source.inputStream())) {
|
||||
return gson.fromJson(reader, Article.class);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
})
|
||||
.open();
|
||||
```
|
||||
|
||||
Our updated data flow now looks like this:
|
||||
|
||||
`store.get()` -> ![Simple Store Flow](https://github.com/nytm/Store/blob/master/Images/store-3.jpg)
|
||||
|
||||
|
||||
|
||||
### Middleware - GsonSourceParser
|
||||
|
||||
There is also a seperate middleware lib with parsers to help in cases where your fetcher is a Reader, BufferedSource or String and your parser is Gson:
|
||||
GsonReaderParser,
|
||||
GsonSourceParser,
|
||||
GsonStringParser.
|
||||
|
||||
|
||||
Our example can now be rewritten as:
|
||||
```java
|
||||
Store<Article> Store = ParsingStoreBuilder.<BufferedSource, Article>builder()
|
||||
.nonObservableFetcher(this::getResponse)
|
||||
.parser(new GsonSourceParser<>(gson, Article.class))
|
||||
.open();
|
||||
```
|
||||
|
||||
### Disk Caching
|
||||
|
||||
Stores can enable disk caching by passing in a Persister to the builder. Whenever a new network request is made, it will first write to the disk cache and then read from the disk cache.
|
||||
|
||||
|
||||
Now our data flow looks like:
|
||||
`store.get()` -> ![Simple Store Flow](https://github.com/nytm/Store/blob/master/Images/store-5.jpg)
|
||||
|
||||
|
||||
|
||||
Ideally, data will be streamed from network to disk using either a BufferedSource or Reader as your network raw type (rather than String).
|
||||
|
||||
```java
|
||||
Store<String> Store = ParsingStoreBuilder.<BufferedSource, String>builder()
|
||||
.nonObservableFetcher(this::ResponseAsSource) //okhttp responseBody.source()
|
||||
.persister(new Persister<BufferedSource>() {
|
||||
@Override
|
||||
public Observable<BufferedSource> read(BarCode barCode) {
|
||||
if(dataIsCached)
|
||||
return Observable.fromCallable(()->userImplementedCache.get(barcode));
|
||||
else{
|
||||
Return Observable.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Observable<Boolean> write(BarCode barCode, BufferedSource source) {
|
||||
userImplementedCache.save(barcode,source)
|
||||
return Observable.just(true);
|
||||
}
|
||||
})
|
||||
.parser(new GsonSourceParser<>(gson, String.class))
|
||||
.open();
|
||||
```
|
||||
|
||||
Stores don’t care how you’re storing or retrieving your data from disk. As a result, you can use stores with object storage or any database (realm, sql lite, couchDB,firebase etc). The only requirement is that you can store and retrieve the data using the same type as your Fetcher. Technically there is nothing stopping you from implementing an in memory cache for the “persister” implementation and instead have 2 levels of in memory caching (one with inflated and one with deflated models, allowing for sharing of the “persister” cache data between stores)
|
||||
|
||||
|
||||
**Note**: When using a Parser and a disk cache, the parser will be called AFTER fetching from disk and not between the network and disk allow your persister to work on the network stream directly.
|
||||
|
||||
|
||||
If using SqlLite we recommend working with SqlBrite. If you are not using SqlBrite an Observable can be created rather simply with `Observable.fromCallable(() -> getDBValue())`
|
||||
|
||||
### Middleware - SourcePersister & FileSystem
|
||||
|
||||
We've found the fastest form of persistence is streaming network responses directly to disk. As a result, we have included a seperate lib with a reactive FileSystem which depends on OKIO BufferedSources. We have also included a SourcePersister which will give you disk caching and works beautifully with GsonSourceParser. Now we are back to our first example:
|
||||
|
||||
```
|
||||
Store<String> Store = ParsingStoreBuilder.<BufferedSource, String>builder()
|
||||
.nonObservableFetcher(this::ResponseAsSource) //okhttp responseBody.source()
|
||||
.persister(new SourcePersister(new FileSystemImpl(context.getFilesDir())))
|
||||
.parser(new GsonSourceParser<>(gson, String.class))
|
||||
.open();
|
||||
```
|
||||
|
||||
As mentioned, the above builder is how we work with network operations at New York Times. With the above setup you have:
|
||||
+ Memory caching with Guava Cache
|
||||
+ Disk caching with FileSystem (you can reuse the same file system impl for all stores)
|
||||
+ Parsing from a BufferedSource to a <T> (String in our case) with Gson
|
||||
+ in-flight request management
|
||||
+ Ability to get cached data or bust through your caches (get vs fresh)
|
||||
|
||||
|
||||
We recommend using the above setup of the builder for most Stores. The SourcePersister implementation has a tiny memory footprint as it will stream bytes from network to disk and then from disk to parser. The streaming nature of our stores allows us to download dozens of 1mb+ json responses without worrying about OOM on low-memory devices. As mentioned above, Stores allow us to do things like calling `configStore.get()` a dozen times asynchronously before our Main Activity finishes loading without blocking the main thread or flooding our network.
|
||||
|
||||
### Subclassing a Store
|
||||
|
||||
We can also subclass a Store implementation (RealStore<T>):
|
||||
|
||||
```java
|
||||
public class SampleStore extends RealStore<String> {
|
||||
public SampleStore(Fetcher<String> f, Persister<String> p) {
|
||||
super(f, p);
|
||||
}
|
||||
}
|
||||
```
|
||||
Or with a parser:
|
||||
|
||||
```java
|
||||
public class SampleStore extends RealStore<String> {
|
||||
public SampleStore(Fetcher<BufferedSource> fetcher,
|
||||
Persister<BufferedSource> persister,
|
||||
Parser<BufferedSource,String> parser) {
|
||||
super(fetcher, persister, parser);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Subclassing is useful for when you’d like to inject Store dependencies or add a few helper methods to a store:
|
||||
|
||||
```java
|
||||
public class SampleStore extends RealStore<String> {
|
||||
@Inject
|
||||
public SampleStore(Fetcher<String> f, Persister<String> p) {
|
||||
super(f, p);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Artifacts
|
||||
Since this is android, we have split Store into 4 artifacts:
|
||||
+ **Cache** Cache extracted from Guava (~200 methods)
|
||||
|
||||
`compile 'com.nytimes.android:cache:1.0.1'`
|
||||
+ **Store**. This contains only Store classes and has a dependecy on RxJava + the above cache.
|
||||
|
||||
`compile 'com.nytimes.android:store:1.0.1'`
|
||||
+ **Middleware** Sample gson parsers, (feel free to create more and open PRs)
|
||||
|
||||
`compile 'com.nytimes.android:middleware:1.0.1'`
|
||||
+ **File System** Persistence Library built using OKIO Source/Sink + Middleware for streaming from Network to FileSystem
|
||||
|
||||
`compile 'com.nytimes.android:filesystem:1.0.1'`
|
||||
|
||||
|
||||
### Sample Project
|
||||
|
||||
See app for example usage of Store.
|
||||
+ Simple Example: Retrofit + Store
|
||||
+ Complex Example: BufferedSource from Retrofit (Can be OKHTTP too) + our FileSystem + our GsonSourceParser
|
|
@ -1,4 +1,7 @@
|
|||
apply plugin: 'com.android.application'
|
||||
apply plugin: 'me.tatarka.retrolambda'
|
||||
apply plugin: 'com.getkeepsafe.dexcount'
|
||||
apply plugin: 'com.neenbedankt.android-apt'
|
||||
|
||||
android {
|
||||
compileSdkVersion 24
|
||||
|
@ -11,20 +14,50 @@ android {
|
|||
versionName "1.0"
|
||||
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
}
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
lintOptions {
|
||||
abortOnError false
|
||||
disable 'InvalidPackage'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile fileTree(dir: 'libs', include: ['*.jar'])
|
||||
final RETROFIT_VERSION = '2.0.0-beta3'
|
||||
|
||||
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
|
||||
exclude group: 'com.android.support', module: 'support-annotations'
|
||||
})
|
||||
compile 'com.android.support:appcompat-v7:25.0.0'
|
||||
|
||||
compile 'com.android.support:recyclerview-v7:24.0.0'
|
||||
compile 'com.android.support:appcompat-v7:24.0.0'
|
||||
compile 'com.android.support:cardview-v7:24.0.0'
|
||||
compile 'com.android.support:design:24.0.0'
|
||||
compile "com.squareup.retrofit2:retrofit:$RETROFIT_VERSION"
|
||||
compile "com.squareup.retrofit2:converter-gson:$RETROFIT_VERSION"
|
||||
compile "com.squareup.retrofit2:adapter-rxjava:$RETROFIT_VERSION"
|
||||
compile 'com.squareup.picasso:picasso:2.5.2'
|
||||
compile 'com.google.guava:guava:19.0'
|
||||
|
||||
apt "org.immutables:value:2.1.16" // <-- for annotation processor
|
||||
provided "org.immutables:value:2.1.16" // <-- for annotation API
|
||||
provided "org.immutables:gson:2.1.16" // for annotations
|
||||
|
||||
testCompile 'junit:junit:4.12'
|
||||
project(':middleware')
|
||||
// compile project(path: ':store')
|
||||
// compile project(path: ':cache')
|
||||
compile project(path: ':store')
|
||||
compile project(path: ':middleware')
|
||||
compile project(path: ':filesystem')
|
||||
retrolambdaConfig libraries.retrolambda
|
||||
compile libraries.rxAndroid
|
||||
|
||||
}
|
||||
|
|
Binary file not shown.
|
@ -1,6 +1,8 @@
|
|||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.nytimes.android.sample">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
|
@ -8,7 +10,7 @@
|
|||
android:supportsRtl="true"
|
||||
android:theme="@style/AppTheme">
|
||||
<activity
|
||||
android:name=".activity.StoreActivity">
|
||||
android:name=".activity.PersistingStoreActivity">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
|
||||
|
|
|
@ -0,0 +1,126 @@
|
|||
package com.nytimes.android.sample.activity;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
import android.support.v7.widget.LinearLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.Toolbar;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.nytimes.android.external.fs.SourcePersister;
|
||||
import com.nytimes.android.external.fs.impl.FileSystemImpl;
|
||||
import com.nytimes.android.external.store.base.Store;
|
||||
import com.nytimes.android.external.store.base.impl.BarCode;
|
||||
import com.nytimes.android.external.store.base.impl.ParsingStoreBuilder;
|
||||
import com.nytimes.android.external.store.middleware.GsonSourceParser;
|
||||
import com.nytimes.android.sample.BuildConfig;
|
||||
import com.nytimes.android.sample.R;
|
||||
import com.nytimes.android.sample.data.model.Children;
|
||||
import com.nytimes.android.sample.data.model.GsonAdaptersModel;
|
||||
import com.nytimes.android.sample.data.model.Post;
|
||||
import com.nytimes.android.sample.data.model.RedditData;
|
||||
import com.nytimes.android.sample.data.remote.Api;
|
||||
import com.nytimes.android.sample.reddit.PostAdapter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import okio.BufferedSource;
|
||||
import retrofit2.GsonConverterFactory;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.RxJavaCallAdapterFactory;
|
||||
import rx.Observable;
|
||||
import rx.android.schedulers.AndroidSchedulers;
|
||||
import rx.schedulers.Schedulers;
|
||||
|
||||
import static android.widget.Toast.makeText;
|
||||
|
||||
|
||||
public class PersistingStoreActivity extends AppCompatActivity {
|
||||
|
||||
private SourcePersister sourcePersister;
|
||||
private RecyclerView recyclerView;
|
||||
private PostAdapter postAdapter;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
setContentView(R.layout.activity_store);
|
||||
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
|
||||
|
||||
try {
|
||||
sourcePersister = persister();
|
||||
} catch (IOException exception) {
|
||||
throw new RuntimeException(exception);
|
||||
}
|
||||
|
||||
postAdapter = new PostAdapter();
|
||||
recyclerView = (RecyclerView) findViewById(R.id.postRecyclerView);
|
||||
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
|
||||
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
|
||||
recyclerView.setLayoutManager(layoutManager);
|
||||
recyclerView.setAdapter(postAdapter);
|
||||
|
||||
loadPosts();
|
||||
}
|
||||
|
||||
public void loadPosts() {
|
||||
BarCode awwRequest = new BarCode(RedditData.class.getSimpleName(), "aww");
|
||||
provideRedditStore()
|
||||
.get(awwRequest)
|
||||
.flatMap(this::sanitizeData)
|
||||
.toList()
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(this::showPosts, throwable -> {});
|
||||
}
|
||||
|
||||
private void showPosts(List<Post> posts) {
|
||||
postAdapter.setPosts(posts);
|
||||
makeText(PersistingStoreActivity.this,
|
||||
"Loaded " + posts.size() + " posts",
|
||||
Toast.LENGTH_SHORT)
|
||||
.show();
|
||||
}
|
||||
|
||||
private Observable<Post> sanitizeData(RedditData redditData) {
|
||||
return Observable.from(redditData.data().children())
|
||||
.map(Children::data);
|
||||
}
|
||||
|
||||
private Store<RedditData> provideRedditStore() {
|
||||
return ParsingStoreBuilder.<BufferedSource,RedditData>builder()
|
||||
.fetcher(this::fetcher)
|
||||
.persister(sourcePersister)
|
||||
.parser(new GsonSourceParser<>(provideGson(),RedditData.class))
|
||||
.open();
|
||||
}
|
||||
|
||||
private SourcePersister persister() throws IOException {
|
||||
return new SourcePersister(new FileSystemImpl(getApplicationContext().getCacheDir()));
|
||||
}
|
||||
|
||||
private Observable<BufferedSource> fetcher(BarCode barCode) {
|
||||
return provideRetrofit().fetchSubredditForPersister(barCode.getKey(), "10")
|
||||
.map(responseBody -> responseBody.source());
|
||||
}
|
||||
|
||||
private Api provideRetrofit() {
|
||||
return new Retrofit.Builder()
|
||||
.baseUrl("http://reddit.com/")
|
||||
.addConverterFactory(GsonConverterFactory.create(provideGson()))
|
||||
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
|
||||
.validateEagerly(BuildConfig.DEBUG) // Fail early: check Retrofit configuration at creation time in Debug build.
|
||||
.build()
|
||||
.create(Api.class);
|
||||
}
|
||||
|
||||
Gson provideGson() {
|
||||
return new GsonBuilder()
|
||||
.registerTypeAdapterFactory(new GsonAdaptersModel())
|
||||
.create();
|
||||
}
|
||||
}
|
|
@ -1,12 +1,104 @@
|
|||
package com.nytimes.android.sample.activity;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.os.Bundle;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
import android.support.v7.widget.LinearLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.Toolbar;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.nytimes.android.external.store.base.Store;
|
||||
import com.nytimes.android.external.store.base.impl.BarCode;
|
||||
import com.nytimes.android.external.store.base.impl.StoreBuilder;
|
||||
import com.nytimes.android.sample.BuildConfig;
|
||||
import com.nytimes.android.sample.R;
|
||||
import com.nytimes.android.sample.data.model.Children;
|
||||
import com.nytimes.android.sample.data.model.GsonAdaptersModel;
|
||||
import com.nytimes.android.sample.data.model.Post;
|
||||
import com.nytimes.android.sample.data.model.RedditData;
|
||||
import com.nytimes.android.sample.data.remote.Api;
|
||||
import com.nytimes.android.sample.reddit.PostAdapter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import retrofit2.GsonConverterFactory;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.RxJavaCallAdapterFactory;
|
||||
import rx.Observable;
|
||||
import rx.android.schedulers.AndroidSchedulers;
|
||||
import rx.schedulers.Schedulers;
|
||||
|
||||
import static android.widget.Toast.makeText;
|
||||
|
||||
|
||||
public class StoreActivity extends AppCompatActivity {
|
||||
|
||||
private RecyclerView recyclerView;
|
||||
private PostAdapter postAdapter;
|
||||
|
||||
public class StoreActivity extends Activity {
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_store);
|
||||
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
|
||||
postAdapter = new PostAdapter();
|
||||
recyclerView = (RecyclerView) findViewById(R.id.postRecyclerView);
|
||||
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
|
||||
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
|
||||
recyclerView.setLayoutManager(layoutManager);
|
||||
recyclerView.setAdapter(postAdapter);
|
||||
|
||||
loadPosts();
|
||||
}
|
||||
|
||||
public void loadPosts() {
|
||||
BarCode awwRequest = new BarCode(RedditData.class.getSimpleName(), "aww");
|
||||
provideRedditStore()
|
||||
.get(awwRequest)
|
||||
.flatMap(this::sanitizeData)
|
||||
.toList()
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(this::showPosts, throwable -> {
|
||||
Log.e(StoreActivity.class.getSimpleName(), throwable.getMessage(), throwable);
|
||||
});
|
||||
}
|
||||
|
||||
private void showPosts(List<Post> posts) {
|
||||
postAdapter.setPosts(posts);
|
||||
makeText(StoreActivity.this,
|
||||
"Loaded " + posts.size() + " posts",
|
||||
Toast.LENGTH_SHORT)
|
||||
.show();
|
||||
}
|
||||
|
||||
private Observable<Post> sanitizeData(RedditData redditData) {
|
||||
return Observable.from(redditData.data().children())
|
||||
.map(Children::data);
|
||||
}
|
||||
|
||||
private Store<RedditData> provideRedditStore() {
|
||||
return StoreBuilder.<RedditData>builder()
|
||||
.fetcher(barCode -> provideRetrofit().fetchSubreddit(barCode.getKey(), "10"))
|
||||
.open();
|
||||
}
|
||||
|
||||
private Api provideRetrofit() {
|
||||
return new Retrofit.Builder()
|
||||
.baseUrl("http://reddit.com/")
|
||||
.addConverterFactory(GsonConverterFactory.create(provideGson()))
|
||||
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
|
||||
.validateEagerly(BuildConfig.DEBUG) // Fail early: check Retrofit configuration at creation time in Debug build.
|
||||
.build()
|
||||
.create(Api.class);
|
||||
}
|
||||
|
||||
Gson provideGson() {
|
||||
return new GsonBuilder()
|
||||
.registerTypeAdapterFactory(new GsonAdaptersModel())
|
||||
.create();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
package com.nytimes.android.sample.data.model;
|
||||
|
||||
import org.immutables.value.Value;
|
||||
|
||||
@Value.Immutable
|
||||
public abstract class Children {
|
||||
public abstract Post data();
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.nytimes.android.sample.data.model;
|
||||
|
||||
import org.immutables.value.Value;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Value.Immutable
|
||||
public abstract class Data {
|
||||
public abstract List<Children> children();
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.nytimes.android.sample.data.model;
|
||||
|
||||
import org.immutables.value.Value;
|
||||
|
||||
@Value.Immutable
|
||||
public abstract class Image {
|
||||
public abstract String url();
|
||||
public abstract int height();
|
||||
public abstract int width();
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.nytimes.android.sample.data.model;
|
||||
|
||||
import org.immutables.value.Value;
|
||||
|
||||
@Value.Immutable
|
||||
public abstract class Images {
|
||||
public abstract Image source();
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.nytimes.android.sample.data.model;
|
||||
|
||||
import android.support.annotation.Nullable;
|
||||
|
||||
import com.google.common.base.Optional;
|
||||
|
||||
import org.immutables.value.Value;
|
||||
|
||||
@Value.Immutable
|
||||
public abstract class Post {
|
||||
@Nullable
|
||||
public abstract Preview preview();
|
||||
|
||||
public abstract String title();
|
||||
|
||||
public abstract String url();
|
||||
|
||||
@Nullable
|
||||
public abstract Integer height();
|
||||
|
||||
@Nullable
|
||||
public abstract Integer width();
|
||||
|
||||
@Value.Derived
|
||||
public Optional<Image> nestedThumbnail() {
|
||||
if (preview() == null || preview().images() == null || preview().images().get(0).source() == null)
|
||||
return Optional.absent();
|
||||
return Optional.of(preview().images().get(0).source());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.nytimes.android.sample.data.model;
|
||||
|
||||
import org.immutables.value.Value;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Value.Immutable
|
||||
@Value.Style(allParameters = true)
|
||||
public abstract class Preview {
|
||||
@Value.Parameter(false)
|
||||
public abstract List<Images> images();
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.nytimes.android.sample.data.model;
|
||||
|
||||
import org.immutables.value.Value;
|
||||
|
||||
@Value.Immutable
|
||||
public abstract class RedditData {
|
||||
public abstract Data data();
|
||||
public abstract String kind();
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
@Gson.TypeAdapters
|
||||
package com.nytimes.android.sample.data.model;
|
||||
|
||||
import org.immutables.gson.Gson;
|
|
@ -0,0 +1,21 @@
|
|||
package com.nytimes.android.sample.data.remote;
|
||||
|
||||
import com.nytimes.android.sample.data.model.RedditData;
|
||||
|
||||
import okhttp3.Response;
|
||||
import okhttp3.ResponseBody;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Path;
|
||||
import retrofit2.http.Query;
|
||||
import rx.Observable;
|
||||
|
||||
public interface Api {
|
||||
|
||||
@GET("r/{subredditName}/new/.json")
|
||||
Observable<RedditData> fetchSubreddit(@Path("subredditName") String subredditName,
|
||||
@Query("limit") String limit);
|
||||
|
||||
@GET("r/{subredditName}/new/.json")
|
||||
Observable<ResponseBody> fetchSubredditForPersister(@Path("subredditName") String subredditName,
|
||||
@Query("limit") String limit);
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.nytimes.android.sample.reddit;
|
||||
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import com.nytimes.android.sample.R;
|
||||
import com.nytimes.android.sample.data.model.Post;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
|
||||
public class PostAdapter extends RecyclerView.Adapter<PostViewHolder> {
|
||||
|
||||
private final List<Post> articles = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
View itemView = LayoutInflater.from(
|
||||
parent.getContext()).inflate(R.layout.article_item, parent, false);
|
||||
return new PostViewHolder(itemView);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(PostViewHolder holder, int position) {
|
||||
holder.onBind(articles.get(position));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return articles.size();
|
||||
}
|
||||
|
||||
public void setPosts(List<Post> articlesToAdd) {
|
||||
articles.clear();
|
||||
articles.addAll(articlesToAdd);
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,105 @@
|
|||
package com.nytimes.android.sample.reddit;
|
||||
|
||||
import android.app.Application;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.view.View;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
|
||||
import com.nytimes.android.sample.R;
|
||||
import com.nytimes.android.sample.data.model.Image;
|
||||
import com.nytimes.android.sample.data.model.ImmutableImage;
|
||||
import com.nytimes.android.sample.data.model.Post;
|
||||
import com.nytimes.android.sample.util.BitmapTransform;
|
||||
import com.nytimes.android.sample.util.DeviceUtils;
|
||||
import com.squareup.picasso.Picasso;
|
||||
|
||||
|
||||
public class PostViewHolder extends RecyclerView.ViewHolder {
|
||||
|
||||
private int maxHeight;
|
||||
private int maxWidth;
|
||||
private TextView title;
|
||||
private ImageView thumbnail;
|
||||
private View topSpacer;
|
||||
private final DeviceUtils deviceUtils;
|
||||
|
||||
public PostViewHolder(View itemView) {
|
||||
super(itemView);
|
||||
deviceUtils = new DeviceUtils((Application) itemView.getContext().getApplicationContext());
|
||||
findViews(itemView);
|
||||
setMaxDimensions(itemView);
|
||||
}
|
||||
|
||||
public void onBind(Post article) {
|
||||
title.setText(article.title());
|
||||
if (article.nestedThumbnail().isPresent()) {
|
||||
showImage(article);
|
||||
}
|
||||
}
|
||||
|
||||
private void showImage(Post article) {
|
||||
Image nestedImage = article.nestedThumbnail().get();
|
||||
Image image = ImmutableImage
|
||||
.builder()
|
||||
.height(nestedImage.height())
|
||||
.width(nestedImage.width())
|
||||
.url(nestedImage.url())
|
||||
.build();
|
||||
BitmapTransform bitmapTransform = new BitmapTransform(maxWidth, maxHeight, image);
|
||||
|
||||
int targetWidth = bitmapTransform.targetWidth;
|
||||
int targetHeight = bitmapTransform.targetHeight;
|
||||
|
||||
setSpacer(targetWidth, targetHeight);
|
||||
|
||||
setupThumbnail(targetWidth, targetHeight);
|
||||
|
||||
Picasso.with(itemView.getContext())
|
||||
.load(image.url())
|
||||
.transform(bitmapTransform)
|
||||
.resize(targetWidth, targetHeight)
|
||||
.centerInside()
|
||||
.placeholder(R.color.gray80)
|
||||
.into(thumbnail);
|
||||
}
|
||||
|
||||
private void setSpacer(int targetWidth, int targetHeight) {
|
||||
if (targetWidth >= targetHeight) {
|
||||
topSpacer.setVisibility(View.GONE);
|
||||
} else {
|
||||
topSpacer.setVisibility(View.VISIBLE);
|
||||
}
|
||||
}
|
||||
|
||||
private void setupThumbnail(int targetWidth, int targetHeight) {
|
||||
thumbnail.setMaxWidth(targetWidth);
|
||||
thumbnail.setMaxHeight(targetHeight);
|
||||
thumbnail.setMinimumWidth(targetWidth);
|
||||
thumbnail.setMinimumHeight(targetHeight);
|
||||
thumbnail.requestLayout();
|
||||
}
|
||||
|
||||
private void setMaxDimensions(View itemView) {
|
||||
int screenWidth;
|
||||
int screenHeight;
|
||||
screenWidth = deviceUtils.getScreenWidth();
|
||||
screenHeight = deviceUtils.getScreenHeight();
|
||||
|
||||
if (screenWidth > screenHeight) {
|
||||
screenHeight = deviceUtils.getScreenWidth();
|
||||
screenWidth = deviceUtils.getScreenHeight();
|
||||
}
|
||||
|
||||
maxHeight = (int) (screenHeight * .55f);
|
||||
int margin = itemView.getContext().getResources().getDimensionPixelSize(R.dimen.post_horizontal_margin);
|
||||
maxWidth = screenWidth - (2 * margin);
|
||||
}
|
||||
|
||||
private void findViews(View itemView) {
|
||||
title = (TextView) itemView.findViewById(R.id.title);
|
||||
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
|
||||
topSpacer = itemView.findViewById(R.id.topSpacer);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.nytimes.android.sample.util;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
|
||||
import com.nytimes.android.sample.data.model.Image;
|
||||
import com.squareup.picasso.Transformation;
|
||||
|
||||
|
||||
public class BitmapTransform implements Transformation
|
||||
{
|
||||
int maxWidth, maxHeight;
|
||||
Image key;
|
||||
public int targetWidth;
|
||||
public int targetHeight;
|
||||
private final String picassoKey;
|
||||
|
||||
public BitmapTransform(int maxWidth, int maxHeight, Image image) {
|
||||
this.maxWidth = maxWidth;
|
||||
this.maxHeight = maxHeight;
|
||||
this.key = image;
|
||||
this.picassoKey = key.url() + "_" + targetWidth + ":" + targetHeight;
|
||||
|
||||
double aspectRatio;
|
||||
if (image.width() >= image.height()) {
|
||||
targetWidth = maxWidth;
|
||||
aspectRatio = (double) image.height() / (double) image.width();
|
||||
targetHeight = (int) (targetWidth * aspectRatio);
|
||||
} else {
|
||||
targetHeight = maxHeight;
|
||||
aspectRatio = (double) image.width() / (double) image.height();
|
||||
targetWidth = (int) (targetHeight * aspectRatio);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Bitmap transform(Bitmap source) {
|
||||
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth,
|
||||
targetHeight, true);
|
||||
if (result != source) {
|
||||
source.recycle();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return picassoKey;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.nytimes.android.sample.util;
|
||||
|
||||
import android.app.Application;
|
||||
import android.content.Context;
|
||||
import android.graphics.Point;
|
||||
import android.view.Display;
|
||||
import android.view.WindowManager;
|
||||
|
||||
public class DeviceUtils {
|
||||
|
||||
private WindowManager windowManager;
|
||||
|
||||
public DeviceUtils(Application context) {
|
||||
windowManager =
|
||||
(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
|
||||
}
|
||||
|
||||
public int getScreenWidth() {
|
||||
return getScreenSize().x;
|
||||
}
|
||||
|
||||
public int getScreenHeight() {
|
||||
return getScreenSize().y;
|
||||
}
|
||||
|
||||
public Point getScreenSize() {
|
||||
Display display = windowManager.getDefaultDisplay();
|
||||
Point result = new Point();
|
||||
display.getSize(result);
|
||||
return result;
|
||||
}
|
||||
}
|
43
app/src/main/res/layout/activity_store.xml
Normal file
43
app/src/main/res/layout/activity_store.xml
Normal file
|
@ -0,0 +1,43 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<android.support.design.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">
|
||||
|
||||
<android.support.design.widget.AppBarLayout
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_width="match_parent"
|
||||
android:theme="@style/AppTheme.AppBarOverlay">
|
||||
|
||||
<android.support.v7.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"/>
|
||||
|
||||
</android.support.design.widget.AppBarLayout>
|
||||
|
||||
<android.support.v7.widget.RecyclerView
|
||||
android:id="@+id/postRecyclerView"
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
app:layout_behavior="@string/appbar_scrolling_view_behavior"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/gray70"/>
|
||||
|
||||
<android.support.design.widget.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"/>
|
||||
|
||||
</android.support.design.widget.CoordinatorLayout>
|
46
app/src/main/res/layout/article_item.xml
Normal file
46
app/src/main/res/layout/article_item.xml
Normal file
|
@ -0,0 +1,46 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<android.support.v7.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_marginRight="@dimen/post_horizontal_margin"
|
||||
android:layout_marginTop="@dimen/post_horizontal_margin_half"
|
||||
android:layout_marginBottom="@dimen/post_horizontal_margin_half"
|
||||
|
||||
card_view:cardUseCompatPadding="false"
|
||||
card_view:cardElevation="7dp"
|
||||
card_view:cardCornerRadius="4dp">
|
||||
|
||||
<LinearLayout
|
||||
android:orientation="vertical"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content">
|
||||
|
||||
<View
|
||||
android:id="@+id/topSpacer"
|
||||
android:visibility="gone"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="@dimen/post_horizontal_margin"/>
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/thumbnail"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_gravity="center_horizontal"/>
|
||||
|
||||
<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>
|
||||
|
||||
</android.support.v7.widget.CardView>
|
|
@ -3,4 +3,44 @@
|
|||
<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>
|
||||
|
|
18
app/src/main/res/values/dimens.xml
Normal file
18
app/src/main/res/values/dimens.xml
Normal file
|
@ -0,0 +1,18 @@
|
|||
<?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>
|
|
@ -1,11 +1,17 @@
|
|||
<resources>
|
||||
|
||||
<!-- Base application theme. -->
|
||||
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
|
||||
<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>
|
||||
|
|
|
@ -2,7 +2,12 @@ package com.nytimes.android.sample;
|
|||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static java.lang.Thread.sleep;
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
|
@ -10,8 +15,93 @@ import static org.junit.Assert.*;
|
|||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||
*/
|
||||
public class ExampleUnitTest {
|
||||
|
||||
public static final String KEY = "key";
|
||||
private final LinkedHashMap<String, AtomicReference<String>> cache =
|
||||
new LinkedHashMap<String, AtomicReference<String>>(){
|
||||
private static final int MAX_ENTRIES = 100;
|
||||
|
||||
@Override
|
||||
protected boolean removeEldestEntry(Entry eldest) {
|
||||
return size() > MAX_ENTRIES;
|
||||
}
|
||||
};
|
||||
private final AtomicInteger counter = new AtomicInteger(0);
|
||||
|
||||
@Test
|
||||
public void addition_isCorrect() throws Exception {
|
||||
assertEquals(4, 2 + 2);
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
synchronizedGet(KEY);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
};
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
synchronizedGet(KEY);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
};
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
synchronizedGet(KEY);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
};
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
synchronizedGet(KEY);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
};
|
||||
new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
synchronizedGet(KEY);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
assertEquals(synchronizedGet(KEY), "1");
|
||||
|
||||
}
|
||||
|
||||
private String synchronizedGet(String key) throws InterruptedException {
|
||||
AtomicReference<String> ref;
|
||||
synchronized (cache) {
|
||||
ref = cache.get(key);
|
||||
if (ref == null) {
|
||||
ref = new AtomicReference<>();
|
||||
cache.put(key, ref);
|
||||
}
|
||||
}
|
||||
synchronized (ref) {
|
||||
if(ref.get()==null){
|
||||
sleep(1000);
|
||||
counter.incrementAndGet();
|
||||
ref.set(counter.toString());
|
||||
}
|
||||
|
||||
}
|
||||
return ref.get();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,41 @@
|
|||
package com.nytimes.android.sample;
|
||||
|
||||
import com.nytimes.android.external.store.base.Store;
|
||||
import com.nytimes.android.external.store.base.impl.BarCode;
|
||||
import com.nytimes.android.external.store.base.impl.StoreBuilder;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||
*/
|
||||
public class StoreIntegrationTest {
|
||||
|
||||
private Store<String> testStore;
|
||||
|
||||
@Test
|
||||
public void addition_isCorrect() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
testStore = StoreBuilder.<String>builder()
|
||||
.nonObservableFetcher(barCode -> "hello")
|
||||
.open();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRepeatedGet() throws Exception {
|
||||
String first = testStore.get(BarCode.empty()).toBlocking().first();
|
||||
assertEquals(first,"hello");
|
||||
|
||||
}
|
||||
}
|
1
app/version.properties
Normal file
1
app/version.properties
Normal file
|
@ -0,0 +1 @@
|
|||
version=0.1
|
29
build.gradle
29
build.gradle
|
@ -16,8 +16,10 @@ buildscript {
|
|||
maven {
|
||||
url 'https://artifactory.em.nytimes.com/artifactory/android-maven-thirdparty-local/'
|
||||
}
|
||||
|
||||
|
||||
maven {
|
||||
url = 'https://oss.jfrog.org/artifactory/oss-snapshot-local'
|
||||
url = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/'
|
||||
}
|
||||
|
||||
jcenter()
|
||||
|
@ -27,7 +29,7 @@ buildscript {
|
|||
classpath 'com.android.tools.build:gradle:2.2.2'
|
||||
classpath 'com.google.gms:google-services:3.0.0'
|
||||
classpath('com.nytimes.android.gradle:base-plugin:1.0.5') {
|
||||
exclude module: 'guava-jdk5'
|
||||
// exclude module: 'guava-jdk5'
|
||||
}
|
||||
classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.5.6'
|
||||
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
|
||||
|
@ -57,6 +59,29 @@ allprojects {
|
|||
}
|
||||
}
|
||||
|
||||
ext {
|
||||
// SDK versions
|
||||
|
||||
// POM file
|
||||
GROUP = "com.nytimes.android"
|
||||
VERSION_NAME = "1.0.1"
|
||||
POM_PACKAGING = "pom"
|
||||
POM_DESCRIPTION = "Store"
|
||||
|
||||
POM_URL = "https://github.com/nytimes/Store/"
|
||||
POM_SCM_URL = "https://github.com/nytimes/Store/"
|
||||
POM_SCM_CONNECTION = "scm:git:https://github.com/nytm/Store.git"
|
||||
POM_SCM_DEV_CONNECTION = "scm:git:git@github.com:nytm/Store.git"
|
||||
|
||||
POM_LICENCE_NAME = "Apache License"
|
||||
POM_LICENCE_URL = "http://www.apache.org/licenses/"
|
||||
POM_LICENCE_DIST = "repo"
|
||||
|
||||
POM_DEVELOPER_ID = "nytimesandroid"
|
||||
POM_DEVELOPER_NAME = "New York Times"
|
||||
}
|
||||
|
||||
|
||||
// From command line use: -PdisablePreDex to disable it: primarily for jenkins
|
||||
project.ext.preDexLibs = !project.hasProperty('disablePreDex')
|
||||
|
||||
|
|
|
@ -18,7 +18,7 @@ allprojects {
|
|||
}
|
||||
|
||||
ext.versions = [
|
||||
minSdk : 19,
|
||||
minSdk : 16,
|
||||
targetSdk : 23,
|
||||
compileSdk : 23,
|
||||
buildTools : '24.0.2',
|
||||
|
|
1
cache/.gitignore
vendored
Normal file
1
cache/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
/build
|
43
cache/build.gradle
vendored
Normal file
43
cache/build.gradle
vendored
Normal file
|
@ -0,0 +1,43 @@
|
|||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'me.tatarka.retrolambda'
|
||||
apply plugin: 'com.neenbedankt.android-apt'
|
||||
|
||||
group = GROUP
|
||||
version = VERSION_NAME
|
||||
|
||||
android {
|
||||
compileSdkVersion versions.compileSdk
|
||||
buildToolsVersion versions.buildTools
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion versions.minSdk
|
||||
targetSdkVersion versions.targetSdk
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
debug {
|
||||
minifyEnabled false
|
||||
zipAlignEnabled false
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_7
|
||||
targetCompatibility JavaVersion.VERSION_1_7
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
abortOnError false
|
||||
disable 'InvalidPackage'
|
||||
}
|
||||
}
|
||||
|
||||
task sourcesJar(type: Jar) {
|
||||
from android.sourceSets.main.java.srcDirs
|
||||
classifier = 'sources'
|
||||
}
|
||||
|
||||
artifacts {
|
||||
archives sourcesJar
|
||||
}
|
||||
|
||||
apply from: rootProject.file("gradle/maven-push.gradle")
|
3
cache/gradle.properties
vendored
Normal file
3
cache/gradle.properties
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
POM_NAME=com.nytimes.android
|
||||
POM_ARTIFACT_ID=cache
|
||||
POM_PACKAGING=aar
|
9
cache/src/main/AndroidManifest.xml
vendored
Normal file
9
cache/src/main/AndroidManifest.xml
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest
|
||||
package="com.nytimes.android.external.cache">
|
||||
|
||||
|
||||
<application>
|
||||
</application>
|
||||
|
||||
</manifest>
|
907
cache/src/main/java/com/nytimes/android/external/cache/AbstractFuture.java
vendored
Normal file
907
cache/src/main/java/com/nytimes/android/external/cache/AbstractFuture.java
vendored
Normal file
|
@ -0,0 +1,907 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
|
||||
|
||||
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 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()
|
||||
|
||||
@Override public final V get() throws InterruptedException, ExecutionException {
|
||||
return super.get();
|
||||
}
|
||||
|
||||
@Override public final V get(long timeout, 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(Runnable listener, 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 */);
|
||||
|
||||
|
||||
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(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 {
|
||||
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
|
||||
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.") {
|
||||
@Override public synchronized Throwable fillInStackTrace() {
|
||||
return this; // no stack trace
|
||||
}
|
||||
});
|
||||
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}
|
||||
*/
|
||||
@Override
|
||||
public V get(long timeout, 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}
|
||||
*/
|
||||
@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.
|
||||
*/
|
||||
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(Runnable listener, 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( 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(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( 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(Runnable runnable, 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);
|
||||
}
|
||||
}
|
||||
|
||||
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(Waiter waiter, Thread newValue) {
|
||||
waiterThreadUpdater.lazySet(waiter, newValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
void putNext(Waiter waiter, Waiter newValue) {
|
||||
waiterNextUpdater.lazySet(waiter, newValue);
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean casWaiters(AbstractFuture<?> future, Waiter expect, Waiter update) {
|
||||
return waitersUpdater.compareAndSet(future, expect, update);
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean casListeners(AbstractFuture<?> future, Listener expect, Listener update) {
|
||||
return listenersUpdater.compareAndSet(future, expect, update);
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean casValue(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(Waiter waiter, Thread newValue) {
|
||||
waiter.thread = newValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
void putNext(Waiter waiter, Waiter newValue) {
|
||||
waiter.next = newValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean casWaiters(AbstractFuture<?> future, Waiter expect, Waiter update) {
|
||||
synchronized (future) {
|
||||
if (future.waiters == expect) {
|
||||
future.waiters = update;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean casListeners(AbstractFuture<?> future, Listener expect, Listener update) {
|
||||
synchronized (future) {
|
||||
if (future.listeners == expect) {
|
||||
future.listeners = update;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean casValue(AbstractFuture<?> future, Object expect, Object update) {
|
||||
synchronized (future) {
|
||||
if (future.value == expect) {
|
||||
future.value = update;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
43
cache/src/main/java/com/nytimes/android/external/cache/AbstractSequentialIterator.java
vendored
Normal file
43
cache/src/main/java/com/nytimes/android/external/cache/AbstractSequentialIterator.java
vendored
Normal file
|
@ -0,0 +1,43 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
|
||||
|
||||
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
public abstract class AbstractSequentialIterator<T> extends UnmodifiableIterator<T> {
|
||||
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()}.
|
||||
*/
|
||||
protected abstract T computeNext(T previous);
|
||||
|
||||
@Override
|
||||
public final boolean hasNext() {
|
||||
return nextOrNull != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final T next() {
|
||||
if (!hasNext()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
try {
|
||||
return nextOrNull;
|
||||
} finally {
|
||||
nextOrNull = computeNext(nextOrNull);
|
||||
}
|
||||
}
|
||||
}
|
40
cache/src/main/java/com/nytimes/android/external/cache/Ascii.java
vendored
Normal file
40
cache/src/main/java/com/nytimes/android/external/cache/Ascii.java
vendored
Normal file
|
@ -0,0 +1,40 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
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.
|
||||
*/
|
||||
public static String toLowerCase(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');
|
||||
}
|
||||
|
||||
}
|
105
cache/src/main/java/com/nytimes/android/external/cache/Cache.java
vendored
Normal file
105
cache/src/main/java/com/nytimes/android/external/cache/Cache.java
vendored
Normal file
|
@ -0,0 +1,105 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
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
|
||||
*/
|
||||
|
||||
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
|
||||
*/
|
||||
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();
|
||||
}
|
528
cache/src/main/java/com/nytimes/android/external/cache/CacheBuilder.java
vendored
Normal file
528
cache/src/main/java/com/nytimes/android/external/cache/CacheBuilder.java
vendored
Normal file
|
@ -0,0 +1,528 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
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.
|
||||
*/
|
||||
public static CacheBuilder<Object, Object> newBuilder() {
|
||||
return new CacheBuilder<Object, Object>();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) {
|
||||
Preconditions.checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
|
||||
keyEquivalence = Preconditions.checkNotNull(equivalence);
|
||||
return this;
|
||||
}
|
||||
|
||||
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.
|
||||
*/
|
||||
CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) {
|
||||
Preconditions.checkState(valueEquivalence == null,
|
||||
"value equivalence was already set to %s", valueEquivalence);
|
||||
this.valueEquivalence = Preconditions.checkNotNull(equivalence);
|
||||
return this;
|
||||
}
|
||||
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher(
|
||||
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.
|
||||
@SuppressWarnings("unchecked")
|
||||
<K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() {
|
||||
return (Weigher<K1, V1>) MoreObjects.firstNonNull(weigher, OneWeigher.INSTANCE);
|
||||
}
|
||||
|
||||
|
||||
CacheBuilder<K, V> setKeyStrength(LocalCache.Strength strength) {
|
||||
Preconditions.checkState(keyStrength == null, "Key strength was already set to %s", keyStrength);
|
||||
keyStrength = Preconditions.checkNotNull(strength);
|
||||
return this;
|
||||
}
|
||||
|
||||
LocalCache.Strength getKeyStrength() {
|
||||
return MoreObjects.firstNonNull(keyStrength, LocalCache.Strength.STRONG);
|
||||
}
|
||||
|
||||
|
||||
CacheBuilder<K, V> setValueStrength(LocalCache.Strength strength) {
|
||||
Preconditions.checkState(valueStrength == null, "Value strength was already set to %s", valueStrength);
|
||||
valueStrength = Preconditions.checkNotNull(strength);
|
||||
return this;
|
||||
}
|
||||
|
||||
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
|
||||
*/
|
||||
public CacheBuilder<K, V> expireAfterWrite(long duration, 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
|
||||
*/
|
||||
public CacheBuilder<K, V> expireAfterAccess(long duration, 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
|
||||
*/
|
||||
public CacheBuilder<K, V> ticker(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
|
||||
*/
|
||||
public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener(
|
||||
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.
|
||||
@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
|
||||
*/
|
||||
public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build(
|
||||
CacheLoader<? super K1, V1> loader) {
|
||||
checkWeightWithWeigher();
|
||||
return new LocalCache.LocalLoadingCache<K1, V1>(this, loader);
|
||||
}
|
||||
|
||||
public <K1 extends K, V1 extends V> Cache<K1, V1> build() {
|
||||
checkWeightWithWeigher();
|
||||
checkNonLoadingCache();
|
||||
return new LocalCache.LocalManualCache<K1, V1>(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();
|
||||
}
|
||||
}
|
119
cache/src/main/java/com/nytimes/android/external/cache/CacheLoader.java
vendored
Normal file
119
cache/src/main/java/com/nytimes/android/external/cache/CacheLoader.java
vendored
Normal file
|
@ -0,0 +1,119 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Map;
|
||||
|
||||
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
|
||||
*/
|
||||
public abstract V load(K key) throws Exception;
|
||||
|
||||
|
||||
public ListenableFuture<V> reload(K key, V oldValue) throws Exception {
|
||||
Preconditions.checkNotNull(key);
|
||||
Preconditions.checkNotNull(oldValue);
|
||||
return Futures.immediateFuture(load(key));
|
||||
}
|
||||
|
||||
|
||||
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}
|
||||
*/
|
||||
public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
|
||||
return new FunctionToCacheLoader<K, V>(function);
|
||||
}
|
||||
|
||||
private static final class FunctionToCacheLoader<K, V>
|
||||
extends CacheLoader<K, V> implements Serializable {
|
||||
private final Function<K, V> computingFunction;
|
||||
|
||||
public FunctionToCacheLoader(Function<K, V> computingFunction) {
|
||||
this.computingFunction = Preconditions.checkNotNull(computingFunction);
|
||||
}
|
||||
|
||||
@Override
|
||||
public V load(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
|
||||
*/
|
||||
public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
|
||||
return new SupplierToCacheLoader<V>(supplier);
|
||||
}
|
||||
|
||||
|
||||
private static final class SupplierToCacheLoader<V>
|
||||
extends CacheLoader<Object, V> implements Serializable {
|
||||
private final Supplier<V> computingSupplier;
|
||||
|
||||
public SupplierToCacheLoader(Supplier<V> computingSupplier) {
|
||||
this.computingSupplier = Preconditions.checkNotNull(computingSupplier);
|
||||
}
|
||||
|
||||
@Override
|
||||
public V load(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);
|
||||
}
|
||||
}
|
||||
}
|
14
cache/src/main/java/com/nytimes/android/external/cache/DirectExecutor.java
vendored
Normal file
14
cache/src/main/java/com/nytimes/android/external/cache/DirectExecutor.java
vendored
Normal file
|
@ -0,0 +1,14 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
enum DirectExecutor implements Executor {
|
||||
INSTANCE;
|
||||
@Override public void execute(Runnable command) {
|
||||
command.run();
|
||||
}
|
||||
|
||||
@Override public String toString() {
|
||||
return "MoreExecutors.directExecutor()";
|
||||
}
|
||||
}
|
178
cache/src/main/java/com/nytimes/android/external/cache/Equivalence.java
vendored
Normal file
178
cache/src/main/java/com/nytimes/android/external/cache/Equivalence.java
vendored
Normal file
|
@ -0,0 +1,178 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
|
||||
/**
|
||||
* 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( 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)
|
||||
*/
|
||||
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)
|
||||
*/
|
||||
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(Object a, Object b) {
|
||||
return a.equals(b);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int doHash(Object o) {
|
||||
return o.hashCode();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private Object readResolve() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
private static final long serialVersionUID = 1;
|
||||
}
|
||||
}
|
15
cache/src/main/java/com/nytimes/android/external/cache/ExecutionError.java
vendored
Normal file
15
cache/src/main/java/com/nytimes/android/external/cache/ExecutionError.java
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
|
||||
|
||||
|
||||
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;
|
||||
}
|
90
cache/src/main/java/com/nytimes/android/external/cache/ForwardingCache.java
vendored
Normal file
90
cache/src/main/java/com/nytimes/android/external/cache/ForwardingCache.java
vendored
Normal file
|
@ -0,0 +1,90 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
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
|
||||
*/
|
||||
@Override
|
||||
public V getIfPresent(Object key) {
|
||||
return delegate().getIfPresent(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 11.0
|
||||
*/
|
||||
@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();
|
||||
}
|
||||
|
||||
}
|
20
cache/src/main/java/com/nytimes/android/external/cache/ForwardingObject.java
vendored
Normal file
20
cache/src/main/java/com/nytimes/android/external/cache/ForwardingObject.java
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
12
cache/src/main/java/com/nytimes/android/external/cache/Function.java
vendored
Normal file
12
cache/src/main/java/com/nytimes/android/external/cache/Function.java
vendored
Normal file
|
@ -0,0 +1,12 @@
|
|||
//
|
||||
// Source code recreated from a .class file by IntelliJ IDEA
|
||||
// (powered by Fernflower decompiler)
|
||||
//
|
||||
|
||||
package com.nytimes.android.external.cache;
|
||||
|
||||
public interface Function<F, T> {
|
||||
T apply(F var1);
|
||||
|
||||
boolean equals(Object var1);
|
||||
}
|
188
cache/src/main/java/com/nytimes/android/external/cache/Futures.java
vendored
Normal file
188
cache/src/main/java/com/nytimes/android/external/cache/Futures.java
vendored
Normal file
|
@ -0,0 +1,188 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
|
||||
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;
|
||||
|
||||
public final class Futures {
|
||||
private Futures() {
|
||||
}
|
||||
|
||||
|
||||
public static <V> ListenableFuture<V> immediateFuture( V value) {
|
||||
if (value == null) {
|
||||
Futures.ImmediateSuccessfulFuture typedNull = Futures.ImmediateSuccessfulFuture.NULL;
|
||||
return typedNull;
|
||||
} else {
|
||||
return new Futures.ImmediateSuccessfulFuture(value);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) {
|
||||
Preconditions.checkNotNull(throwable);
|
||||
return new Futures.ImmediateFailedFuture(throwable);
|
||||
}
|
||||
|
||||
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function) {
|
||||
Preconditions.checkNotNull(function);
|
||||
Futures.ChainingFuture output = new Futures.ChainingFuture(input, function);
|
||||
input.addListener(output, DirectExecutor.INSTANCE);
|
||||
return output;
|
||||
}
|
||||
|
||||
public static <V, X extends Exception> V getChecked(Future<V> future, Class<X> exceptionClass) throws X {
|
||||
return FuturesGetChecked.getChecked(future, exceptionClass);
|
||||
}
|
||||
|
||||
public static <V, X extends Exception> V getChecked(Future<V> future, Class<X> exceptionClass, long timeout, 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);
|
||||
}
|
||||
|
||||
void doTransform(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.
|
||||
|
||||
ListenableFuture<? extends I> inputFuture;
|
||||
|
||||
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;
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public V get() throws ExecutionException {
|
||||
throw new ExecutionException(this.thrown);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class ImmediateSuccessfulFuture<V> extends Futures.ImmediateFuture<V> {
|
||||
static final Futures.ImmediateSuccessfulFuture<Object> NULL = new Futures.ImmediateSuccessfulFuture((Object) null);
|
||||
|
||||
private final V value;
|
||||
|
||||
ImmediateSuccessfulFuture( V value) {
|
||||
super();
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
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() {
|
||||
}
|
||||
|
||||
public void addListener(Runnable listener, 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public boolean cancel(boolean mayInterruptIfRunning) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public abstract V get() throws ExecutionException;
|
||||
|
||||
public V get(long timeout, TimeUnit unit) throws ExecutionException {
|
||||
Preconditions.checkNotNull(unit);
|
||||
return this.get();
|
||||
}
|
||||
|
||||
public boolean isCancelled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isDone() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
136
cache/src/main/java/com/nytimes/android/external/cache/FuturesGetChecked.java
vendored
Normal file
136
cache/src/main/java/com/nytimes/android/external/cache/FuturesGetChecked.java
vendored
Normal file
|
@ -0,0 +1,136 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
|
||||
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 static java.lang.Thread.currentThread;
|
||||
|
||||
final class FuturesGetChecked {
|
||||
static <V, X extends Exception> V getChecked(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(
|
||||
GetCheckedTypeValidator validator, 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(
|
||||
Future<V> future, Class<X> exceptionClass, long timeout, 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);
|
||||
}
|
||||
|
||||
private static GetCheckedTypeValidator bestGetCheckedTypeValidator() {
|
||||
return GetCheckedTypeValidatorHolder.BEST_VALIDATOR;
|
||||
}
|
||||
|
||||
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(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.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
25
cache/src/main/java/com/nytimes/android/external/cache/ListenableFuture.java
vendored
Normal file
25
cache/src/main/java/com/nytimes/android/external/cache/ListenableFuture.java
vendored
Normal file
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
|
||||
public interface ListenableFuture<V> extends Future<V> {
|
||||
void addListener(Runnable listener, Executor executor);
|
||||
}
|
127
cache/src/main/java/com/nytimes/android/external/cache/LoadingCache.java
vendored
Normal file
127
cache/src/main/java/com/nytimes/android/external/cache/LoadingCache.java
vendored
Normal file
|
@ -0,0 +1,127 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
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.)
|
||||
*/
|
||||
@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();
|
||||
}
|
4819
cache/src/main/java/com/nytimes/android/external/cache/LocalCache.java
vendored
Normal file
4819
cache/src/main/java/com/nytimes/android/external/cache/LocalCache.java
vendored
Normal file
File diff suppressed because it is too large
Load diff
371
cache/src/main/java/com/nytimes/android/external/cache/MoreObjects.java
vendored
Normal file
371
cache/src/main/java/com/nytimes/android/external/cache/MoreObjects.java
vendored
Normal file
|
@ -0,0 +1,371 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
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()}).
|
||||
*/
|
||||
public static ToStringHelper toStringHelper(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;
|
||||
private ValueHolder holderHead = new ValueHolder();
|
||||
private ValueHolder holderTail = holderHead;
|
||||
private boolean omitNullValues = false;
|
||||
|
||||
/**
|
||||
* Use {@link MoreObjects#toStringHelper(Object)} to create an instance.
|
||||
*/
|
||||
private ToStringHelper(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.
|
||||
*/
|
||||
public ToStringHelper add(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()}).
|
||||
*/
|
||||
public ToStringHelper add(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()}).
|
||||
*/
|
||||
public ToStringHelper add(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.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
|
||||
private ValueHolder addHolder() {
|
||||
ValueHolder valueHolder = new ValueHolder();
|
||||
holderTail = holderTail.next = valueHolder;
|
||||
return valueHolder;
|
||||
}
|
||||
|
||||
private ToStringHelper addHolder( Object value) {
|
||||
ValueHolder valueHolder = addHolder();
|
||||
valueHolder.value = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
private ToStringHelper addHolder(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() {}
|
||||
}
|
53
cache/src/main/java/com/nytimes/android/external/cache/Objects.java
vendored
Normal file
53
cache/src/main/java/com/nytimes/android/external/cache/Objects.java
vendored
Normal file
|
@ -0,0 +1,53 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
|
||||
}
|
31
cache/src/main/java/com/nytimes/android/external/cache/Platform.java
vendored
Normal file
31
cache/src/main/java/com/nytimes/android/external/cache/Platform.java
vendored
Normal file
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
}
|
150
cache/src/main/java/com/nytimes/android/external/cache/Preconditions.java
vendored
Normal file
150
cache/src/main/java/com/nytimes/android/external/cache/Preconditions.java
vendored
Normal file
|
@ -0,0 +1,150 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
|
||||
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
69
cache/src/main/java/com/nytimes/android/external/cache/RemovalCause.java
vendored
Normal file
69
cache/src/main/java/com/nytimes/android/external/cache/RemovalCause.java
vendored
Normal file
|
@ -0,0 +1,69 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
13
cache/src/main/java/com/nytimes/android/external/cache/RemovalListener.java
vendored
Normal file
13
cache/src/main/java/com/nytimes/android/external/cache/RemovalListener.java
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
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);
|
||||
}
|
85
cache/src/main/java/com/nytimes/android/external/cache/RemovalNotification.java
vendored
Normal file
85
cache/src/main/java/com/nytimes/android/external/cache/RemovalNotification.java
vendored
Normal file
|
@ -0,0 +1,85 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static com.nytimes.android.external.cache.Preconditions.checkNotNull;
|
||||
|
||||
public final class RemovalNotification<K, V> implements Map.Entry<K, V> {
|
||||
|
||||
private final K key;
|
||||
private final V value;
|
||||
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
|
||||
*/
|
||||
public static <K, V> RemovalNotification<K, V> create(
|
||||
K key, V value, RemovalCause cause) {
|
||||
return new RemovalNotification(key, value, cause);
|
||||
}
|
||||
|
||||
private RemovalNotification( K key, V value, 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;
|
||||
}
|
||||
|
||||
@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>.
|
||||
*/
|
||||
@Override public String toString() {
|
||||
return getKey() + "=" + getValue();
|
||||
}
|
||||
// --Commented out by Inspection (11/29/16, 5:04 PM):private static final long serialVersionUID = 0;
|
||||
}
|
33
cache/src/main/java/com/nytimes/android/external/cache/SettableFuture.java
vendored
Normal file
33
cache/src/main/java/com/nytimes/android/external/cache/SettableFuture.java
vendored
Normal file
|
@ -0,0 +1,33 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
|
||||
|
||||
|
||||
public final class SettableFuture<V> extends AbstractFuture.TrustedFuture<V> {
|
||||
|
||||
/**
|
||||
* Creates a new {@code SettableFuture} in the default state.
|
||||
*/
|
||||
public static <V> SettableFuture<V> create() {
|
||||
return new SettableFuture<V>();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(ListenableFuture<? extends V> future) {
|
||||
return super.setFuture(future);
|
||||
}
|
||||
}
|
204
cache/src/main/java/com/nytimes/android/external/cache/Stopwatch.java
vendored
Normal file
204
cache/src/main/java/com/nytimes/android/external/cache/Stopwatch.java
vendored
Normal file
|
@ -0,0 +1,204 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.nytimes.android.external.cache.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 {
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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));
|
||||
}
|
||||
|
||||
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(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();
|
||||
}
|
||||
}
|
||||
}
|
10
cache/src/main/java/com/nytimes/android/external/cache/Supplier.java
vendored
Normal file
10
cache/src/main/java/com/nytimes/android/external/cache/Supplier.java
vendored
Normal file
|
@ -0,0 +1,10 @@
|
|||
//
|
||||
// Source code recreated from a .class file by IntelliJ IDEA
|
||||
// (powered by Fernflower decompiler)
|
||||
//
|
||||
|
||||
package com.nytimes.android.external.cache;
|
||||
|
||||
public interface Supplier<T> {
|
||||
T get();
|
||||
}
|
47
cache/src/main/java/com/nytimes/android/external/cache/Ticker.java
vendored
Normal file
47
cache/src/main/java/com/nytimes/android/external/cache/Ticker.java
vendored
Normal file
|
@ -0,0 +1,47 @@
|
|||
/*
|
||||
* 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.nytimes.android.external.cache;
|
||||
|
||||
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
|
||||
*/
|
||||
public static Ticker systemTicker() {
|
||||
return SYSTEM_TICKER;
|
||||
}
|
||||
|
||||
private static final Ticker SYSTEM_TICKER =
|
||||
new Ticker() {
|
||||
@Override
|
||||
public long read() {
|
||||
return Platform.systemNanoTime();
|
||||
}
|
||||
};
|
||||
}
|
37
cache/src/main/java/com/nytimes/android/external/cache/UncheckedExecutionException.java
vendored
Normal file
37
cache/src/main/java/com/nytimes/android/external/cache/UncheckedExecutionException.java
vendored
Normal file
|
@ -0,0 +1,37 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
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;
|
||||
}
|
39
cache/src/main/java/com/nytimes/android/external/cache/Uninterruptibles.java
vendored
Normal file
39
cache/src/main/java/com/nytimes/android/external/cache/Uninterruptibles.java
vendored
Normal file
|
@ -0,0 +1,39 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
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(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() {}
|
||||
}
|
20
cache/src/main/java/com/nytimes/android/external/cache/UnmodifiableIterator.java
vendored
Normal file
20
cache/src/main/java/com/nytimes/android/external/cache/UnmodifiableIterator.java
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
12
cache/src/main/java/com/nytimes/android/external/cache/Weigher.java
vendored
Normal file
12
cache/src/main/java/com/nytimes/android/external/cache/Weigher.java
vendored
Normal file
|
@ -0,0 +1,12 @@
|
|||
package com.nytimes.android.external.cache;
|
||||
|
||||
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);
|
||||
}
|
1
filesystem/.gitignore
vendored
Normal file
1
filesystem/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
/build
|
48
filesystem/build.gradle
Normal file
48
filesystem/build.gradle
Normal file
|
@ -0,0 +1,48 @@
|
|||
apply plugin: 'com.android.library'
|
||||
apply plugin: 'com.getkeepsafe.dexcount'
|
||||
|
||||
group = GROUP
|
||||
version = VERSION_NAME
|
||||
|
||||
android {
|
||||
compileSdkVersion versions.compileSdk
|
||||
buildToolsVersion versions.buildTools
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion versions.minSdk
|
||||
targetSdkVersion versions.targetSdk
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
debug {
|
||||
minifyEnabled false
|
||||
zipAlignEnabled false
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_1_7
|
||||
targetCompatibility JavaVersion.VERSION_1_7
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
abortOnError false
|
||||
disable 'InvalidPackage'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile libraries.okio
|
||||
compile libraries.gson
|
||||
|
||||
compile libraries.rxJava
|
||||
compile project(path: ':cache')
|
||||
compile project(path: ':store')
|
||||
compile project(path: ':middleware')
|
||||
testCompile libraries.mockito
|
||||
testCompile libraries.assertJ
|
||||
testCompile libraries.junit
|
||||
testCompile libraries.robolectric
|
||||
}
|
||||
apply from: rootProject.file("gradle/maven-push.gradle")
|
||||
|
||||
|
3
filesystem/gradle.properties
Normal file
3
filesystem/gradle.properties
Normal file
|
@ -0,0 +1,3 @@
|
|||
POM_NAME=com.nytimes.android
|
||||
POM_ARTIFACT_ID=filesystem
|
||||
POM_PACKAGING=aar
|
9
filesystem/src/main/AndroidManifest.xml
Normal file
9
filesystem/src/main/AndroidManifest.xml
Normal file
|
@ -0,0 +1,9 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest
|
||||
package="com.nytimes.android.filesystem">
|
||||
|
||||
|
||||
<application>
|
||||
</application>
|
||||
|
||||
</manifest>
|
|
@ -1,4 +1,4 @@
|
|||
package com.nytimes.android.external.store.middleware.fs;
|
||||
package com.nytimes.android.external.fs;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
|
@ -1,8 +1,7 @@
|
|||
package com.nytimes.android.external.store.middleware;
|
||||
package com.nytimes.android.external.fs;
|
||||
|
||||
import com.nytimes.android.external.store.middleware.fs.FileSystem;
|
||||
import com.nytimes.android.store.base.DiskRead;
|
||||
import com.nytimes.android.store.base.impl.BarCode;
|
||||
import com.nytimes.android.external.store.base.DiskRead;
|
||||
import com.nytimes.android.external.store.base.impl.BarCode;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.concurrent.Callable;
|
||||
|
@ -12,7 +11,7 @@ import javax.inject.Inject;
|
|||
import okio.BufferedSource;
|
||||
import rx.Observable;
|
||||
|
||||
import static com.nytimes.android.external.store.middleware.SourcePersister.pathForBarcode;
|
||||
import static com.nytimes.android.external.fs.SourcePersister.pathForBarcode;
|
||||
|
||||
public class SourceFileReader implements DiskRead<BufferedSource> {
|
||||
|
||||
|
@ -32,4 +31,8 @@ public class SourceFileReader implements DiskRead<BufferedSource> {
|
|||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean exists(BarCode barCode) {
|
||||
return fileSystem.exists(pathForBarcode(barCode));
|
||||
}
|
||||
}
|
|
@ -1,8 +1,7 @@
|
|||
package com.nytimes.android.external.store.middleware;
|
||||
package com.nytimes.android.external.fs;
|
||||
|
||||
import com.nytimes.android.external.store.middleware.fs.FileSystem;
|
||||
import com.nytimes.android.store.base.DiskWrite;
|
||||
import com.nytimes.android.store.base.impl.BarCode;
|
||||
import com.nytimes.android.external.store.base.DiskWrite;
|
||||
import com.nytimes.android.external.store.base.impl.BarCode;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
|
@ -11,7 +10,7 @@ import javax.inject.Inject;
|
|||
import okio.BufferedSource;
|
||||
import rx.Observable;
|
||||
|
||||
import static com.nytimes.android.external.store.middleware.SourcePersister.pathForBarcode;
|
||||
import static com.nytimes.android.external.fs.SourcePersister.pathForBarcode;
|
||||
import static okio.Okio.buffer;
|
||||
|
||||
public class SourceFileWriter implements DiskWrite<BufferedSource> {
|
|
@ -1,10 +1,9 @@
|
|||
package com.nytimes.android.external.store.middleware;
|
||||
package com.nytimes.android.external.fs;
|
||||
|
||||
import android.support.annotation.NonNull;
|
||||
|
||||
import com.nytimes.android.external.store.middleware.fs.FileSystem;
|
||||
import com.nytimes.android.store.base.Persister;
|
||||
import com.nytimes.android.store.base.impl.BarCode;
|
||||
import com.nytimes.android.external.store.base.Persister;
|
||||
import com.nytimes.android.external.store.base.impl.BarCode;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
|
@ -33,7 +32,7 @@ public class SourcePersister implements Persister<BufferedSource> {
|
|||
|
||||
@Override
|
||||
public Observable<BufferedSource> read(final BarCode barCode) {
|
||||
return sourceFileReader.read(barCode);
|
||||
return sourceFileReader.exists(barCode) ? sourceFileReader.read(barCode) : Observable.<BufferedSource>empty();
|
||||
}
|
||||
|
||||
@Override
|
64
filesystem/src/main/java/com/nytimes/android/external/fs/Util.java
vendored
Normal file
64
filesystem/src/main/java/com/nytimes/android/external/fs/Util.java
vendored
Normal file
|
@ -0,0 +1,64 @@
|
|||
package com.nytimes.android.external.fs;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Stack;
|
||||
|
||||
import static dagger.internal.Preconditions.checkNotNull;
|
||||
|
||||
public class Util {
|
||||
|
||||
public String simplifyPath(String path) {
|
||||
if (path == null || path.length() == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
String delim = "[/]+";
|
||||
String[] arr = path.split(delim);
|
||||
|
||||
Stack<String> stack = new Stack<String>();
|
||||
|
||||
for (String str : arr) {
|
||||
if(str.equals("/")){
|
||||
continue;
|
||||
}
|
||||
if (str.equals("..")) {
|
||||
if (!stack.isEmpty()) {
|
||||
stack.pop();
|
||||
}
|
||||
} else if (!str.equals(".") && !str.isEmpty()) {
|
||||
stack.push(str);
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (stack.isEmpty()) {
|
||||
return "/";
|
||||
}
|
||||
|
||||
for (String str : stack) {
|
||||
sb.append("/" + str);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void createParentDirs(File file) throws IOException {
|
||||
checkNotNull(file);
|
||||
File parent = file.getCanonicalFile().getParentFile();
|
||||
if (parent == null) {
|
||||
/*
|
||||
* The given directory is a filesystem root. All zero of its ancestors
|
||||
* exist. This doesn't mean that the root itself exists -- consider x:\ on
|
||||
* a Windows machine without such a drive -- or even that the caller can
|
||||
* create it, but this method makes no such guarantees even for non-root
|
||||
* files.
|
||||
*/
|
||||
return;
|
||||
}
|
||||
parent.mkdirs();
|
||||
if (!parent.isDirectory()) {
|
||||
throw new IOException("Unable to create parent directories of " + file);
|
||||
}
|
||||
}
|
||||
}
|
144
filesystem/src/main/java/com/nytimes/android/external/fs/impl/BreadthFirstFileTreeIterator.java
vendored
Normal file
144
filesystem/src/main/java/com/nytimes/android/external/fs/impl/BreadthFirstFileTreeIterator.java
vendored
Normal file
|
@ -0,0 +1,144 @@
|
|||
package com.nytimes.android.external.fs.impl;
|
||||
|
||||
/*
|
||||
* Copyright 2004-2007 the original author or 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 org.jpublish.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Stack;
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/** Breadth first iterator which iterates through all files which are decendents
|
||||
of the specified root file.
|
||||
|
||||
@author Anthony Eden
|
||||
@since 1.1
|
||||
*/
|
||||
|
||||
public class BreadthFirstFileTreeIterator implements Iterator{
|
||||
|
||||
private File root;
|
||||
private int currentIndex = 0;
|
||||
private File[] currentList;
|
||||
private File nextFile;
|
||||
private Stack directories;
|
||||
private boolean endOfTree = false;
|
||||
|
||||
/** Construct a new BreadthFirstFileTreeIterator with the specified root.
|
||||
|
||||
@param root The root directory
|
||||
*/
|
||||
|
||||
public BreadthFirstFileTreeIterator(File root){
|
||||
this.root = root;
|
||||
this.currentList = root.listFiles();
|
||||
this.directories = new Stack();
|
||||
}
|
||||
|
||||
/** Returns true if the iteration has more elements. (In other words,
|
||||
returns true if next would return an element rather than throwing
|
||||
an exception.)
|
||||
|
||||
@return True if the iteration has more elements
|
||||
*/
|
||||
|
||||
public boolean hasNext(){
|
||||
if(endOfTree)
|
||||
return false;
|
||||
return getNextFile() != null;
|
||||
}
|
||||
|
||||
/** Returns the next element in the iteration.
|
||||
|
||||
@return The next element in the iteration
|
||||
*/
|
||||
|
||||
public Object next(){
|
||||
if(endOfTree)
|
||||
throw new NoSuchElementException();
|
||||
|
||||
File file = getNextFile();
|
||||
if(file == null){
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
this.nextFile = null;
|
||||
return file;
|
||||
}
|
||||
|
||||
/** Removes from the underlying collection the last element returned by
|
||||
the iterator (optional operation). This method can be called only
|
||||
once per call to next. The behavior of an iterator is unspecified
|
||||
if the underlying collection is modified while the iteration is in
|
||||
progress in any way other than by calling this method.
|
||||
|
||||
@throws UnsupportedOperationException
|
||||
*/
|
||||
|
||||
public void remove(){
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
/** Get the next file. If the value for the next file is null then the
|
||||
findNextFile() method is invoked to locate the next file. A call
|
||||
to next() will return the next file and will null out the next file
|
||||
variable.
|
||||
|
||||
@return The next file
|
||||
*/
|
||||
|
||||
protected File getNextFile(){
|
||||
if(nextFile == null){
|
||||
nextFile = findNextFile();
|
||||
}
|
||||
return nextFile;
|
||||
}
|
||||
|
||||
/** Find the next file.
|
||||
|
||||
@return The next file
|
||||
*/
|
||||
|
||||
protected File findNextFile(){
|
||||
while(currentIndex < currentList.length){
|
||||
if(currentList[currentIndex].isDirectory()){
|
||||
directories.push(currentList[currentIndex]);
|
||||
currentIndex++;
|
||||
} else {
|
||||
File file = currentList[currentIndex];
|
||||
currentIndex++;
|
||||
return file;
|
||||
}
|
||||
}
|
||||
|
||||
while(!directories.empty()){
|
||||
File directory = (File)directories.remove(0);
|
||||
currentList = directory.listFiles();
|
||||
currentIndex = 0;
|
||||
File file = findNextFile();
|
||||
if(file != null){
|
||||
return file;
|
||||
}
|
||||
}
|
||||
|
||||
endOfTree = true;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,6 @@
|
|||
package com.nytimes.android.external.store.middleware.fs.impl;
|
||||
package com.nytimes.android.external.fs.impl;
|
||||
|
||||
import com.nytimes.android.external.fs.Util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
|
@ -8,11 +10,11 @@ import okio.BufferedSink;
|
|||
import okio.BufferedSource;
|
||||
import okio.Okio;
|
||||
|
||||
import static com.google.common.io.Files.createParentDirs;
|
||||
import static java.lang.String.format;
|
||||
|
||||
class FSFile {
|
||||
|
||||
private final Util util = new Util();
|
||||
private final String path;
|
||||
private final File file;
|
||||
|
||||
|
@ -22,7 +24,7 @@ class FSFile {
|
|||
if (file.exists() && file.isDirectory()) {
|
||||
throw new FileNotFoundException(format("expecting a file at %s, instead found a directory", path));
|
||||
}
|
||||
createParentDirs(this.file);
|
||||
util.createParentDirs(this.file);
|
||||
}
|
||||
|
||||
public boolean exists() {
|
||||
|
@ -66,9 +68,10 @@ class FSFile {
|
|||
|
||||
|
||||
public BufferedSource source() throws FileNotFoundException {
|
||||
return Okio.buffer(Okio.source(file));
|
||||
if (file.exists()) {
|
||||
return Okio.buffer(Okio.source(file));
|
||||
}
|
||||
throw new FileNotFoundException(path);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -1,27 +1,22 @@
|
|||
package com.nytimes.android.external.store.middleware.fs.impl;
|
||||
package com.nytimes.android.external.fs.impl;
|
||||
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.collect.FluentIterable;
|
||||
import com.google.common.io.Files;
|
||||
import com.nytimes.android.external.store.middleware.fs.FileSystem;
|
||||
import com.nytimes.android.external.cache.CacheLoader;
|
||||
import com.nytimes.android.external.cache.LoadingCache;
|
||||
import com.nytimes.android.external.fs.FileSystem;
|
||||
import com.nytimes.android.external.fs.Util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
|
||||
import okio.BufferedSource;
|
||||
|
||||
import static com.google.common.cache.CacheBuilder.newBuilder;
|
||||
import static com.google.common.io.Files.createParentDirs;
|
||||
import static com.google.common.io.Files.simplifyPath;
|
||||
import static com.nytimes.android.external.cache.CacheBuilder.newBuilder;
|
||||
import static java.lang.String.format;
|
||||
|
||||
|
||||
/**
|
||||
* implements a {@link FileSystem} as regular files on disk in a specific document root (kind of like a root jail)
|
||||
* <p>
|
||||
|
@ -29,6 +24,7 @@ import static java.lang.String.format;
|
|||
*/
|
||||
public class FileSystemImpl implements FileSystem {
|
||||
|
||||
private final Util util = new Util();
|
||||
final LoadingCache<String, FSFile> files;
|
||||
final File root;
|
||||
|
||||
|
@ -43,7 +39,7 @@ public class FileSystemImpl implements FileSystem {
|
|||
}
|
||||
});
|
||||
|
||||
createParentDirs(root);
|
||||
util.createParentDirs(root);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -63,18 +59,23 @@ public class FileSystemImpl implements FileSystem {
|
|||
|
||||
@Override
|
||||
public Collection<String> list(String directory) throws FileNotFoundException {
|
||||
return findFiles(directory).transform(new Function<FSFile, String>() {
|
||||
@Override
|
||||
public String apply(FSFile fsFile) {
|
||||
return fsFile.path();
|
||||
}
|
||||
}).toList();
|
||||
|
||||
Collection<FSFile> foundFiles = findFiles(directory);
|
||||
Collection<String> names = new ArrayList<>(foundFiles.size());
|
||||
Iterator<FSFile> iterator = foundFiles.iterator();
|
||||
while ((iterator.hasNext())) {
|
||||
names.add(iterator.next().path());
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteAll(String directory) throws FileNotFoundException {
|
||||
for (FSFile file : findFiles(directory).toList()) {
|
||||
file.delete();
|
||||
|
||||
Collection<FSFile> foundFiles = findFiles(directory);
|
||||
Iterator<FSFile> iterator = foundFiles.iterator();
|
||||
while ((iterator.hasNext())) {
|
||||
iterator.next().delete();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -87,33 +88,24 @@ public class FileSystemImpl implements FileSystem {
|
|||
return files.getUnchecked(cleanPath(path));
|
||||
}
|
||||
|
||||
private static String cleanPath(String dirty) {
|
||||
return simplifyPath(dirty);
|
||||
private String cleanPath(String dirty) {
|
||||
return util.simplifyPath(dirty);
|
||||
}
|
||||
|
||||
private FluentIterable<FSFile> findFiles(String path) throws FileNotFoundException {
|
||||
private Collection<FSFile> findFiles(String path) throws FileNotFoundException {
|
||||
|
||||
File searchRoot = new File(root, simplifyPath(path));
|
||||
File searchRoot = new File(root, util.simplifyPath(path));
|
||||
if (searchRoot.exists() && searchRoot.isFile()) {
|
||||
throw new FileNotFoundException(format("expecting a directory at %s, instead found a file", path));
|
||||
}
|
||||
return Files.fileTreeTraverser()
|
||||
.breadthFirstTraversal(searchRoot)
|
||||
.filter(new Predicate<File>() {
|
||||
@Override
|
||||
public boolean apply(File file1) {
|
||||
return file1.isFile();
|
||||
}
|
||||
})
|
||||
.transform(new Function<File, FSFile>() {
|
||||
@Override
|
||||
public FSFile apply(File file) {
|
||||
return files.getUnchecked(simplifyPath(file.getPath()
|
||||
.replaceFirst(root.getPath(), "")));
|
||||
}
|
||||
});
|
||||
|
||||
Collection<FSFile> foundFiles = new ArrayList<>();
|
||||
BreadthFirstFileTreeIterator iterator = new BreadthFirstFileTreeIterator(searchRoot);
|
||||
while (iterator.hasNext()) {
|
||||
File file = (File) iterator.next();
|
||||
foundFiles.add(files.getUnchecked(util.simplifyPath(file.getPath()
|
||||
.replaceFirst(root.getPath(), ""))));
|
||||
}
|
||||
return foundFiles;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
|
@ -1,17 +1,14 @@
|
|||
package com.nytimes.android.external.store.middleware.fs;
|
||||
package com.nytimes.android.external.fs;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.nytimes.android.external.store.middleware.fs.impl.BaseTestCase;
|
||||
import com.nytimes.android.external.store.middleware.fs.impl.FileSystemImpl;
|
||||
import com.nytimes.android.external.fs.impl.BaseTestCase;
|
||||
import com.nytimes.android.external.fs.impl.FileSystemImpl;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
@ -22,6 +19,8 @@ import static com.google.common.base.Charsets.UTF_8;
|
|||
import static com.google.common.io.Files.createTempDir;
|
||||
import static java.util.Arrays.asList;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class MultiTest extends BaseTestCase {
|
||||
|
||||
private static final Map<String, List<String>> fileData
|
||||
|
@ -30,48 +29,42 @@ public class MultiTest extends BaseTestCase {
|
|||
.put("/foo/bar/baz.xyz", asList("sasffvSFv", "AsfgsdvzsfbvasFgae", "szfvzsfszfvzsvbzdsfb"))
|
||||
.build();
|
||||
|
||||
|
||||
private static FileSystem fileSystem;
|
||||
|
||||
@Before
|
||||
public void start() throws IOException {
|
||||
private FileSystem createAndPopulateTestFileSystem() throws IOException {
|
||||
File baseDir = createTempDir();
|
||||
|
||||
fileSystem = new FileSystemImpl(baseDir);
|
||||
FileSystem fileSystem = new FileSystemImpl(baseDir);
|
||||
for (String path : fileData.keySet()) {
|
||||
for (String data : fileData.get(path)) {
|
||||
fileSystem.write(path, source(data));
|
||||
BufferedSource source = source(data);
|
||||
fileSystem.write(path, source);
|
||||
source.close();
|
||||
}
|
||||
}
|
||||
assertThat(fileSystem.list("/").size()).isEqualTo(fileData.size());
|
||||
return fileSystem;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void deleteAll() throws IOException {
|
||||
FileSystem fileSystem = createAndPopulateTestFileSystem();
|
||||
fileSystem.deleteAll("/");
|
||||
assertEquals(0, fileSystem.list("/").size());
|
||||
|
||||
assertThat(fileSystem.list("/").size()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listNCompare() throws IOException {
|
||||
Map<String, List<String>> listData = new HashMap<>();
|
||||
FileSystem fileSystem = createAndPopulateTestFileSystem();
|
||||
int assertCount = 0;
|
||||
for (String path : fileSystem.list("/")) {
|
||||
String data = fileSystem.read(path).readUtf8();
|
||||
List<String> written = fileData.get(path);
|
||||
assertEquals(data, written.get(written.size() - 1));
|
||||
String writtenData = written.get(written.size() - 1);
|
||||
assertThat(data).isEqualTo(writtenData);
|
||||
assertCount++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@After
|
||||
public void stop() {
|
||||
|
||||
assertThat(assertCount).isEqualTo(fileData.size());
|
||||
}
|
||||
|
||||
private static BufferedSource source(String data) {
|
||||
return Okio.buffer(Okio.source(new ByteArrayInputStream(data.getBytes(UTF_8))));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,12 +1,12 @@
|
|||
package com.nytimes.android.external.store;
|
||||
package com.nytimes.android.external.fs;
|
||||
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.nytimes.android.external.store.base.Fetcher;
|
||||
import com.nytimes.android.external.store.base.Store;
|
||||
import com.nytimes.android.external.store.base.impl.BarCode;
|
||||
import com.nytimes.android.external.store.base.impl.ParsingStoreBuilder;
|
||||
import com.nytimes.android.external.store.middleware.GsonSourceParser;
|
||||
import com.nytimes.android.external.store.middleware.SourcePersister;
|
||||
import com.nytimes.android.store.base.Fetcher;
|
||||
import com.nytimes.android.store.base.Store;
|
||||
import com.nytimes.android.store.base.impl.BarCode;
|
||||
import com.nytimes.android.store.base.impl.ParsingStoreBuilder;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
|
@ -1,13 +1,11 @@
|
|||
package com.nytimes.android.external.store;
|
||||
package com.nytimes.android.external.fs;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.nytimes.android.external.store.middleware.GsonSourceParser;
|
||||
import com.nytimes.android.external.store.middleware.SourceFileReader;
|
||||
import com.nytimes.android.external.store.middleware.SourceFileWriter;
|
||||
import com.nytimes.android.store.base.Fetcher;
|
||||
import com.nytimes.android.store.base.Store;
|
||||
import com.nytimes.android.store.base.impl.BarCode;
|
||||
import com.nytimes.android.store.base.impl.ParsingStoreBuilder;
|
||||
import com.nytimes.android.external.store.base.Fetcher;
|
||||
import com.nytimes.android.external.store.base.Store;
|
||||
import com.nytimes.android.external.store.base.impl.BarCode;
|
||||
import com.nytimes.android.external.store.base.impl.ParsingStoreBuilder;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
|
@ -51,7 +49,6 @@ public class SourceFilerReaderWriterStoreTest {
|
|||
|
||||
String sourceData = new Gson().toJson(foo);
|
||||
|
||||
|
||||
BufferedSource source = source(sourceData);
|
||||
Observable<BufferedSource> value = Observable.just(source);
|
||||
when(fetcher.fetch(barCode))
|
39
filesystem/src/test/java/com/nytimes/android/external/fs/UtilTest.java
vendored
Normal file
39
filesystem/src/test/java/com/nytimes/android/external/fs/UtilTest.java
vendored
Normal file
|
@ -0,0 +1,39 @@
|
|||
package com.nytimes.android.external.fs;
|
||||
|
||||
import com.nytimes.android.external.fs.impl.BaseTestCase;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class UtilTest extends BaseTestCase {
|
||||
|
||||
private final Util util = new Util();
|
||||
|
||||
@Test
|
||||
public void simplifyPathTest() {
|
||||
assertThat(util.simplifyPath("/a/b/c/d")).isEqualTo("/a/b/c/d");
|
||||
assertThat(util.simplifyPath("/a/../b/")).isEqualTo("/b");
|
||||
assertThat(util.simplifyPath("/a/./b/c/../d")).isEqualTo("/a/b/d");
|
||||
assertThat(util.simplifyPath("./a")).isEqualTo("/a");
|
||||
assertThat(util.simplifyPath(null)).isEqualTo("");
|
||||
assertThat(util.simplifyPath("")).isEqualTo("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createParentDirTest() throws IOException {
|
||||
File child = mock(File.class);
|
||||
File parent = mock(File.class);
|
||||
when(child.getCanonicalFile()).thenReturn(child);
|
||||
when(child.getParentFile()).thenReturn(parent);
|
||||
when(parent.isDirectory()).thenReturn(true);
|
||||
util.createParentDirs(child);
|
||||
verify(parent).mkdirs();
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.nytimes.android.external.store.middleware.fs.impl;
|
||||
package com.nytimes.android.external.fs.impl;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
|
@ -1,9 +1,8 @@
|
|||
package com.nytimes.android.external.store.middleware.fs.impl;
|
||||
package com.nytimes.android.external.fs.impl;
|
||||
|
||||
|
||||
import com.nytimes.android.external.store.middleware.fs.FileSystem;
|
||||
import com.nytimes.android.external.fs.FileSystem;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -18,6 +17,8 @@ import okio.Okio;
|
|||
import static com.google.common.base.Charsets.UTF_8;
|
||||
import static com.google.common.io.Files.createTempDir;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class SimpleTest extends BaseTestCase {
|
||||
|
||||
private static final String testString1 = "aszfbW#$%#$^&*5 r7ytjdfbv!@#R$\n@!#$%2354 wtyebfsdv\n";
|
||||
|
@ -47,9 +48,10 @@ public class SimpleTest extends BaseTestCase {
|
|||
@Test
|
||||
public void delete() throws IOException {
|
||||
fileSystem.write("/boo", source(testString1));
|
||||
assertEquals(testString1, fileSystem.read("/boo").readUtf8());
|
||||
assertThat(fileSystem.read("/boo").readUtf8()).isEqualTo(testString1);
|
||||
fileSystem.delete("/boo");
|
||||
assertFalse(fileSystem.exists("/boo"));
|
||||
assertThat(fileSystem.exists("/boo")).isFalse();
|
||||
assertThat(fileSystem.exists("/boo")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -59,9 +61,9 @@ public class SimpleTest extends BaseTestCase {
|
|||
BufferedSource source = fileSystem.read("/boo");
|
||||
fileSystem.delete("/boo");
|
||||
|
||||
assertFalse(fileSystem.exists("/boo"));
|
||||
assertEquals(testString1, source.readUtf8());
|
||||
assertFalse(fileSystem.exists("/boo"));
|
||||
assertThat(fileSystem.exists("/boo")).isFalse();
|
||||
assertThat(source.readUtf8()).isEqualTo(testString1);
|
||||
assertThat(fileSystem.exists("/boo")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -69,23 +71,22 @@ public class SimpleTest extends BaseTestCase {
|
|||
|
||||
fileSystem.write("/boo", source(testString1));
|
||||
|
||||
|
||||
BufferedSource source1 = fileSystem.read("/boo"); // open a source and hang onto it
|
||||
fileSystem.delete("/boo"); // now delete the file
|
||||
|
||||
assertFalse(fileSystem.exists("/boo")); // exists() should say it's gone even though
|
||||
assertThat(fileSystem.exists("/boo")).isFalse(); // exists() should say it's gone even though
|
||||
// we still have a source to it
|
||||
fileSystem.write("/boo", source(testString2)); // and now un-delete it by writing a new version
|
||||
assertTrue(fileSystem.exists("/boo")); // exists() should say it's back
|
||||
assertThat(fileSystem.exists("/boo")).isTrue(); // exists() should say it's back
|
||||
BufferedSource source2 = fileSystem.read("/boo"); // open another source and hang onto it
|
||||
fileSystem.delete("/boo"); // now delete the file *again*
|
||||
|
||||
// the sources should have the correct data even though the file was deleted/re-written/deleted
|
||||
assertEquals(testString1, source1.readUtf8());
|
||||
assertEquals(testString2, source2.readUtf8());
|
||||
assertThat(source1.readUtf8()).isEqualTo(testString1);
|
||||
assertThat(source2.readUtf8()).isEqualTo(testString2);
|
||||
|
||||
// now that the 2 sources have been fully read, you shouldn't be able to read it
|
||||
assertFalse(fileSystem.exists("/boo"));
|
||||
assertThat(fileSystem.exists("/boo")).isFalse();
|
||||
}
|
||||
|
||||
private void diffMe(String first, String second) {
|
||||
|
@ -96,7 +97,7 @@ public class SimpleTest extends BaseTestCase {
|
|||
}
|
||||
|
||||
try {
|
||||
assertEquals(testString1, fileSystem.read(second).readUtf8());
|
||||
assertThat(fileSystem.read(second).readUtf8()).isEqualTo(testString1);
|
||||
} catch (IOException error) {
|
||||
throw new RuntimeException("unable to read from " + second, error);
|
||||
}
|
||||
|
@ -108,18 +109,12 @@ public class SimpleTest extends BaseTestCase {
|
|||
}
|
||||
|
||||
try {
|
||||
assertEquals(testString2, fileSystem.read(first).readUtf8());
|
||||
assertThat(fileSystem.read(first).readUtf8()).isEqualTo(testString2);
|
||||
} catch (IOException error) {
|
||||
throw new RuntimeException("unable to read from " + first, error);
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void stop() {
|
||||
// Write some after test execution steps.
|
||||
//Added above to remove PMD violations.
|
||||
}
|
||||
|
||||
private static BufferedSource source(String data) {
|
||||
return Okio.buffer(Okio.source(new ByteArrayInputStream(data.getBytes(UTF_8))));
|
||||
}
|
1
filesystem/version.properties
Normal file
1
filesystem/version.properties
Normal file
|
@ -0,0 +1 @@
|
|||
version=0.1
|
|
@ -1,17 +0,0 @@
|
|||
# Project-wide Gradle settings.
|
||||
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx1536m
|
||||
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
123
gradle/maven-push.gradle
Normal file
123
gradle/maven-push.gradle
Normal file
|
@ -0,0 +1,123 @@
|
|||
apply plugin: "maven"
|
||||
apply plugin: "signing"
|
||||
|
||||
def isReleaseBuild() {
|
||||
return VERSION_NAME.contains("SNAPSHOT") == false
|
||||
}
|
||||
|
||||
def getReleaseRepositoryUrl() {
|
||||
return hasProperty("RELEASE_REPOSITORY_URL") ? RELEASE_REPOSITORY_URL
|
||||
: "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
|
||||
}
|
||||
|
||||
def getSnapshotRepositoryUrl() {
|
||||
return hasProperty("SNAPSHOT_REPOSITORY_URL") ? SNAPSHOT_REPOSITORY_URL
|
||||
: "https://oss.sonatype.org/content/repositories/snapshots/"
|
||||
}
|
||||
|
||||
def getRepositoryUsername() {
|
||||
return hasProperty("SONATYPE_USERNAME") ? SONATYPE_USERNAME : ""
|
||||
}
|
||||
|
||||
def getRepositoryPassword() {
|
||||
return hasProperty("SONATYPE_PASSWORD") ? SONATYPE_PASSWORD : ""
|
||||
}
|
||||
|
||||
afterEvaluate { project ->
|
||||
uploadArchives {
|
||||
repositories {
|
||||
mavenDeployer {
|
||||
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
|
||||
|
||||
pom.groupId = GROUP
|
||||
pom.artifactId = POM_ARTIFACT_ID
|
||||
pom.version = VERSION_NAME
|
||||
|
||||
repository(url: getReleaseRepositoryUrl()) {
|
||||
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
|
||||
}
|
||||
snapshotRepository(url: getSnapshotRepositoryUrl()) {
|
||||
authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
|
||||
}
|
||||
|
||||
pom.project {
|
||||
name POM_NAME
|
||||
packaging POM_PACKAGING
|
||||
description POM_DESCRIPTION
|
||||
url POM_URL
|
||||
|
||||
scm {
|
||||
url POM_SCM_URL
|
||||
connection POM_SCM_CONNECTION
|
||||
developerConnection POM_SCM_DEV_CONNECTION
|
||||
}
|
||||
|
||||
licenses {
|
||||
license {
|
||||
name POM_LICENCE_NAME
|
||||
url POM_LICENCE_URL
|
||||
distribution POM_LICENCE_DIST
|
||||
}
|
||||
}
|
||||
|
||||
developers {
|
||||
developer {
|
||||
id POM_DEVELOPER_ID
|
||||
name POM_DEVELOPER_NAME
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
signing {
|
||||
required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
|
||||
sign configurations.archives
|
||||
}
|
||||
|
||||
task androidJavadocs(type: Javadoc) {
|
||||
source = android.sourceSets.main.java.srcDirs
|
||||
ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
|
||||
classpath += files(ext.androidJar)
|
||||
}
|
||||
|
||||
task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
|
||||
classifier = "javadoc"
|
||||
from androidJavadocs.destinationDir
|
||||
}
|
||||
|
||||
task androidSourcesJar(type: Jar) {
|
||||
classifier = "sources"
|
||||
from android.sourceSets.main.java.sourceFiles
|
||||
}
|
||||
|
||||
if (JavaVersion.current().isJava8Compatible()) {
|
||||
allprojects {
|
||||
tasks.withType(Javadoc) {
|
||||
options.addStringOption("Xdoclint:none", "-quiet")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
artifacts {
|
||||
archives androidSourcesJar
|
||||
archives androidJavadocsJar
|
||||
}
|
||||
|
||||
task installArchives(type: Upload) {
|
||||
group = "Upload"
|
||||
description = "Installs the ':archives' artifacts into the local Maven repository."
|
||||
|
||||
configuration = configurations.archives
|
||||
|
||||
repositories {
|
||||
mavenInstaller {
|
||||
pom.groupId = GROUP
|
||||
pom.artifactId = POM_ARTIFACT_ID
|
||||
pom.version = VERSION_NAME
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue