<commit_before>/**
 *    Retz
 *    Copyright (C) 2016 Nautilus Technologies, Inc.
 *
 *    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 io.github.retz.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import io.github.retz.protocol.*;
import io.github.retz.scheduler.JobQueue;
import org.eclipse.jetty.util.ConcurrentHashSet;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketException;
import org.eclipse.jetty.websocket.api.annotations.*;
import org.eclipse.jetty.websocket.api.extensions.Frame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@WebSocket
public class ConsoleWebSocketHandler {
    private static final Logger LOG = LoggerFactory.getLogger(ConsoleWebSocketHandler.class);

    // TODO: duplicate set of sessions; remove
    private static final Set<Session> SESSIONS = new ConcurrentHashSet<>();
    private static final Set<Session> WATCHERS = new ConcurrentHashSet<>();
    private static final Map<Integer, Session> JOB_WATCHERS = new ConcurrentHashMap<>();
    private final ObjectMapper MAPPER = new ObjectMapper();

    {
        MAPPER.registerModule(new Jdk8Module());
    }

    public static void broadcast(String event, Job job, String status) {
        // TODO: make use of static members
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new Jdk8Module());

        WatchResponse res = new WatchResponse(event, job);
        res.status(status);
        try {
            String msg = mapper.writeValueAsString(res);
            broadcast(msg);
        } catch (JsonProcessingException e) {
            LOG.error("never comes here");
        }
    }

    private static void broadcast(String msg) {
        LOG.info("Broadcasting {}", msg);
        //List<Future<Void>> results = new LinkedList<>();
        for (Session s : WATCHERS) {
            //results.add(s.getRemote().sendStringByFuture(msg));
            s.getRemote().sendStringByFuture(msg);

        }
        /*
        for (Future<Void> f : results) {
            try {
                f.get();  // TODO: do we really need this wait?
            } catch (InterruptedException e) {
            } catch (ExecutionException e) {
                   LOG.warn("cannot send broadcast: {}", e.getCause().toString());
            }
        }*/
    }

    public static void sendPingAll() {
        for (Session s : WATCHERS) {
            try {
                ByteBuffer ping = ByteBuffer.wrap("ping".getBytes(StandardCharsets.UTF_8));
                LOG.debug("Sending ping to {}", s.getRemoteAddress().getHostName());
                s.getRemote().sendPing(ping);
            } catch (IOException e) {
                LOG.warn("cannot send to {}: {}", s.getRemoteAddress().getHostName(), e.toString());
                s.close();
                WATCHERS.remove(s);
            }
        }<commit_msg>Why the heck WebSocketException is non-checked<commit_after>/**
 *    Retz
 *    Copyright (C) 2016 Nautilus Technologies, Inc.
 *
 *    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 io.github.retz.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import io.github.retz.protocol.*;
import io.github.retz.scheduler.JobQueue;
import org.eclipse.jetty.util.ConcurrentHashSet;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketException;
import org.eclipse.jetty.websocket.api.annotations.*;
import org.eclipse.jetty.websocket.api.extensions.Frame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@WebSocket
public class ConsoleWebSocketHandler {
    private static final Logger LOG = LoggerFactory.getLogger(ConsoleWebSocketHandler.class);

    // TODO: duplicate set of sessions; remove
    private static final Set<Session> SESSIONS = new ConcurrentHashSet<>();
    private static final Set<Session> WATCHERS = new ConcurrentHashSet<>();
    private static final Map<Integer, Session> JOB_WATCHERS = new ConcurrentHashMap<>();
    private final ObjectMapper MAPPER = new ObjectMapper();

    {
        MAPPER.registerModule(new Jdk8Module());
    }

    public static void broadcast(String event, Job job, String status) {
        // TODO: make use of static members
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new Jdk8Module());

        WatchResponse res = new WatchResponse(event, job);
        res.status(status);
        try {
            String msg = mapper.writeValueAsString(res);
            broadcast(msg);
        } catch (JsonProcessingException e) {
            LOG.error("never comes here");
        }
    }

    // TODO: I'm afraid of all race condition touching sessions
    private static void broadcast(String msg) {
        LOG.info("Broadcasting {}", msg);
        List<Session> badSessions = new LinkedList<>();
        for (Session s : WATCHERS) {
            //results.add(s.getRemote().sendStringByFuture(msg));
            try {
                s.getRemote().sendStringByFuture(msg);
            } catch (RuntimeException e) {
                LOG.info(e.toString());
                badSessions.add(s);
            }
        }
        // Fire all bad sessions
        WATCHERS.removeAll(badSessions);
        for (Session s : badSessions) {
            s.close();
        }
    }

    public static void sendPingAll() {
        for (Session s : WATCHERS) {
            try {
                ByteBuffer ping = ByteBuffer.wrap("ping".getBytes(StandardCharsets.UTF_8));
                LOG.debug("Sending ping to {}", s.getRemoteAddress().getHostName());
                s.getRemote().sendPing(ping);
            } catch (IOException e) {
                LOG.warn("cannot send to {}: {}", s.getRemoteAddress().getHostName(), e.toString());
                s.close();
                WATCHERS.remove(s);
            }
        }
{'fraction_non_alphanumeric': 0.10643754808925365, 'fraction_numerical': 0.003847140292382662, 'mean_word_length': 2.804390243902439, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 6}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '260540', 'n_tokens_mistral': 2181, 'n_tokens_neox': 2110, 'n_words': 573}