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

se.kth.iss.ug2.KeepAlive Maven / Gradle / Ivy

/*
 * MIT License
 *
 * Copyright (c) 2017 Kungliga Tekniska högskolan
 *
 * 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 se.kth.iss.ug2;

import java.time.Instant;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Keep-alive for {@link Ug2Client}.
 */
public class KeepAlive {
    private final List clients = new CopyOnWriteArrayList<>();
    private final long keepaliveInterval;
    private final long maxUnusedTime;

    public KeepAlive(long keepaliveInterval, long maxUnusedTime) {
        this.keepaliveInterval = keepaliveInterval;
        this.maxUnusedTime = maxUnusedTime;
    }

    synchronized void addClient(Ug2Client client) {
        clients.add(client);
    }

    synchronized void removeClient(Ug2Client client) {
        clients.remove(client);
    }

    public void keepalive() {
        clients.stream().filter(this::matchUnused).forEach(Ug2Client::sendKeepAlive);
    }

    private boolean matchUnused(Ug2Client client) {
        return client.getLastAccessed().isBefore(Instant.now().minusSeconds(maxUnusedTime));
    }

    void startKeepAlive(ScheduledExecutorService keepAliveService) {
        keepAliveService.scheduleWithFixedDelay(this::keepalive, 0L, keepaliveInterval, TimeUnit.SECONDS);
    }

    public void stopKeepAlive() {
        for (Ug2Client client : clients) {
            clients.remove(client);
            client.closeSession("KeepAlive-" + client.sessionId());
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy