├── .gitignore
├── .idea
└── encodings.xml
├── .travis.yml
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── ic_launcher-web.png
│ ├── java
│ └── com
│ │ └── tomclaw
│ │ └── cache
│ │ └── demo
│ │ ├── App.java
│ │ ├── CacheAdapter.java
│ │ ├── MainActivity.java
│ │ ├── Randomizer.java
│ │ ├── executor
│ │ ├── MainExecutor.java
│ │ ├── Task.java
│ │ ├── TaskExecutor.java
│ │ └── WeakObjectTask.java
│ │ └── task
│ │ ├── ClearCacheTask.java
│ │ └── CreateFileTask.java
│ └── res
│ ├── drawable-v24
│ └── ic_launcher_foreground.xml
│ ├── drawable
│ ├── dots.xml
│ ├── ic_file_plus.xml
│ ├── ic_launcher_background.xml
│ └── ic_trash_can.xml
│ ├── layout
│ ├── activity_main.xml
│ └── cache_item.xml
│ ├── mipmap-anydpi-v26
│ ├── ic_launcher.xml
│ └── ic_launcher_round.xml
│ ├── mipmap-hdpi
│ ├── ic_launcher.png
│ ├── ic_launcher_foreground.png
│ └── ic_launcher_round.png
│ ├── mipmap-mdpi
│ ├── ic_launcher.png
│ ├── ic_launcher_foreground.png
│ └── ic_launcher_round.png
│ ├── mipmap-xhdpi
│ ├── ic_launcher.png
│ ├── ic_launcher_foreground.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxhdpi
│ ├── ic_launcher.png
│ ├── ic_launcher_foreground.png
│ └── ic_launcher_round.png
│ ├── mipmap-xxxhdpi
│ ├── ic_launcher.png
│ ├── ic_launcher_foreground.png
│ └── ic_launcher_round.png
│ └── values
│ ├── colors.xml
│ ├── ic_launcher_background.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── cache
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ └── java
│ │ └── com
│ │ └── tomclaw
│ │ └── cache
│ │ ├── DiskLruCache.java
│ │ ├── FileManager.java
│ │ ├── Journal.java
│ │ ├── Logger.java
│ │ ├── Record.java
│ │ ├── RecordComparator.java
│ │ ├── RecordNotFoundException.java
│ │ ├── SimpleFileManager.java
│ │ └── SimpleLogger.java
│ └── test
│ └── java
│ └── com
│ └── tomclaw
│ └── cache
│ ├── Helpers.java
│ ├── JournalUnitTest.java
│ └── RecordComparatorUnitTest.java
├── cache_icon.png
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/libraries
5 | /.idea/modules.xml
6 | /.idea/workspace.xml
7 | .DS_Store
8 | /build
9 | /captures
10 | .externalNativeBuild
11 |
12 | *.class
13 | *.zip
14 | *.apk
15 | *.iml
16 |
17 | # IDE folders #
18 | gen/
19 | bin/
20 | out/
21 | local.properties
22 | proguard_logs/
23 | projectFilesBackup/
24 | .idea/*
25 | !.idea/codeStyleSettings.xml
26 | !.idea/encodings.xml
27 | !.idea/inspectionProfiles/
28 |
29 | # Gradle files
30 | .gradle/
31 | *build/
32 |
33 | # Local configuration file (sdk path, etc)
34 | local.properties
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 | jdk: oraclejdk8
3 |
4 | env:
5 | matrix:
6 | - ANDROID_TARGET=android-25 ANDROID_ABI=google_apis/armeabi-v7a
7 |
8 | android:
9 | components:
10 | - tools
11 | - platform-tools
12 | - build-tools-25.0.3
13 | - android-25
14 | - extra
15 | - extra-android-support
16 | - extra-android-m2repository
17 |
18 | licenses:
19 | - 'android-sdk-license-.+'
20 |
21 | before_script:
22 | - chmod +x gradlew
23 |
24 | script: ./gradlew test dependencies || true
25 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Igor Solkin
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Disk LRU Cache [](https://jitpack.io/#solkin/disk-lru-cache) []( https://android-arsenal.com/details/1/7454 )
2 |
3 | Disk LRU (least recently used) cache with persisted journal.
4 | This cache has specific capacity and location.
5 | Rarely requested files are evicted by actively used.
6 |
7 | Lightweight and extremely easy to use.
8 |
9 | 
10 |
11 | ### Add dependency
12 | **Step 1.** Add the JitPack repository to your build file
13 | ```groovy
14 | allprojects {
15 | repositories {
16 | ...
17 | maven { url 'https://jitpack.io' }
18 | }
19 | }
20 | ```
21 | **Step 2.** Add the dependency
22 | ```groovy
23 | implementation 'com.github.solkin:disk-lru-cache:1.4'
24 | ```
25 |
26 | ### Create DiskLruCache
27 | ```java
28 | long CACHE_SIZE = 500 * 1024; // Size in bytes
29 | DiskLruCache cache = DiskLruCache.create(getCacheDir(), CACHE_SIZE);
30 | ```
31 |
32 | ### Add file into cache
33 | To manage some files by cache you just need to invoke `put` method like any `Map`.
34 |
35 | Key - any string to request this file from cache.
36 |
37 | File - file, that will be moved into cache.
38 |
39 | ```java
40 | String key = "some-key";
41 | File file = File.createTempFile("random", ".dat");
42 | cache.put(key, file);
43 | ```
44 |
45 | ### Getting file from cache
46 | To get file from cache, just invoke `get` method. Yes, also like any `Map`.
47 |
48 | Key is the same you put this file into cache
49 |
50 | This method will return `File` you put into cache or `null`, if file was evicted from cache.
51 |
52 | ```java
53 | String key = "some-key";
54 | File file = cache.get(key);
55 | ```
56 |
57 | ### Delete file from cache
58 | To delete file from cache, just invoke `delete` method.
59 |
60 | Key is the same you put this file into cache
61 |
62 | File will be deleted from cache and from journal.
63 |
64 | ```java
65 | String key = "some-key";
66 | cache.delete(key);
67 | ```
68 |
69 | ### Clear cache
70 | Sometime you may need to clear whole cache and drop all stored files.
71 |
72 | ```java
73 | cache().clearCache();
74 | ```
75 |
76 | ### List keys in cache
77 | To get all keys, managed by cache, invoke `keySet()` method.
78 |
79 | This will return `Set`.
80 |
81 | List all keys in cache may be useful to check all files, stored in cache.
82 |
83 | ```java
84 | Set keys = cache.keySet();
85 | ```
86 |
87 |
88 | ### Get cache status information
89 | There are some useful cache status information, that you can request.
90 |
91 | ```java
92 | cache.getCacheSize(); // Cache size in bytes, that you set up on cache creation.
93 | cache.getUsedSpace(); // Size of all files, stored in cache.
94 | cache.getFreeSpace(); // Free size in cache.
95 | cache.getJournalSize(); // Internal cache journal size in bytes.
96 | ```
97 |
98 |
99 | ### License
100 | MIT License
101 |
102 | Copyright (c) 2022 Igor Solkin
103 |
104 | Permission is hereby granted, free of charge, to any person obtaining a copy
105 | of this software and associated documentation files (the "Software"), to deal
106 | in the Software without restriction, including without limitation the rights
107 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
108 | copies of the Software, and to permit persons to whom the Software is
109 | furnished to do so, subject to the following conditions:
110 |
111 | The above copyright notice and this permission notice shall be included in all
112 | copies or substantial portions of the Software.
113 |
114 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
115 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
116 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
117 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
118 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
119 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
120 | SOFTWARE.
121 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdk 34
5 | namespace = "com.tomclaw.cache.demo"
6 | defaultConfig {
7 | applicationId "com.tomclaw.cache.demo"
8 | minSdkVersion 21
9 | targetSdkVersion 34
10 | versionCode 1
11 | versionName "1.1"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | compileOptions {
20 | sourceCompatibility JavaVersion.VERSION_17
21 | targetCompatibility JavaVersion.VERSION_17
22 | }
23 | }
24 |
25 | dependencies {
26 | implementation 'androidx.appcompat:appcompat:1.7.0'
27 | implementation 'com.google.android.material:material:1.12.0'
28 | implementation 'androidx.recyclerview:recyclerview:1.3.2'
29 | implementation project(path: ':cache')
30 | }
31 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
15 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/ic_launcher-web.png
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/App.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo;
2 |
3 | import android.app.Application;
4 |
5 | import com.tomclaw.cache.DiskLruCache;
6 |
7 | import java.io.File;
8 | import java.io.IOException;
9 |
10 | public class App extends Application {
11 |
12 | private static final long CACHE_SIZE = 500 * 1024;
13 |
14 | private static DiskLruCache cache;
15 |
16 | @Override
17 | public void onCreate() {
18 | super.onCreate();
19 | File cacheDir = getCacheDir();
20 | try {
21 | cache = DiskLruCache.create(cacheDir, CACHE_SIZE);
22 | } catch (IOException ignored) {
23 | }
24 | }
25 |
26 | public static DiskLruCache cache() {
27 | return cache;
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/CacheAdapter.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo;
2 |
3 | import android.content.Context;
4 | import android.view.LayoutInflater;
5 | import android.view.View;
6 | import android.view.ViewGroup;
7 | import android.widget.TextView;
8 |
9 | import androidx.annotation.NonNull;
10 | import androidx.recyclerview.widget.RecyclerView;
11 |
12 | import java.util.ArrayList;
13 | import java.util.List;
14 |
15 | public class CacheAdapter extends RecyclerView.Adapter {
16 |
17 | private final List cacheItems;
18 | private final LayoutInflater inflater;
19 |
20 | CacheAdapter(Context context) {
21 | this.inflater = LayoutInflater.from(context);
22 | this.cacheItems = new ArrayList<>();
23 | }
24 |
25 | @NonNull
26 | @Override
27 | public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
28 | View view = inflater.inflate(R.layout.cache_item, parent, false);
29 | return new ViewHolder(view);
30 | }
31 |
32 | @Override
33 | public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
34 | CacheItem item = cacheItems.get(position);
35 | holder.bindCacheItem(item);
36 | }
37 |
38 | @Override
39 | public int getItemCount() {
40 | return cacheItems.size();
41 | }
42 |
43 | void setCacheItems(List cacheItems) {
44 | this.cacheItems.clear();
45 | this.cacheItems.addAll(cacheItems);
46 | }
47 |
48 | public static class ViewHolder extends RecyclerView.ViewHolder {
49 |
50 | private final TextView title;
51 | private final TextView subtitle;
52 |
53 | ViewHolder(View itemView) {
54 | super(itemView);
55 | title = itemView.findViewById(R.id.title);
56 | subtitle = itemView.findViewById(R.id.subtitle);
57 | }
58 |
59 | void bindCacheItem(CacheItem item) {
60 | title.setText(item.getKey());
61 | subtitle.setText(item.getSize());
62 | }
63 |
64 | }
65 |
66 | static class CacheItem {
67 |
68 | private final String key;
69 | private final String size;
70 |
71 | CacheItem(String key, String size) {
72 | this.key = key;
73 | this.size = size;
74 | }
75 |
76 | String getKey() {
77 | return key;
78 | }
79 |
80 | String getSize() {
81 | return size;
82 | }
83 |
84 | }
85 |
86 | }
87 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.content.res.Resources;
5 | import android.os.Bundle;
6 | import android.view.View;
7 | import android.widget.ProgressBar;
8 | import android.widget.TextView;
9 |
10 | import androidx.appcompat.app.AppCompatActivity;
11 | import androidx.recyclerview.widget.LinearLayoutManager;
12 | import androidx.recyclerview.widget.RecyclerView;
13 |
14 | import com.tomclaw.cache.DiskLruCache;
15 | import com.tomclaw.cache.demo.executor.TaskExecutor;
16 | import com.tomclaw.cache.demo.task.ClearCacheTask;
17 | import com.tomclaw.cache.demo.task.CreateFileTask;
18 |
19 | import java.io.File;
20 | import java.util.ArrayList;
21 | import java.util.Collections;
22 | import java.util.List;
23 | import java.util.Set;
24 |
25 | import static com.tomclaw.cache.demo.App.cache;
26 |
27 | public class MainActivity extends AppCompatActivity {
28 |
29 | private TextView cacheSizeView;
30 | private TextView usedSpaceView;
31 | private TextView freeSpaceView;
32 | private TextView journalSizeView;
33 | private TextView filesCountView;
34 | private ProgressBar cacheUsageView;
35 |
36 | private CacheAdapter adapter;
37 |
38 | @Override
39 | protected void onCreate(Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 | setContentView(R.layout.activity_main);
42 |
43 | cacheSizeView = findViewById(R.id.cache_size);
44 | usedSpaceView = findViewById(R.id.used_space);
45 | freeSpaceView = findViewById(R.id.free_space);
46 | cacheUsageView = findViewById(R.id.cache_usage);
47 | journalSizeView = findViewById(R.id.journal_size);
48 | filesCountView = findViewById(R.id.files_count);
49 | View createFileButton = findViewById(R.id.create_file_button);
50 | View clearCacheButton = findViewById(R.id.clear_cache_button);
51 | createFileButton.setOnClickListener(v ->
52 | TaskExecutor.getInstance().execute(new CreateFileTask(MainActivity.this))
53 | );
54 | clearCacheButton.setOnClickListener(v ->
55 | TaskExecutor.getInstance().execute(new ClearCacheTask(MainActivity.this))
56 | );
57 |
58 | RecyclerView recyclerView = findViewById(R.id.recycler);
59 | recyclerView.setLayoutManager(new LinearLayoutManager(this));
60 | adapter = new CacheAdapter(this);
61 | recyclerView.setAdapter(adapter);
62 |
63 | bindViews();
64 | }
65 |
66 | @SuppressLint("NotifyDataSetChanged")
67 | public void bindViews() {
68 | DiskLruCache cache = cache();
69 | cacheSizeView.setText(formatBytes(cache.getCacheSize()));
70 | usedSpaceView.setText(formatBytes(cache.getUsedSpace()));
71 | freeSpaceView.setText(formatBytes(cache.getFreeSpace()));
72 | journalSizeView.setText(formatBytes(cache.getJournalSize()));
73 | filesCountView.setText(String.valueOf(cache.keySet().size()));
74 | cacheUsageView.setProgress((int) (100 * cache.getUsedSpace() / cache.getCacheSize()));
75 | List cacheItems = new ArrayList<>();
76 | Set keySet = Collections.unmodifiableSet(cache.keySet());
77 | for (String key : keySet) {
78 | File file = cache.get(key);
79 | cacheItems.add(new CacheAdapter.CacheItem(key, formatBytes(file.length())));
80 | }
81 | adapter.setCacheItems(cacheItems);
82 | adapter.notifyDataSetChanged();
83 | }
84 |
85 | public String formatBytes(long bytes) {
86 | Resources resources = getResources();
87 | if (bytes < 1024) {
88 | return resources.getString(R.string.bytes, bytes);
89 | } else if (bytes < 1024 * 1024) {
90 | return resources.getString(R.string.kibibytes, bytes / 1024.0f);
91 | } else if (bytes < 1024 * 1024 * 1024) {
92 | return resources.getString(R.string.mibibytes, bytes / 1024.0f / 1024.0f);
93 | } else {
94 | return resources.getString(R.string.gigibytes, bytes / 1024.0f / 1024.0f / 1024.0f);
95 | }
96 | }
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/Randomizer.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo;
2 |
3 | import java.util.Random;
4 |
5 | public class Randomizer {
6 |
7 | public static Random random = new Random(System.currentTimeMillis());
8 |
9 | public static String generateRandomString() {
10 | return generateRandomString(16);
11 | }
12 |
13 | public static String generateRandomString(int length) {
14 | return generateRandomString(random, length, length);
15 | }
16 |
17 | public static String generateRandomString(Random r, int minChars, int maxChars) {
18 | int wordLength = minChars;
19 | int delta = maxChars - minChars;
20 | if (delta > 0) {
21 | wordLength += r.nextInt(delta);
22 | }
23 | StringBuilder sb = new StringBuilder(wordLength);
24 | for (int i = 0; i < wordLength; i++) {
25 | char tmp = (char) ('a' + r.nextInt('z' - 'a'));
26 | sb.append(tmp);
27 | }
28 | return sb.toString();
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/executor/MainExecutor.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo.executor;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 |
6 | @SuppressWarnings({"WeakerAccess"})
7 | public class MainExecutor {
8 |
9 | private static Handler mainHandler = new Handler(Looper.getMainLooper());
10 |
11 | public static boolean isMainThread() {
12 | return mainHandler.getLooper().getThread() == Thread.currentThread();
13 | }
14 |
15 | /**
16 | * Performs a task on the main thread. If the current thread is main, execution immediately.
17 | *
18 | * @param runnable to execute
19 | */
20 | public static void execute(Runnable runnable) {
21 | if (isMainThread()) {
22 | runnable.run();
23 | } else {
24 | mainHandler.post(runnable);
25 | }
26 | }
27 |
28 | /**
29 | * Executes runnable on the main thread after specified delay.
30 | *
31 | * @param runnable to execute
32 | * @param delay delay in milliseconds until the code will be executed
33 | */
34 | public static void executeLater(Runnable runnable, long delay) {
35 | mainHandler.postDelayed(runnable, delay);
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/executor/Task.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo.executor;
2 |
3 | @SuppressWarnings("WeakerAccess")
4 | public abstract class Task implements Runnable {
5 |
6 | @Override
7 | public void run() {
8 | try {
9 | executeBackground();
10 | onSuccessBackground();
11 | MainExecutor.execute(new Runnable() {
12 | @Override
13 | public void run() {
14 | onPostExecuteMain();
15 | onSuccessMain();
16 | }
17 | });
18 | } catch (final Throwable ex) {
19 | onFailBackground();
20 | MainExecutor.execute(new Runnable() {
21 | @Override
22 | public void run() {
23 | onPostExecuteMain();
24 | onFailMain(ex);
25 | }
26 | });
27 | }
28 | }
29 |
30 | public boolean isPreExecuteRequired() {
31 | return false;
32 | }
33 |
34 | public void onPreExecuteMain() {
35 | }
36 |
37 | public abstract void executeBackground() throws Throwable;
38 |
39 | public void onPostExecuteMain() {
40 | }
41 |
42 | public void onSuccessBackground() {
43 | }
44 |
45 | public void onFailBackground() {
46 | }
47 |
48 | public void onSuccessMain() {
49 | }
50 |
51 | public void onFailMain(Throwable ex) {
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/executor/TaskExecutor.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo.executor;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | @SuppressWarnings({"WeakerAccess"})
7 | public class TaskExecutor {
8 |
9 | private final ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
10 |
11 | private static class Holder {
12 |
13 | static TaskExecutor instance = new TaskExecutor();
14 |
15 | }
16 |
17 | public static TaskExecutor getInstance() {
18 | return Holder.instance;
19 | }
20 |
21 | public void execute(final Task task) {
22 | if (task.isPreExecuteRequired()) {
23 | MainExecutor.execute(new Runnable() {
24 | @Override
25 | public void run() {
26 | task.onPreExecuteMain();
27 | threadExecutor.submit(task);
28 | }
29 | });
30 | } else {
31 | threadExecutor.submit(task);
32 | }
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/executor/WeakObjectTask.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo.executor;
2 |
3 | import java.lang.ref.WeakReference;
4 |
5 | @SuppressWarnings({"WeakerAccess"})
6 | public abstract class WeakObjectTask extends Task {
7 |
8 | private final WeakReference weakObject;
9 |
10 | public WeakObjectTask(W object) {
11 | this.weakObject = new WeakReference<>(object);
12 | }
13 |
14 | public W getWeakObject() {
15 | return weakObject.get();
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/task/ClearCacheTask.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo.task;
2 |
3 | import android.content.Context;
4 |
5 | import com.tomclaw.cache.demo.MainActivity;
6 | import com.tomclaw.cache.demo.executor.WeakObjectTask;
7 |
8 | import java.io.IOException;
9 |
10 | import static com.tomclaw.cache.demo.App.cache;
11 |
12 | public class ClearCacheTask extends WeakObjectTask {
13 |
14 | public ClearCacheTask(MainActivity activity) {
15 | super(activity);
16 | }
17 |
18 | @Override
19 | public void executeBackground() {
20 | Context context = getWeakObject();
21 | if (context != null) {
22 | try {
23 | cache().clearCache();
24 | } catch (IOException ignored) {
25 | }
26 | }
27 | }
28 |
29 | @Override
30 | public void onSuccessMain() {
31 | MainActivity activity = getWeakObject();
32 | if (activity != null) {
33 | activity.bindViews();
34 | }
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/app/src/main/java/com/tomclaw/cache/demo/task/CreateFileTask.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache.demo.task;
2 |
3 | import android.content.Context;
4 |
5 | import com.tomclaw.cache.demo.MainActivity;
6 | import com.tomclaw.cache.demo.Randomizer;
7 | import com.tomclaw.cache.demo.executor.WeakObjectTask;
8 |
9 | import java.io.DataOutputStream;
10 | import java.io.File;
11 | import java.io.FileOutputStream;
12 |
13 | import static com.tomclaw.cache.demo.App.cache;
14 |
15 | public class CreateFileTask extends WeakObjectTask {
16 |
17 | public CreateFileTask(MainActivity activity) {
18 | super(activity);
19 | }
20 |
21 | @SuppressWarnings("TryFinallyCanBeTryWithResources")
22 | @Override
23 | public void executeBackground() throws Throwable {
24 | Context context = getWeakObject();
25 | if (context != null) {
26 | String extension = Randomizer.generateRandomString(3);
27 | File file = File.createTempFile("rnd", "." + extension);
28 | DataOutputStream stream = null;
29 | try {
30 | stream = new DataOutputStream(new FileOutputStream(file));
31 | int blocks = 2000 + Randomizer.random.nextInt(6000);
32 | for (int c = 0; c < blocks; c++) {
33 | stream.writeLong(Randomizer.random.nextLong());
34 | stream.flush();
35 | }
36 | } finally {
37 | if (stream != null) {
38 | stream.close();
39 | }
40 | }
41 | String key = Randomizer.generateRandomString();
42 | cache().put(key, file);
43 | }
44 | }
45 |
46 | @Override
47 | public void onSuccessMain() {
48 | MainActivity activity = getWeakObject();
49 | if (activity != null) {
50 | activity.bindViews();
51 | }
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/dots.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_file_plus.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_trash_can.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
16 |
17 |
25 |
26 |
31 |
32 |
33 |
34 |
39 |
40 |
48 |
49 |
54 |
55 |
56 |
57 |
62 |
63 |
71 |
72 |
77 |
78 |
79 |
80 |
85 |
86 |
94 |
95 |
100 |
101 |
102 |
103 |
108 |
109 |
117 |
118 |
123 |
124 |
125 |
126 |
133 |
134 |
142 |
143 |
147 |
148 |
163 |
164 |
179 |
180 |
181 |
182 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/cache_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
20 |
21 |
28 |
29 |
40 |
41 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3c6382
4 | #2d4a66
5 | #823c40
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #0A3D62
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | LRU Cache
3 | Cache size:
4 | Used space
5 | Free space
6 | Create file
7 | %d B
8 | %.1f KB
9 | %.1f MB
10 | %.1f GB
11 | Journal size
12 | Files count
13 | Clear cache
14 |
15 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 |
3 | repositories {
4 | google()
5 | mavenCentral()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:8.8.1'
9 | }
10 | }
11 |
12 | allprojects {
13 | repositories {
14 | google()
15 | mavenCentral()
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/cache/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/cache/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'maven-publish'
4 | }
5 |
6 | android {
7 | compileSdk 34
8 | namespace = "com.tomclaw.cache"
9 | defaultConfig {
10 | minSdkVersion 16
11 | targetSdkVersion 34
12 | }
13 |
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 |
21 | publishing {
22 | singleVariant('release') {
23 | withSourcesJar()
24 | }
25 | }
26 | }
27 |
28 | dependencies {
29 | testImplementation 'junit:junit:4.13.2'
30 | }
31 |
32 | publishing {
33 | publications {
34 | release(MavenPublication) {
35 | groupId = 'com.tomclaw.cache'
36 | artifactId = 'cache'
37 | version = '1.7'
38 |
39 | afterEvaluate {
40 | from components.findByName('release')
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/cache/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/cache/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/cache/src/main/java/com/tomclaw/cache/DiskLruCache.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.nio.charset.Charset;
6 | import java.security.MessageDigest;
7 | import java.security.NoSuchAlgorithmException;
8 | import java.util.HashSet;
9 | import java.util.Set;
10 |
11 | @SuppressWarnings({"unused", "WeakerAccess", "UnusedReturnValue"})
12 | public class DiskLruCache {
13 |
14 | public static final Charset UTF_8 = Charset.forName("UTF-8");
15 | public static final String HASH_ALGORITHM = "MD5";
16 |
17 | private final Journal journal;
18 | private final long cacheSize;
19 | private final FileManager fileManager;
20 | private final Logger logger;
21 |
22 | private DiskLruCache(FileManager fileManager, Journal journal, Logger logger, long cacheSize) {
23 | this.fileManager = fileManager;
24 | this.journal = journal;
25 | this.logger = logger;
26 | this.cacheSize = cacheSize;
27 | }
28 |
29 | public static DiskLruCache create(File cacheDir, long cacheSize) throws IOException {
30 | FileManager fileManager = new SimpleFileManager(cacheDir);
31 | Logger logger = new SimpleLogger(false);
32 | return create(fileManager, logger, cacheSize);
33 | }
34 |
35 | public static DiskLruCache create(FileManager fileManager, Logger logger, long cacheSize) throws IOException {
36 | fileManager.prepare();
37 | Journal journal = Journal.readJournal(fileManager, logger);
38 | return new DiskLruCache(fileManager, journal, logger, cacheSize);
39 | }
40 |
41 | public File put(String key, File file) throws IOException {
42 | synchronized (journal) {
43 | assertKeyValid(key);
44 | String name = generateName(key, file);
45 | long time = System.currentTimeMillis();
46 | long fileSize = file.length();
47 | Record record = new Record(key, name, time, fileSize);
48 | File cacheFile = fileManager.accept(file, name);
49 | journal.delete(key);
50 | journal.put(record, cacheSize);
51 | journal.writeJournal();
52 | return cacheFile;
53 | }
54 | }
55 |
56 | public File get(String key) {
57 | synchronized (journal) {
58 | assertKeyValid(key);
59 | Record record = journal.get(key);
60 | if (record != null) {
61 | File file = fileManager.get(record.getName());
62 | if (!file.exists()) {
63 | journal.delete(key);
64 | file = null;
65 | }
66 | journal.writeJournal();
67 | return file;
68 | } else {
69 | logger.log("[-] No requested file with key %s in cache", key);
70 | return null;
71 | }
72 | }
73 | }
74 |
75 | public void delete(String key) throws IOException, RecordNotFoundException {
76 | delete(key, true);
77 | }
78 |
79 | private void delete(String key, boolean writeJournal)
80 | throws IOException, RecordNotFoundException {
81 | synchronized (journal) {
82 | assertKeyValid(key);
83 | Record record = journal.delete(key);
84 | if (record != null) {
85 | if (writeJournal) {
86 | journal.writeJournal();
87 | }
88 | fileManager.delete(record.getName());
89 | } else {
90 | throw new RecordNotFoundException();
91 | }
92 | }
93 | }
94 |
95 | public void clearCache() throws IOException {
96 | synchronized (journal) {
97 | Set keys = new HashSet<>(journal.keySet());
98 | for (String key : keys) {
99 | try {
100 | delete(key, false);
101 | } catch (RecordNotFoundException ignored) {
102 | }
103 | }
104 | journal.writeJournal();
105 | }
106 | }
107 |
108 | public Set keySet() {
109 | synchronized (journal) {
110 | return journal.keySet();
111 | }
112 | }
113 |
114 | public long getCacheSize() {
115 | return cacheSize;
116 | }
117 |
118 | public long getUsedSpace() {
119 | synchronized (journal) {
120 | return journal.getTotalSize();
121 | }
122 | }
123 |
124 | public long getFreeSpace() {
125 | synchronized (journal) {
126 | return cacheSize - journal.getTotalSize();
127 | }
128 | }
129 |
130 | public long getJournalSize() {
131 | synchronized (journal) {
132 | return journal.getJournalSize();
133 | }
134 | }
135 |
136 | private static void assertKeyValid(String key) {
137 | if (key == null || key.isEmpty()) {
138 | throw new IllegalArgumentException(String.format("Invalid key value: '%s'", key));
139 | }
140 | }
141 |
142 | private static String keyHash(String base) {
143 | try {
144 | MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
145 | byte[] bytes = digest.digest(base.getBytes(UTF_8));
146 | StringBuilder hexString = new StringBuilder();
147 | for (byte b : bytes) {
148 | String hex = Integer.toHexString(0xff & b);
149 | if (hex.length() == 1) {
150 | hexString.append('0');
151 | }
152 | hexString.append(hex);
153 | }
154 | return hexString.toString();
155 | } catch (NoSuchAlgorithmException ignored) {
156 | }
157 | throw new IllegalArgumentException("Unable to hash key");
158 | }
159 |
160 | private static String generateName(String key, File file) {
161 | return keyHash(key) + fileExtension(file.getName());
162 | }
163 |
164 | private static String fileExtension(String path) {
165 | String suffix = "";
166 | if (path != null && !path.isEmpty()) {
167 | int index = path.lastIndexOf(".");
168 | if (index != -1) {
169 | suffix = path.substring(index);
170 | }
171 | }
172 | return suffix;
173 | }
174 |
175 | }
176 |
--------------------------------------------------------------------------------
/cache/src/main/java/com/tomclaw/cache/FileManager.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 |
6 | public interface FileManager {
7 |
8 | File journal();
9 |
10 | void prepare() throws IOException;
11 |
12 | File get(String name);
13 |
14 | File accept(File extFile, String name) throws IOException;
15 |
16 | boolean exists(String name);
17 |
18 | void delete(String name) throws IOException;
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/cache/src/main/java/com/tomclaw/cache/Journal.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | import java.io.BufferedInputStream;
4 | import java.io.BufferedOutputStream;
5 | import java.io.DataInputStream;
6 | import java.io.DataOutputStream;
7 | import java.io.File;
8 | import java.io.FileInputStream;
9 | import java.io.FileNotFoundException;
10 | import java.io.FileOutputStream;
11 | import java.io.IOException;
12 | import java.util.ArrayList;
13 | import java.util.Collections;
14 | import java.util.HashMap;
15 | import java.util.List;
16 | import java.util.Map;
17 | import java.util.Set;
18 |
19 | @SuppressWarnings({"unused", "WeakerAccess"})
20 | class Journal {
21 |
22 | public static final int JOURNAL_FORMAT_VERSION = 1;
23 |
24 | private final File file;
25 | private final FileManager fileManager;
26 | private final Logger logger;
27 | private final Map map = new HashMap<>();
28 | private long totalSize = 0;
29 |
30 | private Journal(File file, FileManager fileManager, Logger logger) {
31 | this.file = file;
32 | this.fileManager = fileManager;
33 | this.logger = logger;
34 | }
35 |
36 | public void put(Record record, long cacheSize) throws IOException {
37 | long fileSize = record.getSize();
38 | prepare(fileSize, cacheSize);
39 | put(record);
40 | }
41 |
42 | private void put(Record record) {
43 | map.put(record.getKey(), record);
44 | totalSize += record.getSize();
45 | logger.log("[+] Put %s (%d bytes) and cache size became %d bytes",
46 | record.getKey(), record.getSize(), totalSize);
47 | }
48 |
49 | public Record get(String key) {
50 | Record record = map.get(key);
51 | if (record != null) {
52 | updateTime(record);
53 | logger.log("[^] Update time of %s (%d bytes)", record.getKey(), record.getSize());
54 | }
55 | return record;
56 | }
57 |
58 | public Record delete(String key) {
59 | Record record = map.remove(key);
60 | if (record != null) {
61 | totalSize -= record.getSize();
62 | }
63 | return record;
64 | }
65 |
66 | public Set keySet() {
67 | return Collections.unmodifiableSet(map.keySet());
68 | }
69 |
70 | private void updateTime(Record record) {
71 | long time = System.currentTimeMillis();
72 | map.put(record.getKey(), new Record(record, time));
73 | }
74 |
75 | private void prepare(long fileSize, long cacheSize) throws IOException {
76 | if (totalSize + fileSize > cacheSize) {
77 | logger.log("[!] File %d bytes is not fit in cache %d bytes", fileSize, totalSize);
78 | List records = new ArrayList<>(map.values());
79 | Collections.sort(records, new RecordComparator());
80 | for (int c = records.size() - 1; c > 0; c--) {
81 | Record record = records.remove(c);
82 | long nextTotalSize = totalSize - record.getSize();
83 | logger.log("[x] Delete %s [%d ms] %d bytes and free cache to %d bytes",
84 | record.getKey(), record.getTime(), record.getSize(), nextTotalSize);
85 | fileManager.delete(record.getName());
86 | map.remove(record.getKey());
87 | totalSize = nextTotalSize;
88 |
89 | if (totalSize + fileSize <= cacheSize) {
90 | break;
91 | }
92 | }
93 | }
94 | }
95 |
96 | public long getTotalSize() {
97 | return totalSize;
98 | }
99 |
100 | public long getJournalSize() {
101 | return file.length();
102 | }
103 |
104 | private void setTotalSize(long totalSize) {
105 | this.totalSize = totalSize;
106 | }
107 |
108 | public void writeJournal() {
109 | try (FileOutputStream fileStream = new FileOutputStream(file)) {
110 | try (DataOutputStream stream = new DataOutputStream(new BufferedOutputStream(fileStream))) {
111 | stream.writeShort(JOURNAL_FORMAT_VERSION);
112 | stream.writeInt(map.size());
113 | for (Record record : map.values()) {
114 | stream.writeUTF(record.getKey());
115 | stream.writeUTF(record.getName());
116 | stream.writeLong(record.getTime());
117 | stream.writeLong(record.getSize());
118 | }
119 | }
120 | } catch (IOException ex) {
121 | logger.log("[.] Failed to write journal %s", ex.getMessage());
122 | ex.printStackTrace();
123 | }
124 | }
125 |
126 | public static Journal readJournal(FileManager fileManager, Logger logger) {
127 | File file = fileManager.journal();
128 | logger.log("[.] Start journal reading", file.getName());
129 | Journal journal = new Journal(file, fileManager, logger);
130 | try (FileInputStream fileStream = new FileInputStream(file)) {
131 | try (DataInputStream stream = new DataInputStream(new BufferedInputStream(fileStream))) {
132 | int version = stream.readShort();
133 | if (version != JOURNAL_FORMAT_VERSION) {
134 | throw new IllegalArgumentException("Invalid journal format version");
135 | }
136 | int count = stream.readInt();
137 | long totalSize = 0;
138 | for (int c = 0; c < count; c++) {
139 | String key = stream.readUTF();
140 | String name = stream.readUTF();
141 | long time = stream.readLong();
142 | long size = stream.readLong();
143 | totalSize += size;
144 | Record record = new Record(key, name, time, size);
145 | journal.put(record);
146 | }
147 | journal.setTotalSize(totalSize);
148 | logger.log("[.] Journal read. Files count is %d and total size is %d", count, totalSize);
149 | }
150 | } catch (FileNotFoundException ignored) {
151 | logger.log("[.] Journal not found and will be created");
152 | } catch (IOException ex) {
153 | logger.log("[.] Failed to read journal %s", ex.getMessage());
154 | ex.printStackTrace();
155 | }
156 | return journal;
157 | }
158 |
159 | }
160 |
--------------------------------------------------------------------------------
/cache/src/main/java/com/tomclaw/cache/Logger.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | public interface Logger {
4 |
5 | void log(String format, Object... args);
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/cache/src/main/java/com/tomclaw/cache/Record.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | @SuppressWarnings("WeakerAccess")
4 | class Record {
5 |
6 | private final String key;
7 | private final String name;
8 | private final long time;
9 | private final long size;
10 |
11 | Record(Record record, long time) {
12 | this(record.key, record.name, time, record.size);
13 | }
14 |
15 | Record(String key, String name, long time, long size) {
16 | this.key = key;
17 | this.name = name;
18 | this.time = time;
19 | this.size = size;
20 | }
21 |
22 | public String getKey() {
23 | return key;
24 | }
25 |
26 | public String getName() {
27 | return name;
28 | }
29 |
30 | public long getTime() {
31 | return time;
32 | }
33 |
34 | public long getSize() {
35 | return size;
36 | }
37 |
38 | @Override
39 | public boolean equals(Object o) {
40 | if (this == o) return true;
41 | if (o == null || getClass() != o.getClass()) return false;
42 |
43 | Record record = (Record) o;
44 |
45 | if (time != record.time) return false;
46 | if (size != record.size) return false;
47 | if (!key.equals(record.key)) return false;
48 | return name.equals(record.name);
49 | }
50 |
51 | @Override
52 | public int hashCode() {
53 | int result = key.hashCode();
54 | result = 31 * result + name.hashCode();
55 | result = 31 * result + (int) (time ^ (time >>> 32));
56 | result = 31 * result + (int) (size ^ (size >>> 32));
57 | return result;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/cache/src/main/java/com/tomclaw/cache/RecordComparator.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | import java.util.Comparator;
4 |
5 | class RecordComparator implements Comparator {
6 |
7 | @Override
8 | public int compare(Record record1, Record record2) {
9 | return compare(record2.getTime(), record1.getTime());
10 | }
11 |
12 | @SuppressWarnings("UseCompareMethod")
13 | private static int compare(long x, long y) {
14 | return (x < y) ? -1 : ((x == y) ? 0 : 1);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/cache/src/main/java/com/tomclaw/cache/RecordNotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | @SuppressWarnings("WeakerAccess")
4 | public class RecordNotFoundException extends Throwable {
5 | }
6 |
--------------------------------------------------------------------------------
/cache/src/main/java/com/tomclaw/cache/SimpleFileManager.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 |
6 | public class SimpleFileManager implements FileManager {
7 |
8 | private final File dir;
9 |
10 | @SuppressWarnings("WeakerAccess")
11 | public SimpleFileManager(File dir) {
12 | this.dir = dir;
13 | }
14 |
15 | @Override
16 | public File journal() {
17 | return new File(dir, "journal.bin");
18 | }
19 |
20 | @Override
21 | public void prepare() throws IOException {
22 | if (!dir.exists()) {
23 | if (!dir.mkdirs()) {
24 | throw new IOException("Unable to create specified cache directory");
25 | }
26 | }
27 | }
28 |
29 | @Override
30 | public File get(String name) {
31 | return new File(dir, name);
32 | }
33 |
34 | @Override
35 | public File accept(File extFile, String name) throws IOException {
36 | File newFile = get(name);
37 | if ((dir.exists() || dir.mkdirs())
38 | | (newFile.exists() && newFile.delete())
39 | | extFile.renameTo(newFile)) {
40 | return newFile;
41 | } else {
42 | throw formatException("Unable to accept file %s", extFile);
43 | }
44 | }
45 |
46 | @Override
47 | public boolean exists(String name) {
48 | return new File(dir, name).exists();
49 | }
50 |
51 | @Override
52 | public void delete(String name) throws IOException {
53 | File file = new File(dir, name);
54 | if (file.exists() && !file.delete()) {
55 | throw formatException("Unable to delete file %s", file);
56 | }
57 | }
58 |
59 | private IOException formatException(String format, File file) {
60 | String message = String.format(format, file.getName());
61 | return new IOException(message);
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/cache/src/main/java/com/tomclaw/cache/SimpleLogger.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | public class SimpleLogger implements Logger {
4 |
5 | private final boolean isLoggingEnabled;
6 |
7 | public SimpleLogger(Boolean isLoggingEnabled) {
8 | this.isLoggingEnabled = isLoggingEnabled;
9 | }
10 |
11 | public void log(String format, Object... args) {
12 | if (isLoggingEnabled) {
13 | System.out.printf((format) + "%n", args);
14 | }
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/cache/src/test/java/com/tomclaw/cache/Helpers.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | import java.util.Random;
4 |
5 | class Helpers {
6 |
7 | private static final Random random = new Random(System.currentTimeMillis());
8 |
9 | static String randomString() {
10 | return randomString(16);
11 | }
12 |
13 | static String randomString(int length) {
14 | return randomString(random, length, length);
15 | }
16 |
17 | static String randomString(Random r, int minChars, int maxChars) {
18 | int wordLength = minChars;
19 | int delta = maxChars - minChars;
20 | if (delta > 0) {
21 | wordLength += r.nextInt(delta);
22 | }
23 | StringBuilder sb = new StringBuilder(wordLength);
24 | for (int i = 0; i < wordLength; i++) {
25 | char tmp = (char) ('a' + r.nextInt('z' - 'a'));
26 | sb.append(tmp);
27 | }
28 | return sb.toString();
29 | }
30 |
31 | static long randomLong() {
32 | return random.nextLong();
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/cache/src/test/java/com/tomclaw/cache/JournalUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | import org.junit.Before;
4 | import org.junit.Rule;
5 | import org.junit.Test;
6 | import org.junit.rules.TemporaryFolder;
7 |
8 | import java.io.DataOutputStream;
9 | import java.io.File;
10 | import java.io.FileOutputStream;
11 | import java.io.IOException;
12 | import java.util.Random;
13 | import java.util.Set;
14 |
15 | import static com.tomclaw.cache.Helpers.randomString;
16 | import static org.junit.Assert.assertEquals;
17 | import static org.junit.Assert.assertFalse;
18 | import static org.junit.Assert.assertNotEquals;
19 | import static org.junit.Assert.assertNull;
20 | import static org.junit.Assert.assertTrue;
21 |
22 | public class JournalUnitTest {
23 |
24 | @Rule
25 | public TemporaryFolder folder = new TemporaryFolder();
26 |
27 | private final Random random = new Random(System.currentTimeMillis());
28 |
29 | private Journal journal;
30 |
31 | private FileManager fileManager;
32 | private Logger logger;
33 |
34 | @Before
35 | public void setUp() {
36 | fileManager = new SimpleFileManager(folder.getRoot());
37 | logger = new SimpleLogger(false);
38 | }
39 |
40 | @Test
41 | public void putRecords_totalSizeIncreasedCorrectly() throws Exception {
42 | long cacheSize = 1024;
43 | journal = createJournal();
44 | File file1 = createRandomFile(100);
45 | File file2 = createRandomFile(200);
46 | File file3 = createRandomFile(150);
47 | Record record1 = randomRecord(file1, 1001);
48 | Record record2 = randomRecord(file2, 1002);
49 | Record record3 = randomRecord(file3, 1003);
50 |
51 | journal.put(record1, cacheSize);
52 | journal.put(record2, cacheSize);
53 | journal.put(record3, cacheSize);
54 |
55 | assertEquals(450, journal.getTotalSize());
56 | }
57 |
58 | @Test
59 | public void putRecords_recordsAccessible() throws Exception {
60 | long cacheSize = 300;
61 | journal = createJournal();
62 | File file1 = createRandomFile(100);
63 | File file2 = createRandomFile(200);
64 | Record record1 = randomRecord(file1, 1001);
65 | Record record2 = randomRecord(file2, 1002);
66 |
67 | journal.put(record1, cacheSize);
68 | journal.put(record2, cacheSize);
69 |
70 | assertEquals(record1, journal.get(record1.getKey()));
71 | assertTrue(file1.exists());
72 | assertEquals(record2, journal.get(record2.getKey()));
73 | assertTrue(file2.exists());
74 | }
75 |
76 | @Test
77 | public void putRecords_keySetIsCorrect() throws Exception {
78 | long cacheSize = 300;
79 | journal = createJournal();
80 | File file1 = createRandomFile(100);
81 | File file2 = createRandomFile(200);
82 | Record record1 = randomRecord(file1, 1001);
83 | Record record2 = randomRecord(file2, 1002);
84 | journal.put(record1, cacheSize);
85 | journal.put(record2, cacheSize);
86 |
87 | Set keySet = journal.keySet();
88 |
89 | assertEquals(2, keySet.size());
90 | assertTrue(keySet.contains(record1.getKey()));
91 | assertTrue(keySet.contains(record2.getKey()));
92 | }
93 |
94 | @Test
95 | public void putRecords_firstInsertedRecordPurged_recordsSizeMoreThanCacheSize() throws Exception {
96 | long cacheSize = 300;
97 | journal = createJournal();
98 | File file1 = createRandomFile(100);
99 | File file2 = createRandomFile(200);
100 | File file3 = createRandomFile(150);
101 | Record record1 = randomRecord(file1, 1001);
102 | Record record2 = randomRecord(file2, 1002);
103 | Record record3 = randomRecord(file3, 1003);
104 |
105 | journal.put(record1, cacheSize);
106 | journal.put(record2, cacheSize);
107 | journal.put(record3, cacheSize);
108 |
109 | assertNull(journal.get(record1.getKey()));
110 | assertFalse(file1.exists());
111 | }
112 |
113 | @Test
114 | public void getRecords_recordTimeUpdates() throws Exception {
115 | long cacheSize = 300;
116 | journal = createJournal();
117 | File file = createRandomFile(100);
118 | Record original = randomRecord(file, 1001);
119 | String key = original.getKey();
120 |
121 | journal.put(original, cacheSize);
122 | journal.get(key);
123 |
124 | Record updated = journal.get(key);
125 | assertNotEquals(original.getTime(), updated.getTime());
126 | assertEquals(original.getName(), updated.getName());
127 | }
128 |
129 | @Test
130 | public void putRecords_leastUsedRecordIsPurged() throws Exception {
131 | long cacheSize = 300;
132 | journal = createJournal();
133 | File file1 = createRandomFile(100);
134 | File file2 = createRandomFile(200);
135 | File file3 = createRandomFile(150);
136 | Record record1 = randomRecord(file1, 1001);
137 | Record record2 = randomRecord(file2, 1002);
138 | Record record3 = randomRecord(file3, 1003);
139 |
140 | journal.put(record1, cacheSize);
141 | journal.put(record2, cacheSize);
142 | journal.get(record1.getKey());
143 | journal.put(record3, cacheSize);
144 |
145 | assertNull(journal.get(record2.getKey()));
146 | assertFalse(file2.exists());
147 | assertEquals(record1.getName(), journal.get(record1.getKey()).getName());
148 | assertTrue(file1.exists());
149 | }
150 |
151 | @Test
152 | public void deleteRecords_recordIsNotAccessible() throws Exception {
153 | long cacheSize = 300;
154 | journal = createJournal();
155 | File file = createRandomFile(100);
156 | Record record = randomRecord(file, 1001);
157 | journal.put(record, cacheSize);
158 |
159 | journal.delete(record.getKey());
160 |
161 | assertNull(journal.get(record.getKey()));
162 | }
163 |
164 | @Test
165 | public void writeJournal_journalSizeIsCorrect() throws Exception {
166 | long cacheSize = 1000;
167 | Journal journal = Journal.readJournal(fileManager, logger);
168 | File file = createRandomFile(100);
169 | Record record = randomRecord(file, 1001);
170 | journal.put(record, cacheSize);
171 | journal.writeJournal();
172 |
173 | long journalSize = journal.getJournalSize();
174 |
175 | File journalFile = fileManager.journal();
176 | assertEquals(journalFile.length(), journalSize);
177 | }
178 |
179 | @Test
180 | public void writeAndParseJournal_journalRestoresCorrectly() throws Exception {
181 | long cacheSize = 1000;
182 | Journal original = Journal.readJournal(fileManager, logger);
183 | File file1 = createRandomFile(100);
184 | File file2 = createRandomFile(200);
185 | File file3 = createRandomFile(150);
186 | Record record1 = randomRecord(file1, 1001);
187 | Record record2 = randomRecord(file2, 1002);
188 | Record record3 = randomRecord(file3, 1003);
189 | original.put(record1, cacheSize);
190 | original.put(record2, cacheSize);
191 | original.put(record3, cacheSize);
192 |
193 | original.writeJournal();
194 | Journal restored = Journal.readJournal(fileManager, logger);
195 |
196 | assertEquals(record1, restored.get(record1.getKey()));
197 | assertEquals(record2, restored.get(record2.getKey()));
198 | assertEquals(record3, restored.get(record3.getKey()));
199 | }
200 |
201 | private Record randomRecord(File file, long time) {
202 | String key = randomString();
203 | String name = file.getName();
204 | long size = file.length();
205 | return new Record(key, name, time, size);
206 | }
207 |
208 | private File createRandomFile(int size) throws IOException {
209 | String name = randomString(8);
210 | String extension = randomString(3);
211 | File file = folder.newFile(name + "." + extension);
212 | try (DataOutputStream stream = new DataOutputStream(new FileOutputStream(file))) {
213 | for (int c = 0; c < size; c++) {
214 | stream.writeByte(random.nextInt(255));
215 | }
216 | stream.flush();
217 | }
218 | return file;
219 | }
220 |
221 | private Journal createJournal() {
222 | return Journal.readJournal(fileManager, logger);
223 | }
224 |
225 | }
--------------------------------------------------------------------------------
/cache/src/test/java/com/tomclaw/cache/RecordComparatorUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.tomclaw.cache;
2 |
3 | import org.junit.Before;
4 | import org.junit.Test;
5 |
6 | import static com.tomclaw.cache.Helpers.randomLong;
7 | import static com.tomclaw.cache.Helpers.randomString;
8 | import static org.junit.Assert.assertEquals;
9 |
10 | public class RecordComparatorUnitTest {
11 |
12 | private RecordComparator comparator;
13 |
14 | @Before
15 | public void setUp() {
16 | comparator = createComparator();
17 | }
18 |
19 | @Test
20 | public void compare_leftRecordTimeIsLessThanRight() {
21 | Record record1 = randomRecord(1000);
22 | Record record2 = randomRecord(1001);
23 |
24 | int result = comparator.compare(record1, record2);
25 |
26 | assertEquals(1, result);
27 | }
28 |
29 | @Test
30 | public void compare_recordsTimesAreEquals() {
31 | Record record1 = randomRecord(1000);
32 | Record record2 = randomRecord(1000);
33 |
34 | int result = comparator.compare(record1, record2);
35 |
36 | assertEquals(0, result);
37 | }
38 |
39 | @Test
40 | public void compare_leftRecordTimeIsMoreThanRight() {
41 | Record record1 = randomRecord(1001);
42 | Record record2 = randomRecord(1000);
43 |
44 | int result = comparator.compare(record1, record2);
45 |
46 | assertEquals(-1, result);
47 | }
48 |
49 | private Record randomRecord(long time) {
50 | String key = randomString();
51 | String name = randomString();
52 | long size = randomLong();
53 | return new Record(key, name, time, size);
54 | }
55 |
56 | private RecordComparator createComparator() {
57 | return new RecordComparator();
58 | }
59 |
60 | }
--------------------------------------------------------------------------------
/cache_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/cache_icon.png
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | android.enableJetifier=true
10 | android.useAndroidX=true
11 | org.gradle.jvmargs=-Xmx1536m
12 | # When configured, Gradle will run in incubating parallel mode.
13 | # This option should only be used with decoupled projects. More details, visit
14 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
15 | # org.gradle.parallel=true
16 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/solkin/disk-lru-cache/196e53df0586aa0605da75e35360cb86f9aa5c79/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat Dec 30 03:57:01 MSK 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/jitpack.yml:
--------------------------------------------------------------------------------
1 | jdk:
2 | - openjdk17
3 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':cache'
2 |
--------------------------------------------------------------------------------