use workmanager

This commit is contained in:
Morten Delenk 2022-08-22 16:41:31 +01:00
parent 503824167e
commit 941cf5b0cb
No known key found for this signature in database
GPG key ID: 5130416C797067B6
37 changed files with 116 additions and 1269 deletions

View file

@ -34,6 +34,7 @@ android {
} }
} }
compileOptions { compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_15 sourceCompatibility JavaVersion.VERSION_15
targetCompatibility JavaVersion.VERSION_15 targetCompatibility JavaVersion.VERSION_15
} }
@ -48,8 +49,8 @@ android {
} }
dependencies { dependencies {
implementation 'androidx.appcompat:appcompat:1.4.2' implementation 'androidx.appcompat:appcompat:1.5.0'
implementation 'com.google.android.material:material:1.7.0-alpha03' implementation 'com.google.android.material:material:1.7.0-beta01'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation "androidx.navigation:navigation-fragment:2.5.1" implementation "androidx.navigation:navigation-fragment:2.5.1"
implementation "androidx.navigation:navigation-ui:2.5.1" implementation "androidx.navigation:navigation-ui:2.5.1"
@ -62,7 +63,7 @@ dependencies {
implementation 'com.google.android.gms:play-services-cronet:18.0.1' implementation 'com.google.android.gms:play-services-cronet:18.0.1'
implementation 'org.chromium.net:cronet-fallback:102.5005.125' implementation 'org.chromium.net:cronet-fallback:102.5005.125'
implementation 'com.google.net.cronet:cronet-okhttp:0.1.0' implementation 'com.google.net.cronet:cronet-okhttp:0.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.10'
implementation project(path: ':invtracker') implementation project(path: ':invtracker')
implementation 'androidx.annotation:annotation:1.4.0' implementation 'androidx.annotation:annotation:1.4.0'
@ -83,6 +84,12 @@ dependencies {
implementation 'org.osmdroid:osmdroid-android:6.1.13' implementation 'org.osmdroid:osmdroid-android:6.1.13'
def work_version = "2.7.1"
implementation "androidx.work:work-runtime:$work_version"
implementation "androidx.work:work-rxjava3:$work_version"
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
// workaround for gradle being terrible // workaround for gradle being terrible
compileOnly "com.android.tools.build:aapt2:7.2.2-7984345" compileOnly "com.android.tools.build:aapt2:7.2.2-7984345"
} }

View file

@ -8,8 +8,9 @@ import com.google.zxing.BinaryBitmap;
import com.google.zxing.common.HybridBinarizer; import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader; import com.google.zxing.qrcode.QRCodeReader;
import rs.chir.compat.java.util.Optional; import java.util.Optional;
import rs.chir.compat.java.util.function.Function; import java.util.function.Function;
/** /**
* {@link ImageAnalysis.Analyzer} for QR codes. * {@link ImageAnalysis.Analyzer} for QR codes.

View file

@ -9,10 +9,10 @@ import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.core.Single;
import rs.chir.compat.java.util.Optional;
import rs.chir.invtracker.model.Cursor; import rs.chir.invtracker.model.Cursor;
import rs.chir.invtracker.model.GeoLocation; import rs.chir.invtracker.model.GeoLocation;
import rs.chir.invtracker.model.GeoRect; import rs.chir.invtracker.model.GeoRect;
@ -95,7 +95,13 @@ public class CachedClientImpl extends Client {
@NonNull @NonNull
@Override @Override
public Single<TrackedItem> getObject(long id) { public Single<TrackedItem> getObject(long id) {
return Optional.tryIndex(this.objects, id).map(Single::just).orElseGet(() -> this.client.getObject(id).doOnSuccess(this::cacheObject)); synchronized(this.objects) {
if (this.objects.containsKey(id)) {
return Single.just(this.objects.get(id));
} else {
return this.client.getObject(id).doOnSuccess(this::cacheObject);
}
}
} }
/** /**

View file

@ -8,7 +8,7 @@ import java.io.InputStream;
import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.core.Single;
import rs.chir.compat.java.util.Optional; import java.util.Optional;
import rs.chir.invtracker.model.Cursor; import rs.chir.invtracker.model.Cursor;
import rs.chir.invtracker.model.GeoLocation; import rs.chir.invtracker.model.GeoLocation;
import rs.chir.invtracker.model.GeoRect; import rs.chir.invtracker.model.GeoRect;

View file

@ -2,8 +2,9 @@ package rs.chir.invtracker.api;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import java.util.function.Supplier;
import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.core.Single;
import rs.chir.compat.java.util.function.Supplier;
import rs.chir.invtracker.utils.SingleBackoff; import rs.chir.invtracker.utils.SingleBackoff;
/** /**

View file

@ -16,6 +16,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.Optional;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
@ -29,7 +30,6 @@ import okhttp3.ResponseBody;
import okio.BufferedSink; import okio.BufferedSink;
import okio.Okio; import okio.Okio;
import rs.chir.compat.java.util.Base64; import rs.chir.compat.java.util.Base64;
import rs.chir.compat.java.util.Optional;
import rs.chir.invtracker.client.model.APIKey; import rs.chir.invtracker.client.model.APIKey;
import rs.chir.invtracker.model.Cursor; import rs.chir.invtracker.model.Cursor;
import rs.chir.invtracker.model.GeoLocation; import rs.chir.invtracker.model.GeoLocation;

View file

@ -11,9 +11,9 @@ import org.chromium.net.CronetEngine;
import org.chromium.net.impl.JavaCronetProvider; import org.chromium.net.impl.JavaCronetProvider;
import java.io.File; import java.io.File;
import java.util.Optional;
import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.core.Single;
import rs.chir.compat.java.util.Optional;
import rs.chir.invtracker.utils.RXJavaAdapters; import rs.chir.invtracker.utils.RXJavaAdapters;
/** /**

View file

@ -12,9 +12,9 @@ import com.google.android.material.color.DynamicColors;
import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security; import java.security.Security;
import java.util.Optional;
import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.core.Single;
import rs.chir.compat.java.util.Optional;
import rs.chir.invtracker.api.CachedClientImpl; import rs.chir.invtracker.api.CachedClientImpl;
import rs.chir.invtracker.api.Client; import rs.chir.invtracker.api.Client;
import rs.chir.invtracker.api.ClientImpl; import rs.chir.invtracker.api.ClientImpl;

View file

@ -22,8 +22,8 @@ import androidx.core.content.FileProvider;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.util.Optional;
import rs.chir.compat.java.util.Optional;
import rs.chir.invtracker.client.databinding.FragmentEditItemBinding; import rs.chir.invtracker.client.databinding.FragmentEditItemBinding;
import rs.chir.invtracker.model.TrackedItem; import rs.chir.invtracker.model.TrackedItem;

View file

@ -20,8 +20,8 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URI; import java.net.URI;
import java.util.Optional;
import rs.chir.compat.java.util.Optional;
import rs.chir.invtracker.client.databinding.FragmentItemDetailBinding; import rs.chir.invtracker.client.databinding.FragmentItemDetailBinding;
import rs.chir.invtracker.client.model.LocationListAdapter; import rs.chir.invtracker.client.model.LocationListAdapter;
import rs.chir.invtracker.model.TrackedItem; import rs.chir.invtracker.model.TrackedItem;

View file

@ -6,7 +6,8 @@ import android.view.View;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import rs.chir.compat.java.util.Optional; import java.util.Optional;
import rs.chir.invtracker.client.databinding.FragmentLoginBinding; import rs.chir.invtracker.client.databinding.FragmentLoginBinding;
import rs.chir.invtracker.client.model.APIKey; import rs.chir.invtracker.client.model.APIKey;
import rs.chir.invtracker.model.PasetoToken; import rs.chir.invtracker.model.PasetoToken;

View file

@ -12,7 +12,8 @@ import androidx.recyclerview.widget.LinearLayoutManager;
import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationServices;
import rs.chir.compat.java.util.Optional; import java.util.Optional;
import rs.chir.invtracker.client.databinding.FragmentNearbyBinding; import rs.chir.invtracker.client.databinding.FragmentNearbyBinding;
import rs.chir.invtracker.client.model.ItemListAdapter; import rs.chir.invtracker.client.model.ItemListAdapter;
import rs.chir.invtracker.model.GeoLocation; import rs.chir.invtracker.model.GeoLocation;

View file

@ -1,6 +1,7 @@
package rs.chir.invtracker.client; package rs.chir.invtracker.client;
import android.Manifest; import android.Manifest;
import android.content.Context;
import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable;
import android.os.Bundle; import android.os.Bundle;
import android.util.DisplayMetrics; import android.util.DisplayMetrics;
@ -14,6 +15,15 @@ import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.Preview; import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.ListenableWorker;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import androidx.work.rxjava3.RxWorker;
import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationServices;
import com.google.android.material.color.MaterialColors; import com.google.android.material.color.MaterialColors;
@ -22,10 +32,13 @@ import com.google.android.material.snackbar.Snackbar;
import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Contract;
import java.sql.Timestamp;
import java.util.OptionalDouble;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import io.reactivex.rxjava3.core.Single;
import rs.chir.cv.QRAnalyzer; import rs.chir.cv.QRAnalyzer;
import rs.chir.invtracker.client.databinding.FragmentQrScanBinding; import rs.chir.invtracker.client.databinding.FragmentQrScanBinding;
import rs.chir.invtracker.model.GeoLocation; import rs.chir.invtracker.model.GeoLocation;
@ -175,6 +188,35 @@ public class QRScanFragment extends FragmentBase<FragmentQrScanBinding> implemen
this.getBinding().viewFinder.setVisibility(visibility); this.getBinding().viewFinder.setVisibility(visibility);
} }
public static class LocationUpdateWorker extends RxWorker {
public LocationUpdateWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Single<Result> createWork() {
var data = this.getInputData();
var id = data.getLong("id", -1);
var lat = data.getDouble("lat", -1);
var lon = data.getDouble("lon", -1);
var alt = OptionalDouble.empty();
if (data.hasKeyWithValueOfType("alt", Double.class)) {
alt = OptionalDouble.of(data.getDouble("alt", -1));
}
var time = new Timestamp(data.getLong("time", -1));
var location = new GeoLocation(lat, lon, alt, time);
return Application.getInstance(this.getApplicationContext())
.getClient()
.flatMap(client -> client.updateLocation(id, location))
.map(__ -> Result.success())
.onErrorResumeWith(__ -> Result.retry());
}
}
/** /**
* Update the location of the object * Update the location of the object
* *
@ -182,16 +224,22 @@ public class QRScanFragment extends FragmentBase<FragmentQrScanBinding> implemen
* @param location the location of the object * @param location the location of the object
*/ */
private void updateLocation(long id, GeoLocation location) { private void updateLocation(long id, GeoLocation location) {
this.subscribe( // We run this in the background
this.getClient() var constraints = new Constraints.Builder()
.flatMap(client -> client.updateLocation(id, location)), .setRequiredNetworkType(NetworkType.CONNECTED)
__ -> this.showDetailView(id), err -> { .build();
err.printStackTrace(); var data = new Data.Builder();
Snackbar.make(this.getBinding().getRoot(), "Error: " + err.getMessage(), BaseTransientBottomBar.LENGTH_LONG).show(); data.putLong("id", id);
this.hasScanned.set(false); data.putDouble("lat", location.latitude());
this.hideUI(false); data.putDouble("lon", location.longitude());
} location.altitude().ifPresent(alt -> data.putDouble("alt", alt));
); data.putLong("time", location.locationTime().getTime());
var workRequest = new OneTimeWorkRequest.Builder(LocationUpdateWorker.class)
.setInputData(data.build())
.setConstraints(constraints)
.build();
WorkManager.getInstance(this.requireContext()).enqueue(workRequest);
this.showDetailView(id);
} }
/** /**

View file

@ -6,7 +6,7 @@ import androidx.preference.ListPreference;
import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SeekBarPreference; import androidx.preference.SeekBarPreference;
import rs.chir.compat.java.util.function.Consumer; import java.util.function.Consumer;
/** /**
* The fragment that shows the settings screen. * The fragment that shows the settings screen.

View file

@ -6,8 +6,9 @@ import androidx.annotation.NonNull;
import androidx.datastore.preferences.core.Preferences; import androidx.datastore.preferences.core.Preferences;
import androidx.datastore.preferences.core.PreferencesKeys; import androidx.datastore.preferences.core.PreferencesKeys;
import java.util.Optional;
import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.core.Single;
import rs.chir.compat.java.util.Optional;
import rs.chir.invtracker.client.Application; import rs.chir.invtracker.client.Application;
/** /**

View file

@ -14,10 +14,10 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers; import io.reactivex.rxjava3.schedulers.Schedulers;
import rs.chir.compat.java.util.Optional;
import rs.chir.invtracker.client.Application; import rs.chir.invtracker.client.Application;
import rs.chir.invtracker.client.R; import rs.chir.invtracker.client.R;
import rs.chir.invtracker.model.GeoRect; import rs.chir.invtracker.model.GeoRect;

View file

@ -6,8 +6,10 @@ import com.google.android.gms.tasks.Task;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.function.Function;
import io.reactivex.rxjava3.core.BackpressureStrategy; import io.reactivex.rxjava3.core.BackpressureStrategy;
import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Flowable;
@ -17,8 +19,6 @@ import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.Call; import okhttp3.Call;
import okhttp3.Callback; import okhttp3.Callback;
import okhttp3.Response; import okhttp3.Response;
import rs.chir.compat.java.util.Optional;
import rs.chir.compat.java.util.function.Function;
import rs.chir.invtracker.model.Cursor; import rs.chir.invtracker.model.Cursor;
import rs.chir.utils.xml.XMLSerializable; import rs.chir.utils.xml.XMLSerializable;

View file

@ -7,12 +7,12 @@ import androidx.annotation.NonNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.function.Supplier;
import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.core.SingleObserver; import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.disposables.Disposable;
import rs.chir.compat.java.util.function.Predicate;
import rs.chir.compat.java.util.function.Supplier;
/** /**
* Performs exponential backoff on a single. * Performs exponential backoff on a single.

View file

@ -17,9 +17,9 @@ import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.Priority; import com.google.android.gms.location.Priority;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.OptionalDouble;
import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.core.Single;
import rs.chir.compat.java.util.OptionalDouble;
import rs.chir.invtracker.client.model.LocationRounder; import rs.chir.invtracker.client.model.LocationRounder;
import rs.chir.invtracker.model.GeoLocation; import rs.chir.invtracker.model.GeoLocation;

View file

@ -1,4 +1,4 @@
#Mon Aug 15 10:52:08 GMT 2022 #Mon Aug 22 14:32:31 GMT 2022
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
distributionPath=wrapper/dists distributionPath=wrapper/dists

View file

@ -29,7 +29,7 @@ import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import rs.chir.compat.java.util.function.Supplier; import java.util.function.Supplier;
/** /**
* This class consists of {@code static} utility methods for operating * This class consists of {@code static} utility methods for operating

View file

@ -1,445 +0,0 @@
/*
* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package rs.chir.compat.java.util;
import androidx.annotation.NonNull;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import rs.chir.compat.java.util.function.Consumer;
import rs.chir.compat.java.util.function.Function;
import rs.chir.compat.java.util.function.Predicate;
import rs.chir.compat.java.util.function.Supplier;
/**
* A container object which may or may not contain a non-{@code null} value.
* If a value is present, {@code isPresent()} returns {@code true}. If no
* value is present, the object is considered <i>empty</i> and
* {@code isPresent()} returns {@code false}.
*
* <p>Additional methods that depend on the presence or absence of a contained
* value are provided, such as {@link #orElse(Object) orElse()}
* (returns a default value if no value is present) and
* {@link #ifPresent(Consumer) ifPresent()} (performs an
* action if a value is present).
*
* <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
* class; programmers should treat instances that are
* {@linkplain #equals(Object) equal} as interchangeable and should not
* use instances for synchronization, or unpredictable behavior may
* occur. For example, in a future release, synchronization may fail.
*
* @param <T> the type of value
* @apiNote {@code Optional} is primarily intended for use as a method return type where
* there is a clear need to represent "no result," and where using {@code null}
* is likely to cause errors. A variable whose type is {@code Optional} should
* never itself be {@code null}; it should always point to an {@code Optional}
* instance.
* @since 1.8
*/
public final class Optional<T> {
/**
* Common instance for {@code empty()}.
*/
private static final Optional<?> EMPTY = new Optional<>(null);
/**
* If non-null, the value; if null, indicates no value is present
*/
private final T value;
/**
* Constructs an instance with the described value.
*
* @param value the value to describe; it's the caller's responsibility to
* ensure the value is non-{@code null} unless creating the singleton
* instance returned by {@code empty()}.
*/
private Optional(T value) {
this.value = value;
}
/**
* Returns an empty {@code Optional} instance. No value is present for this
* {@code Optional}.
*
* @param <T> The type of the non-existent value
* @return an empty {@code Optional}
* @apiNote Though it may be tempting to do so, avoid testing if an object is empty
* by comparing with {@code ==} or {@code !=} against instances returned by
* {@code Optional.empty()}. There is no guarantee that it is a singleton.
* Instead, use {@link #isEmpty()} or {@link #isPresent()}.
*/
public static <T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
/**
* Returns an {@code Optional} describing the given non-{@code null}
* value.
*
* @param value the value to describe, which must be non-{@code null}
* @param <T> the type of the value
* @return an {@code Optional} with the value present
* @throws NullPointerException if value is {@code null}
*/
public static <T> Optional<T> of(T value) {
return new Optional<>(Objects.requireNonNull(value));
}
/**
* Returns an {@code Optional} describing the given value, if
* non-{@code null}, otherwise returns an empty {@code Optional}.
*
* @param value the possibly-{@code null} value to describe
* @param <T> the type of the value
* @return an {@code Optional} with a present value if the specified value
* is non-{@code null}, otherwise an empty {@code Optional}
*/
@SuppressWarnings("unchecked")
public static <T> Optional<T> ofNullable(T value) {
return value == null ? (Optional<T>) EMPTY
: new Optional<>(value);
}
/**
* Attempts to retrieve an item from a map.
*
* @param <T> the type of the item
* @param <U> the type of the key
* @param map the map
* @param key the key
*/
@NonNull
public static <T, U> Optional<T> tryIndex(@NonNull Map<U, ? extends T> map, U key) {
return Optional.ofNullable(map.get(key));
}
/**
* If a value is present, returns the value, otherwise throws
* {@code NoSuchElementException}.
*
* @return the non-{@code null} value described by this {@code Optional}
* @throws NoSuchElementException if no value is present
* @apiNote The preferred alternative to this method is {@link #orElseThrow()}.
*/
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
/**
* If a value is present, returns {@code true}, otherwise {@code false}.
*
* @return {@code true} if a value is present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}
/**
* If a value is not present, returns {@code true}, otherwise
* {@code false}.
*
* @return {@code true} if a value is not present, otherwise {@code false}
* @since 11
*/
public boolean isEmpty() {
return value == null;
}
/**
* If a value is present, performs the given action with the value,
* otherwise does nothing.
*
* @param action the action to be performed, if a value is present
* @throws NullPointerException if value is present and the given action is
* {@code null}
*/
public void ifPresent(Consumer<? super T> action) {
if (value != null) {
action.accept(value);
}
}
/**
* If a value is present, performs the given action with the value,
* otherwise performs the given empty-based action.
*
* @param action the action to be performed, if a value is present
* @param emptyAction the empty-based action to be performed, if no value is
* present
* @throws NullPointerException if a value is present and the given action
* is {@code null}, or no value is present and the given empty-based
* action is {@code null}.
* @since 9
*/
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
if (value != null) {
action.accept(value);
} else {
emptyAction.run();
}
}
/**
* If a value is present, and the value matches the given predicate,
* returns an {@code Optional} describing the value, otherwise returns an
* empty {@code Optional}.
*
* @param predicate the predicate to apply to a value, if present
* @return an {@code Optional} describing the value of this
* {@code Optional}, if a value is present and the value matches the
* given predicate, otherwise an empty {@code Optional}
* @throws NullPointerException if the predicate is {@code null}
*/
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!this.isPresent()) {
return this;
} else {
return predicate.test(value) ? this : Optional.empty();
}
}
/**
* If a value is present, returns an {@code Optional} describing (as if by
* {@link #ofNullable}) the result of applying the given mapping function to
* the value, otherwise returns an empty {@code Optional}.
*
* <p>If the mapping function returns a {@code null} result then this method
* returns an empty {@code Optional}.
*
* @param mapper the mapping function to apply to a value, if present
* @param <U> The type of the value returned from the mapping function
* @return an {@code Optional} describing the result of applying a mapping
* function to the value of this {@code Optional}, if a value is
* present, otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is {@code null}
* @apiNote This method supports post-processing on {@code Optional} values, without
* the need to explicitly check for a return status. For example, the
* following code traverses a stream of URIs, selects one that has not
* yet been processed, and creates a path from that URI, returning
* an {@code Optional<Path>}:
*
* <pre>{@code
* Optional<Path> p =
* uris.stream().filter(uri -> !isProcessedYet(uri))
* .findFirst()
* .map(Paths::get);
* }</pre>
* <p>
* Here, {@code findFirst} returns an {@code Optional<URI>}, and then
* {@code map} returns an {@code Optional<Path>} for the desired
* URI if one exists.
*/
public <U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!this.isPresent()) {
return Optional.empty();
} else {
return Optional.ofNullable(mapper.apply(value));
}
}
/**
* If a value is present, returns the result of applying the given
* {@code Optional}-bearing mapping function to the value, otherwise returns
* an empty {@code Optional}.
*
* <p>This method is similar to {@link #map(Function)}, but the mapping
* function is one whose result is already an {@code Optional}, and if
* invoked, {@code flatMap} does not wrap it within an additional
* {@code Optional}.
*
* @param <U> The type of value of the {@code Optional} returned by the
* mapping function
* @param mapper the mapping function to apply to a value, if present
* @return the result of applying an {@code Optional}-bearing mapping
* function to the value of this {@code Optional}, if a value is
* present, otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is {@code null} or
* returns a {@code null} result
*/
public <U> Optional<U> flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) {
Objects.requireNonNull(mapper);
if (!this.isPresent()) {
return Optional.empty();
} else {
@SuppressWarnings("unchecked")
Optional<U> r = (Optional<U>) mapper.apply(value);
return Objects.requireNonNull(r);
}
}
/**
* If a value is present, returns an {@code Optional} describing the value,
* otherwise returns an {@code Optional} produced by the supplying function.
*
* @param supplier the supplying function that produces an {@code Optional}
* to be returned
* @return returns an {@code Optional} describing the value of this
* {@code Optional}, if a value is present, otherwise an
* {@code Optional} produced by the supplying function.
* @throws NullPointerException if the supplying function is {@code null} or
* produces a {@code null} result
* @since 9
*/
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier) {
Objects.requireNonNull(supplier);
if (this.isPresent()) {
return this;
} else {
@SuppressWarnings("unchecked")
Optional<T> r = (Optional<T>) supplier.get();
return Objects.requireNonNull(r);
}
}
/**
* If a value is present, returns the value, otherwise returns
* {@code other}.
*
* @param other the value to be returned, if no value is present.
* May be {@code null}.
* @return the value, if present, otherwise {@code other}
*/
public T orElse(T other) {
return value != null ? value : other;
}
/**
* If a value is present, returns the value, otherwise returns the result
* produced by the supplying function.
*
* @param supplier the supplying function that produces a value to be returned
* @return the value, if present, otherwise the result produced by the
* supplying function
* @throws NullPointerException if no value is present and the supplying
* function is {@code null}
*/
public T orElseGet(Supplier<? extends T> supplier) {
return value != null ? value : supplier.get();
}
/**
* If a value is present, returns the value, otherwise throws
* {@code NoSuchElementException}.
*
* @return the non-{@code null} value described by this {@code Optional}
* @throws NoSuchElementException if no value is present
* @since 10
*/
public T orElseThrow() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
/**
* If a value is present, returns the value, otherwise throws an exception
* produced by the exception supplying function.
*
* @param <X> Type of the exception to be thrown
* @param exceptionSupplier the supplying function that produces an
* exception to be thrown
* @return the value, if present
* @throws X if no value is present
* @throws NullPointerException if no value is present and the exception
* supplying function is {@code null}
* @apiNote A method reference to the exception constructor with an empty argument
* list can be used as the supplier. For example,
* {@code IllegalStateException::new}
*/
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
/**
* Indicates whether some other object is "equal to" this {@code Optional}.
* The other object is considered equal if:
* <ul>
* <li>it is also an {@code Optional} and;
* <li>both instances have no value present or;
* <li>the present values are "equal to" each other via {@code equals()}.
* </ul>
*
* @param obj an object to be tested for equality
* @return {@code true} if the other object is "equal to" this object
* otherwise {@code false}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Optional)) {
return false;
}
return Objects.equals(value, ((Optional<?>) obj).value);
}
/**
* Returns the hash code of the value, if present, otherwise {@code 0}
* (zero) if no value is present.
*
* @return hash code value of the present value or {@code 0} if no value is
* present
*/
@Override
public int hashCode() {
return Objects.hashCode(value);
}
/**
* Returns a non-empty string representation of this {@code Optional}
* suitable for debugging. The exact presentation format is unspecified and
* may vary between implementations and versions.
*
* @return the string representation of this instance
* @implSpec If a value is present the result must include its string representation
* in the result. Empty and present {@code Optional}s must be unambiguously
* differentiable.
*/
@Override
public String toString() {
return value != null
? ("Optional[" + value + "]")
: "Optional.empty";
}
}

View file

@ -1,305 +0,0 @@
/*
* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package rs.chir.compat.java.util;
import java.util.NoSuchElementException;
import rs.chir.compat.java.util.function.DoubleConsumer;
import rs.chir.compat.java.util.function.DoubleSupplier;
import rs.chir.compat.java.util.function.Supplier;
/**
* A container object which may or may not contain a {@code double} value.
* If a value is present, {@code isPresent()} returns {@code true}. If no
* value is present, the object is considered <i>empty</i> and
* {@code isPresent()} returns {@code false}.
*
* <p>Additional methods that depend on the presence or absence of a contained
* value are provided, such as {@link #orElse(double) orElse()}
* (returns a default value if no value is present) and
* {@link #ifPresent(DoubleConsumer) ifPresent()} (performs
* an action if a value is present).
*
* <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
* class; programmers should treat instances that are
* {@linkplain #equals(Object) equal} as interchangeable and should not
* use instances for synchronization, or unpredictable behavior may
* occur. For example, in a future release, synchronization may fail.
*
* @apiNote {@code OptionalDouble} is primarily intended for use as a method return type where
* there is a clear need to represent "no result." A variable whose type is
* {@code OptionalDouble} should never itself be {@code null}; it should always point
* to an {@code OptionalDouble} instance.
* @since 1.8
*/
public final class OptionalDouble {
/**
* Common instance for {@code empty()}.
*/
private static final OptionalDouble EMPTY = new OptionalDouble();
/**
* If true then the value is present, otherwise indicates no value is present
*/
private final boolean isPresent;
private final double value;
/**
* Construct an empty instance.
*
* @implNote generally only one empty instance, {@link OptionalDouble#EMPTY},
* should exist per VM.
*/
private OptionalDouble() {
this.isPresent = false;
this.value = Double.NaN;
}
/**
* Construct an instance with the described value.
*
* @param value the double value to describe.
*/
private OptionalDouble(double value) {
this.isPresent = true;
this.value = value;
}
/**
* Returns an empty {@code OptionalDouble} instance. No value is present
* for this {@code OptionalDouble}.
*
* @return an empty {@code OptionalDouble}.
* @apiNote Though it may be tempting to do so, avoid testing if an object is empty
* by comparing with {@code ==} or {@code !=} against instances returned by
* {@code OptionalDouble.empty()}. There is no guarantee that it is a singleton.
* Instead, use {@link #isEmpty()} or {@link #isPresent()}.
*/
public static OptionalDouble empty() {
return EMPTY;
}
/**
* Returns an {@code OptionalDouble} describing the given value.
*
* @param value the value to describe
* @return an {@code OptionalDouble} with the value present
*/
public static OptionalDouble of(double value) {
return new OptionalDouble(value);
}
/**
* If a value is present, returns the value, otherwise throws
* {@code NoSuchElementException}.
*
* @return the value described by this {@code OptionalDouble}
* @throws NoSuchElementException if no value is present
* @apiNote The preferred alternative to this method is {@link #orElseThrow()}.
*/
public double getAsDouble() {
if (!isPresent) {
throw new NoSuchElementException("No value present");
}
return value;
}
/**
* If a value is present, returns {@code true}, otherwise {@code false}.
*
* @return {@code true} if a value is present, otherwise {@code false}
*/
public boolean isPresent() {
return isPresent;
}
/**
* If a value is not present, returns {@code true}, otherwise
* {@code false}.
*
* @return {@code true} if a value is not present, otherwise {@code false}
* @since 11
*/
public boolean isEmpty() {
return !isPresent;
}
/**
* If a value is present, performs the given action with the value,
* otherwise does nothing.
*
* @param action the action to be performed, if a value is present
* @throws NullPointerException if value is present and the given action is
* {@code null}
*/
public void ifPresent(DoubleConsumer action) {
if (isPresent) {
action.accept(value);
}
}
/**
* If a value is present, performs the given action with the value,
* otherwise performs the given empty-based action.
*
* @param action the action to be performed, if a value is present
* @param emptyAction the empty-based action to be performed, if no value is
* present
* @throws NullPointerException if a value is present and the given action
* is {@code null}, or no value is present and the given empty-based
* action is {@code null}.
* @since 9
*/
public void ifPresentOrElse(DoubleConsumer action, Runnable emptyAction) {
if (isPresent) {
action.accept(value);
} else {
emptyAction.run();
}
}
/**
* If a value is present, returns the value, otherwise returns
* {@code other}.
*
* @param other the value to be returned, if no value is present
* @return the value, if present, otherwise {@code other}
*/
public double orElse(double other) {
return isPresent ? value : other;
}
/**
* If a value is present, returns the value, otherwise returns the result
* produced by the supplying function.
*
* @param supplier the supplying function that produces a value to be returned
* @return the value, if present, otherwise the result produced by the
* supplying function
* @throws NullPointerException if no value is present and the supplying
* function is {@code null}
*/
public double orElseGet(DoubleSupplier supplier) {
return isPresent ? value : supplier.getAsDouble();
}
/**
* If a value is present, returns the value, otherwise throws
* {@code NoSuchElementException}.
*
* @return the value described by this {@code OptionalDouble}
* @throws NoSuchElementException if no value is present
* @since 10
*/
public double orElseThrow() {
if (!isPresent) {
throw new NoSuchElementException("No value present");
}
return value;
}
/**
* If a value is present, returns the value, otherwise throws an exception
* produced by the exception supplying function.
*
* @param <X> Type of the exception to be thrown
* @param exceptionSupplier the supplying function that produces an
* exception to be thrown
* @return the value, if present
* @throws X if no value is present
* @throws NullPointerException if no value is present and the exception
* supplying function is {@code null}
* @apiNote A method reference to the exception constructor with an empty argument
* list can be used as the supplier. For example,
* {@code IllegalStateException::new}
*/
public <X extends Throwable> double orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (isPresent) {
return value;
} else {
throw exceptionSupplier.get();
}
}
/**
* Indicates whether some other object is "equal to" this
* {@code OptionalDouble}. The other object is considered equal if:
* <ul>
* <li>it is also an {@code OptionalDouble} and;
* <li>both instances have no value present or;
* <li>the present values are "equal to" each other via
* {@code Double.compare() == 0}.
* </ul>
*
* @param obj an object to be tested for equality
* @return {@code true} if the other object is "equal to" this object
* otherwise {@code false}
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof OptionalDouble)) {
return false;
}
OptionalDouble other = (OptionalDouble) obj;
return (isPresent && other.isPresent
? Double.compare(value, other.value) == 0
: isPresent == other.isPresent);
}
/**
* Returns the hash code of the value, if present, otherwise {@code 0}
* (zero) if no value is present.
*
* @return hash code value of the present value or {@code 0} if no value is
* present
*/
@Override
public int hashCode() {
return isPresent ? Double.hashCode(value) : 0;
}
/**
* Returns a non-empty string representation of this {@code OptionalDouble}
* suitable for debugging. The exact presentation format is unspecified and
* may vary between implementations and versions.
*
* @return the string representation of this instance
* @implSpec If a value is present the result must include its string representation
* in the result. Empty and present {@code OptionalDouble}s must be
* unambiguously differentiable.
*/
@Override
public String toString() {
return isPresent
? ("OptionalDouble[" + value + "]")
: "OptionalDouble.empty";
}
}

View file

@ -1,69 +0,0 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package rs.chir.compat.java.util.function;
import java.util.Objects;
/**
* Represents an operation that accepts a single input argument and returns no
* result. Unlike most other functional interfaces, {@code Consumer} is expected
* to operate via side-effects.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #accept(Object)}.
*
* @param <T> the type of the input to the operation
* @since 1.8
*/
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> {
this.accept(t);
after.accept(t);
};
}
}

View file

@ -1,70 +0,0 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package rs.chir.compat.java.util.function;
import java.util.Objects;
/**
* Represents an operation that accepts a single {@code double}-valued argument and
* returns no result. This is the primitive type specialization of
* {@link Consumer} for {@code double}. Unlike most other functional interfaces,
* {@code DoubleConsumer} is expected to operate via side-effects.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #accept(double)}.
*
* @see Consumer
* @since 1.8
*/
@FunctionalInterface
public interface DoubleConsumer {
/**
* Performs this operation on the given argument.
*
* @param value the input argument
*/
void accept(double value);
/**
* Returns a composed {@code DoubleConsumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code DoubleConsumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default DoubleConsumer andThen(DoubleConsumer after) {
Objects.requireNonNull(after);
return (double t) -> {
this.accept(t);
after.accept(t);
};
}
}

View file

@ -1,49 +0,0 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package rs.chir.compat.java.util.function;
/**
* Represents a supplier of {@code double}-valued results. This is the
* {@code double}-producing primitive specialization of {@link Supplier}.
*
* <p>There is no requirement that a distinct result be returned each
* time the supplier is invoked.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #getAsDouble()}.
*
* @see Supplier
* @since 1.8
*/
@FunctionalInterface
public interface DoubleSupplier {
/**
* Gets a result.
*
* @return a result
*/
double getAsDouble();
}

View file

@ -1,97 +0,0 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package rs.chir.compat.java.util.function;
import java.util.Objects;
/**
* Represents a function that accepts one argument and produces a result.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object)}.
*
* @param <T> the type of the input to the function
* @param <R> the type of the result of the function
* @since 1.8
*/
@FunctionalInterface
public interface Function<T, R> {
/**
* Returns a function that always returns its input argument.
*
* @param <T> the type of the input and output objects to the function
* @return a function that always returns its input argument
*/
static <T> Function<T, T> identity() {
return t -> t;
}
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
* @see #andThen(Function)
*/
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> this.apply(before.apply(v));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
* @see #compose(Function)
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(this.apply(t));
}
}

