fi.vm.kapa.identification.proxy.background.SessionCleanup.java Source code

Java tutorial

Introduction

Here is the source code for fi.vm.kapa.identification.proxy.background.SessionCleanup.java

Source

/**
 * The MIT License
 * Copyright (c) 2015 Population Register Centre
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package fi.vm.kapa.identification.proxy.background;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fi.vm.kapa.identification.type.AuthMethod;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
import org.springframework.stereotype.Service;

import fi.vm.kapa.identification.proxy.utils.SessionHandlingUtils;
import fi.vm.kapa.identification.dto.SessionDTO;

@Service
public class SessionCleanup {

    private static final Logger logger = LoggerFactory.getLogger(SessionCleanup.class);

    @Value("${sessions.cache.active.ttl}")
    private int activeSessionsTTL;

    @Value("${sessions.cache.failed.ttl}")
    private int failedSessionsTTL;

    @Autowired
    private SessionHandlingUtils sessionHandlingUtils;

    public void runCleanup() {
        try {
            // Using time reference in minutes is good enough for a time frame for expiration
            long failedTTLThreshold = System.currentTimeMillis() - failedSessionsTTL * 60000;
            long activeTTLThreshold = System.currentTimeMillis() - activeSessionsTTL * 60000;

            Map<String, Map<AuthMethod, SessionDTO>> sessionsInCache = sessionHandlingUtils.getSessionsCache();
            List<Pair<String, AuthMethod>> toBeRemoved = new ArrayList<>();

            long originalSize = 0;
            for (Map<AuthMethod, SessionDTO> sessionDTOMap : sessionsInCache.values()) {
                originalSize += sessionDTOMap.size();
            }

            logger.info("Currently there are {} sessions in cache", originalSize);

            sessionsInCache.forEach((key, sessionDTOMap) -> sessionDTOMap.forEach((authMethod, sessionDTO) -> {
                if ((sessionDTO.isValidated() && sessionDTO.getTimestamp() < activeTTLThreshold)
                        || (!sessionDTO.isValidated() && sessionDTO.getTimestamp() < failedTTLThreshold)) {
                    toBeRemoved.add(new Pair<>(key, authMethod));
                }
            }));

            toBeRemoved
                    .forEach((pair) -> sessionHandlingUtils.removeFromSessionCache(pair.getKey(), pair.getValue()));

            long finalSize = 0;
            for (Map<AuthMethod, SessionDTO> sessionDTOMap : sessionsInCache.values()) {
                finalSize += sessionDTOMap.size();
            }
            logger.info("Removed {} expired sessions from cache", originalSize - finalSize);
        } catch (Exception e) {
            logger.error("Error running session cleanup", e);
        }
    }
}