Velocity

I uploaded only implementation.
mail@pastecode.io avatar
unknown
java
2 years ago
2.6 kB
2
Indexable
Never
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.stream.Collectors;


public class Velo implements VelocityProvider {

    ConcurrentHashMap<String, List<Payment>> mapList = new ConcurrentHashMap<>();


    @Override
    public int getUsingCountOfCard(String cardNumber, Duration duration) {
        if (mapList.containsKey(cardNumber)) {
            List<Payment> payments = mapList.get(cardNumber);
            Instant instant = Instant.now().minusSeconds(duration.getSeconds());
            List<Payment> collect = payments.parallelStream().filter(isLaterThan(instant)).collect(Collectors.<Payment>toList());
            return collect.size();
        } else {
            return 0;
        }
    }


    public static Predicate<Payment> isLaterThan(Instant instant) {
        return payment -> payment.getInstant().isAfter(instant);
    }


    @Override
    public void registerPayment(Payment payment) {
        if (mapList.get(payment.getCardNumber()) != null) {
            mapList.get(payment.getCardNumber()).add(payment);
        } else {
            List<Payment> list = new ArrayList<>();
            list.add(payment);
            mapList.put(payment.getCardNumber(), list);
        }
    }


    public static void main(String[] args) {
        VelocityProvider velo = new Velo();
        registerMock(velo, 3600000, "cardOne"); // 1 hour
        registerMock(velo, 10800000, "cardTwo"); // 3 hours
        registerMock(velo, 18000000, "cardThree"); // 5 hours
        registerMock(velo, 72000000, "cardFour"); // 20 hours


        long now = System.currentTimeMillis();

        System.out.println(velo.getUsingCountOfCard("cardOne", Duration.ofDays(10)));
        System.out.println(velo.getUsingCountOfCard("cardTwo", Duration.ofDays(10)));
        System.out.println(velo.getUsingCountOfCard("cardThree", Duration.ofDays(10)));
        System.out.println(velo.getUsingCountOfCard("cardFour", Duration.ofDays(10)));

        System.out.println(System.currentTimeMillis() - now + "ms.");


    }

    private static void registerMock(VelocityProvider velo, long period, String cardName) {
        Long now = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            Payment p1 = new Payment();
            p1.setCardNumber(cardName);
            p1.setInstant(Instant.ofEpochMilli(now));
            now = now - period;
            velo.registerPayment(p1);
        }
    }
}