View file

@ -1,136 +0,0 @@
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package rs.chir.compat.java.util.function;
import java.util.Objects;
/**
* Represents a predicate (boolean-valued function) of one argument.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #test(Object)}.
*
* @param <T> the type of the input to the predicate
* @since 1.8
*/
@FunctionalInterface
public interface Predicate<T> {
/**
* Returns a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}.
*
* @param <T> the type of arguments to the predicate
* @param targetRef the object reference with which to compare for equality,
* which may be {@code null}
* @return a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}
*/
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
/**
* Returns a predicate that is the negation of the supplied predicate.
* This is accomplished by returning result of the calling
* {@code target.negate()}.
*
* @param <T> the type of arguments to the specified predicate
* @param target predicate to negate
* @return a predicate that negates the results of the supplied
* predicate
* @throws NullPointerException if target is null
* @since 11
*/
@SuppressWarnings("unchecked")
static <T> Predicate<T> not(Predicate<? super T> target) {
Objects.requireNonNull(target);
return (Predicate<T>) target.negate();
}
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
/**
* Returns a composed predicate that represents a short-circuiting logical
* AND of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code false}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ANDed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* AND of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> this.test(t) && other.test(t);
}
/**
* Returns a predicate that represents the logical negation of this
* predicate.
*
* @return a predicate that represents the logical negation of this
* predicate
*/
default Predicate<T> negate() {
return (t) -> !this.test(t);
}
/**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code true}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ORed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* OR of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> this.test(t) || other.test(t);
}
}

View file

@ -1,48 +0,0 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package rs.chir.compat.java.util.function;
/**
* Represents a supplier of results.
*
* <p>There is no requirement that a new or distinct result be returned each
* time the supplier is invoked.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #get()}.
*
* @param <T> the type of results supplied by this supplier
* @since 1.8
*/
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}

View file

@ -8,8 +8,8 @@ import org.w3c.dom.Node;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import rs.chir.compat.java.util.Optional;
import rs.chir.utils.IterableNodeList; import rs.chir.utils.IterableNodeList;
import rs.chir.utils.MappableList; import rs.chir.utils.MappableList;
import rs.chir.utils.xml.SimpleXML; import rs.chir.utils.xml.SimpleXML;

View file

@ -9,8 +9,8 @@ import java.io.IOException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.Objects; import java.util.Objects;
import rs.chir.compat.java.util.Optional; import java.util.Optional;
import rs.chir.compat.java.util.OptionalDouble; import java.util.OptionalDouble;
import rs.chir.utils.IterableNodeList; import rs.chir.utils.IterableNodeList;
import rs.chir.utils.xml.XMLSerializable; import rs.chir.utils.xml.XMLSerializable;

View file

@ -9,8 +9,8 @@ import org.w3c.dom.Node;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import rs.chir.compat.java.util.Optional;
import rs.chir.utils.xml.SimpleXML; import rs.chir.utils.xml.SimpleXML;
import rs.chir.utils.xml.XMLSerializable; import rs.chir.utils.xml.XMLSerializable;

View file

@ -6,8 +6,8 @@ import java.util.AbstractList;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import rs.chir.compat.java.util.Optional; import java.util.function.Function;
import rs.chir.compat.java.util.function.Function; import java.util.Optional;
/** /**
* A list that supports mapping and filter-mapping on old java. * A list that supports mapping and filter-mapping on old java.

View file

@ -7,7 +7,7 @@ import org.jetbrains.annotations.Contract;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import rs.chir.compat.java.util.function.Supplier; import java.util.function.Supplier;
/** /**
* Thread local storage. Exists because Android 5 and 6 dont support native TLS. * Thread local storage. Exists because Android 5 and 6 dont support native TLS.

View file

@ -11,13 +11,13 @@ dependencies {
implementation 'androidx.annotation:annotation:1.4.0' implementation 'androidx.annotation:annotation:1.4.0'
implementation project(':invtracker') implementation project(':invtracker')
implementation 'dev.paseto:jpaseto-api:0.7.0' implementation 'dev.paseto:jpaseto-api:0.7.0'
implementation 'org.springframework.security:spring-security-crypto:5.7.2' implementation 'org.springframework.security:spring-security-crypto:5.7.3'
runtimeOnly 'org.xerial:sqlite-jdbc:3.36.0.3' runtimeOnly 'org.xerial:sqlite-jdbc:3.39.2.0'
runtimeOnly 'dev.paseto:jpaseto-impl:0.7.0' runtimeOnly 'dev.paseto:jpaseto-impl:0.7.0'
runtimeOnly 'dev.paseto:jpaseto-jackson:0.7.0' runtimeOnly 'dev.paseto:jpaseto-jackson:0.7.0'
runtimeOnly 'commons-logging:commons-logging:1.2' runtimeOnly 'commons-logging:commons-logging:1.2'
implementation 'org.bouncycastle:bcprov-jdk18on:1.71' implementation 'org.bouncycastle:bcprov-jdk18on:1.71.1'
} }
application { application {

View file

@ -18,8 +18,8 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import rs.chir.compat.java.util.Optional; import java.util.Optional;
import rs.chir.compat.java.util.OptionalDouble; import java.util.OptionalDouble;
import rs.chir.db.CommitBehavior; import rs.chir.db.CommitBehavior;
import rs.chir.db.DBConnection; import rs.chir.db.DBConnection;
import rs.chir.invtracker.model.Cursor; import rs.chir.invtracker.model.Cursor;

View file

@ -21,8 +21,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import rs.chir.compat.java.util.Optional; import java.util.Optional;
import rs.chir.compat.java.util.OptionalDouble; import java.util.OptionalDouble;
import rs.chir.db.CommitBehavior; import rs.chir.db.CommitBehavior;
import rs.chir.db.DBConnection; import rs.chir.db.DBConnection;
import rs.chir.invtracker.model.Cursor; import rs.chir.invtracker.model.Cursor;