net.truelicense.core.Cache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of truelicense-core Show documentation
Show all versions of truelicense-core Show documentation
The TrueLicense Core module provides essential functionality for
license management.
The newest version!
/*
* Copyright (C) 2005-2017 Schlichtherle IT Services.
* All rights reserved. Use is subject to license terms.
*/
package net.truelicense.core;
import java.util.Optional;
import static java.lang.System.currentTimeMillis;
/**
* A simple cache with just one association.
* This class is immutable.
*
* @author Christian Schlichtherle
*/
final class Cache {
private final Optional optKey;
private final Optional optValue;
private final long cachePeriodMillis;
private final long startTimeMillis = currentTimeMillis();
Cache() {
this(Optional.empty(), Optional.empty(), 0); } // => obsolete() == true
Cache(final Optional optKey, final Optional optValue, final long cachePeriodMillis) {
this.optKey = optKey;
this.optValue = optValue;
if (0 > (this.cachePeriodMillis = cachePeriodMillis))
throw new IllegalArgumentException();
}
Cache key(Optional optKey) {
return hasKey(optKey) ? this : new Cache<>(optKey, optValue, cachePeriodMillis);
}
Optional map(Optional optKey) {
return hasKey(optKey) && !obsolete() ? optValue : Optional.empty();
}
boolean hasKey(Optional optKey) {
return optKey.equals(this.optKey);
}
boolean obsolete() {
return currentTimeMillis() - startTimeMillis >= cachePeriodMillis;
}
}