TokenSingleton.java 1.34 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
package web.multitask.trismegistoservices.singleton;

import lombok.Getter;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.stream.IntStream;

@Getter
@Component
public class TokenSingleton {

    private final JSONArray tokens = new JSONArray();

    public boolean consumeToken(String token) {
        boolean isAvailable = false;
        for (int i = 0; i < tokens.length(); i++) {
            if (tokens.getJSONObject(i).getString("token").equals(token)) {
                if (tokens.getJSONObject(i).getBoolean("available")) {
                    tokens.getJSONObject(i).put("available", false);
                    isAvailable = true;
                }
                break;
            }
        }
        return isAvailable;
    }

    public void addToken(String token) {
        tokens.put(new JSONObject().put("token", token).put("available", true));
    }

    public TokenSingleton() {

    }
    @Scheduled(fixedRate = 3600000)
    public void removeUnavailableTokens() {
        System.out.println("Removing unavailable tokens");
        IntStream.range(0, tokens.length()).forEach(i -> {
            if (!tokens.getJSONObject(i).getBoolean("available")) {
                tokens.remove(i);
            }
        });
    }
}