All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.truelicense.core.Cache Maven / Gradle / Ivy

Go to download

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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy