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

com.github.robozonky.internal.remote.Api Maven / Gradle / Ivy

There is a newer version: 6.4.1
Show newest version
/*
 * Copyright 2021 The RoboZonky Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.robozonky.internal.remote;

import java.time.Duration;
import java.util.function.Consumer;
import java.util.function.Function;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

class Api {

    private static final Logger LOGGER = LogManager.getLogger(Api.class);
    private static final Duration ONE_MINUTE = Duration.ofMinutes(1);
    private static final Duration FIVE_MINUTES = Duration.ofMinutes(5);

    private final T proxy;
    private final RequestCounter counter;

    Api(final T proxy) {
        this(proxy, null);
    }

    public Api(final T proxy, final RequestCounter counter) {
        this.proxy = proxy;
        this.counter = counter;
    }

    static  Z call(final Function function, final Y proxy, final RequestCounter counter) {
        LOGGER.trace("Executing...");
        try {
            return function.apply(proxy);
        } finally {
            if (counter != null) {
                counter.mark();
                LOGGER.trace("... done. (Request counts: {} in last 60 sec., {} in last 5 min.)",
                        () -> counter.count(ONE_MINUTE), () -> counter.count(FIVE_MINUTES));
            } else {
                LOGGER.trace("... done. (Not counting towards the API quota.)");
            }
        }
    }

     S call(final Function function) {
        return call(function, proxy, counter);
    }

    void run(final Consumer consumer) {
        final Function wrapper = t -> {
            consumer.accept(t);
            return false; // we need to return something
        };
        call(wrapper);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy