<commit_before>/**
 * Copyright (c) 2010-2017 by the respective copyright holders.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.openhab.binding.kodi.internal.protocol;

import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * KodiClientSocket implements the low level communication to kodi through websocket. Usually this communication is done
 * through port 9090
 *
 * @author <NAME>
 *
 */
public class KodiClientSocket {
    private final Logger logger = LoggerFactory.getLogger(KodiClientSocket.class);

    private final ScheduledExecutorService scheduler;
    private static final int REQUEST_TIMEOUT_MS = 60000;

    private CountDownLatch commandLatch = null;
    private JsonObject commandResponse = null;
    private int nextMessageId = 1;

    private boolean connected = false;

    private final JsonParser parser = new JsonParser();
    private final Gson mapper = new Gson();
    private URI uri;
    private Session session;
    private WebSocketClient client;

    private final KodiClientSocketEventListener eventHandler;

    public KodiClientSocket(KodiClientSocketEventListener eventHandler, URI uri, ScheduledExecutorService scheduler) {
        this.eventHandler = eventHandler;
        this.uri = uri;
        client = new WebSocketClient();
        this.scheduler = scheduler;
    }

    /**
     * Attempts to create a connection to the kodi host and begin listening
     * for updates over the async http web socket
     *
     * @throws Exception
     */
    public synchronized void open() throws Exception {
        if (isConnected()) {
            logger.warn("connect: connection is already open");
        }
        if (!client.isStarted()) {
            client.start();
        }
        KodiWebSocketListener socket = new KodiWebSocketListener();
        ClientUpgradeRequest request = new ClientUpgradeRequest();

        client.connect(socket, uri, request);
    }

    /***
     * Close this connection to the kodi instance
     */
    public void close() {
        // if there is an old web socket then clean up and destroy
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
                logger.error("Exception during closing the websocket {}", e.getMessage(), e);
            }
            session = null;
        }
        try {
            client.stop();
        } catch (Exception e) {
            logger.error("Exception during closing the websocket {}", e.getMessage(), e);
        }
    }

    public boolean isConnected() {
        if (session == null || !session.isOpen()) {
            return false;
        }

        return connected;
    }

    @WebSocket
    public class KodiWebSocketListener {

        @OnWebSocketConnect
        public void onConnect(Session wssession) {
            logger.debug("Connected to server");
            session = wssession;
            connected = true;
            if (eventHandler != null) {
                scheduler.submit(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            eventHandler.onConnectionOpened();
                        } catch (Exception e) {
                            logger.error("Error handling onConnectionOpened() {}", e.getMessage(), e);
                        }

                    }
                });

            }
        }

        @OnWebSocketMessage
        public void onMessage(String message) {
            logger.debug("Message received from server: {}", message);
            final JsonObject json = parser.parse(message).getAsJsonObject();
            if (json.has("id")) {
                logger.debug("Response received from server:" + json.toString());
                int messageId = json.get("id").getAsInt();
                if (messageId == nextMessageId - 1) {
                    commandResponse = json;
                    commandLatch.countDown();
                }
            } else {
                logger.debug("Event received from server: {}", json.toString());
                try {
                    if (eventHandler != null) {
                        scheduler.submit(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    eventHandler.handleEvent(json);
                                } catch (Exception e) {
                                    logger.error("Error handling event {} player state change message: {}", json,
                                            e.getMessage(), e);
                                }

                            }
                        });

                    }
                } catch (Exception e) {
                    logger.error("Error handling player state change message", e);
                }
            }
        }<commit_msg>removed further logger messages that are not constants (related to #2088) (#2119)<commit_after>/**
 * Copyright (c) 2010-2017 by the respective copyright holders.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.openhab.binding.kodi.internal.protocol;

import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * KodiClientSocket implements the low level communication to kodi through websocket. Usually this communication is done
 * through port 9090
 *
 * @author <NAME>
 *
 */
public class KodiClientSocket {
    private final Logger logger = LoggerFactory.getLogger(KodiClientSocket.class);

    private final ScheduledExecutorService scheduler;
    private static final int REQUEST_TIMEOUT_MS = 60000;

    private CountDownLatch commandLatch = null;
    private JsonObject commandResponse = null;
    private int nextMessageId = 1;

    private boolean connected = false;

    private final JsonParser parser = new JsonParser();
    private final Gson mapper = new Gson();
    private URI uri;
    private Session session;
    private WebSocketClient client;

    private final KodiClientSocketEventListener eventHandler;

    public KodiClientSocket(KodiClientSocketEventListener eventHandler, URI uri, ScheduledExecutorService scheduler) {
        this.eventHandler = eventHandler;
        this.uri = uri;
        client = new WebSocketClient();
        this.scheduler = scheduler;
    }

    /**
     * Attempts to create a connection to the kodi host and begin listening
     * for updates over the async http web socket
     *
     * @throws Exception
     */
    public synchronized void open() throws Exception {
        if (isConnected()) {
            logger.warn("connect: connection is already open");
        }
        if (!client.isStarted()) {
            client.start();
        }
        KodiWebSocketListener socket = new KodiWebSocketListener();
        ClientUpgradeRequest request = new ClientUpgradeRequest();

        client.connect(socket, uri, request);
    }

    /***
     * Close this connection to the kodi instance
     */
    public void close() {
        // if there is an old web socket then clean up and destroy
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
                logger.error("Exception during closing the websocket {}", e.getMessage(), e);
            }
            session = null;
        }
        try {
            client.stop();
        } catch (Exception e) {
            logger.error("Exception during closing the websocket {}", e.getMessage(), e);
        }
    }

    public boolean isConnected() {
        if (session == null || !session.isOpen()) {
            return false;
        }

        return connected;
    }

    @WebSocket
    public class KodiWebSocketListener {

        @OnWebSocketConnect
        public void onConnect(Session wssession) {
            logger.debug("Connected to server");
            session = wssession;
            connected = true;
            if (eventHandler != null) {
                scheduler.submit(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            eventHandler.onConnectionOpened();
                        } catch (Exception e) {
                            logger.error("Error handling onConnectionOpened() {}", e.getMessage(), e);
                        }

                    }
                });

            }
        }

        @OnWebSocketMessage
        public void onMessage(String message) {
            logger.debug("Message received from server: {}", message);
            final JsonObject json = parser.parse(message).getAsJsonObject();
            if (json.has("id")) {
                logger.debug("Response received from server: {}", json);
                int messageId = json.get("id").getAsInt();
                if (messageId == nextMessageId - 1) {
                    commandResponse = json;
                    commandLatch.countDown();
                }
            } else {
                logger.debug("Event received from server: {}", json);
                try {
                    if (eventHandler != null) {
                        scheduler.submit(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    eventHandler.handleEvent(json);
                                } catch (Exception e) {
                                    logger.error("Error handling event {} player state change message: {}", json,
                                            e.getMessage(), e);
                                }

                            }
                        });

                    }
                } catch (Exception e) {
                    logger.error("Error handling player state change message", e);
                }
            }
        }
{'fraction_non_alphanumeric': 0.0882800608828006, 'fraction_numerical': 0.004904447826822256, 'mean_word_length': 1.8498795180722891, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7595967', 'n_tokens_mistral': 2954, 'n_tokens_neox': 2808, 'n_words': 787}