From 47f014c344d3033cc9d59b65712ad6489edfbc47 Mon Sep 17 00:00:00 2001 From: Nikky Ai Date: Sun, 21 Jan 2018 08:16:54 +0100 Subject: [PATCH] more cleanup --- .../civilengineering/CivilEngineering.kt | 13 +- .../CancellableConnectionFollowThread.kt | 2 +- .../civilengineering/bridge/MessageHandler.kt | 223 +++++------------- .../bridge/ServerChatHelper.kt | 4 +- .../civilengineering/command/BridgeCommand.kt | 4 +- 5 files changed, 75 insertions(+), 171 deletions(-) diff --git a/src/main/kotlin/civilengineering/CivilEngineering.kt b/src/main/kotlin/civilengineering/CivilEngineering.kt index 93d0c0d..8806634 100644 --- a/src/main/kotlin/civilengineering/CivilEngineering.kt +++ b/src/main/kotlin/civilengineering/CivilEngineering.kt @@ -41,7 +41,8 @@ object CivilEngineering { } var config: Configuration = Configuration() -// var messageNetworkThread = Thread(MessageHandler()) + + //create fake logger to get around Nullability var logger: Logger = SimpleLogger ("", Level.OFF, false, @@ -56,9 +57,9 @@ object CivilEngineering { @Mod.EventHandler fun preInit(event: FMLPreInitializationEvent) { logger = event.modLog - logger!!.info("loading logger") + logger.info("loading logger") - CivilEngineering.logger!!.info("Reading bridge blueprints...") + CivilEngineering.logger.info("Reading bridge blueprints...") val directory = event.modConfigurationDirectory config = Configuration(File(directory.path, "CivilEngineering.cfg")) Config.readConfig() @@ -66,7 +67,7 @@ object CivilEngineering { @Mod.EventHandler fun init(event: FMLInitializationEvent) { - logger!!.info("Bridge building init.") + logger.info("Bridge building init.") } @Mod.EventHandler @@ -81,7 +82,7 @@ object CivilEngineering { @Mod.EventHandler fun serverStarting(event: FMLServerStartingEvent) { event.registerServerCommand(BridgeCommand()) - logger!!.info("Bridge building starting.") + logger.info("Bridge building starting.") MessageHandler.start() //maybe try registering them manually @@ -92,7 +93,7 @@ object CivilEngineering { @Mod.EventHandler fun serverStopping(event: FMLServerStoppingEvent) { - logger!!.info("Bridge shutting down.") + logger.info("Bridge shutting down.") MessageHandler.stop() } } diff --git a/src/main/kotlin/civilengineering/bridge/CancellableConnectionFollowThread.kt b/src/main/kotlin/civilengineering/bridge/CancellableConnectionFollowThread.kt index e4cf255..a231897 100644 --- a/src/main/kotlin/civilengineering/bridge/CancellableConnectionFollowThread.kt +++ b/src/main/kotlin/civilengineering/bridge/CancellableConnectionFollowThread.kt @@ -9,7 +9,7 @@ import java.net.HttpURLConnection * @version 1.0 */ -class CancellableConnectionFollowThread (val httpConnClosure: () -> HttpURLConnection, val mhandler: (String) -> Unit): Thread() { +class CancellableConnectionFollowThread (httpConnClosure: () -> HttpURLConnection, private val mhandler: (String) -> Unit): Thread() { val cancelGuard = Object() var waitingOnNetwork = true var cancelled = false diff --git a/src/main/kotlin/civilengineering/bridge/MessageHandler.kt b/src/main/kotlin/civilengineering/bridge/MessageHandler.kt index cb32559..db02f61 100644 --- a/src/main/kotlin/civilengineering/bridge/MessageHandler.kt +++ b/src/main/kotlin/civilengineering/bridge/MessageHandler.kt @@ -2,186 +2,91 @@ package civilengineering.bridge import civilengineering.CivilEngineering import civilengineering.Config -import com.google.gson.Gson -import java.io.BufferedReader import java.io.DataOutputStream import java.io.IOException -import java.io.InputStreamReader -import java.lang.Thread.sleep import java.net.HttpURLConnection import java.net.URL import java.util.concurrent.ConcurrentLinkedQueue -class MessageHandler : Runnable { - override fun run() { - CivilEngineering.logger!!.info("Connecting to bridge server @ " + Config.connectURL) - try { - while (true) { - transmitFromQueue() -// receiveToQueue() - sleep(1000) - } - } catch (e: Exception) { +object MessageHandler { - if (e is InterruptedException) { - CivilEngineering.logger!!.info("Connection closed.") - } else if (e is IOException) { - CivilEngineering.logger!!.error("Error connecting to bridge server!") - CivilEngineering.logger!!.error(e.message) + private fun createThread(): CancellableConnectionFollowThread { + return CancellableConnectionFollowThread( + { + CivilEngineering.logger.info("Connecting to bridge server @ " + Config.connectURL) + val httpConn = URL(Config.connectURL + "/api/stream").openConnection() as HttpURLConnection + if (Config.authToken.isNotBlank()) + httpConn.setRequestProperty("Authorization", "Bearer ${Config.authToken}") + httpConn + }, + { + rcvQueue.add( + ApiMessage.decode(it) + ) + CivilEngineering.logger.trace("received: " + it) + } + ) + } - } + private var cancellableThread: CancellableConnectionFollowThread = createThread() + + private var xmitQueue = ConcurrentLinkedQueue() + + var rcvQueue = ConcurrentLinkedQueue() + + fun transmit(msg: ApiMessage) { + CivilEngineering.logger.info("transmitting " + msg) + transmitMessage(msg) + //TODO: create thread with Runnable(sendstuff).execute() + } + + fun stop() { + cancellableThread.abort() + CivilEngineering.logger.info("bridge closed ") + } + + fun start(): Boolean { + if (cancellableThread.isInterrupted) { + CivilEngineering.logger.info("rebuilding bridge") + cancellableThread = createThread() } + if (!cancellableThread.isAlive) { + cancellableThread.start() + return true + } + return false } @Throws(IOException::class) - private fun transmitFromQueue() { - var nextMessage: ApiMessage? = xmitQueue.poll() - while (nextMessage != null) { - //open a connection - val url = URL(Config.connectURL + "/api/message") - val urlConnection = url.openConnection() - val connection = urlConnection as HttpURLConnection - - //configure the connection - connection.allowUserInteraction = false - connection.instanceFollowRedirects = true - connection.setRequestProperty("Content-Type", "application/json") - connection.requestMethod = "POST" - if (Config.authToken.isNotEmpty()) { - connection.setRequestProperty("Authorization", "Bearer " + Config.authToken) - } - - //encode the ApiMessage for sending - val json = nextMessage.encode() - - //send the message - connection.doOutput = true - val post = DataOutputStream(connection.outputStream) - post.writeBytes(json) - post.flush() - post.close() - - if (connection.responseCode != 200) { - CivilEngineering.logger!!.error("Server returned " + connection.responseCode) - break - } - nextMessage = xmitQueue.poll() - } - } - - @Throws(IOException::class) - private fun receiveToQueue() { - val messages: Array - + private fun transmitMessage(message: ApiMessage) { //open a connection - val url = URL(Config.connectURL + "/api/messages") - val con = url.openConnection() as HttpURLConnection + val url = URL(Config.connectURL + "/api/message") + val urlConnection = url.openConnection() + val connection = urlConnection as HttpURLConnection //configure the connection - con.allowUserInteraction = false - con.instanceFollowRedirects = true + connection.allowUserInteraction = false + connection.instanceFollowRedirects = true + connection.setRequestProperty("Content-Type", "application/json") + connection.requestMethod = "POST" if (Config.authToken.isNotEmpty()) { - con.setRequestProperty("Authorization", "Bearer " + Config.authToken) + connection.setRequestProperty("Authorization", "Bearer " + Config.authToken) } - //read the messages - val input = BufferedReader(InputStreamReader(con.inputStream)) - val data = StringBuilder() - var line: String? - while (true) { - line = input.readLine() - if (line == null) { - break - } - data.append(line) - } - //decode the messages - val gson = Gson() - messages = gson.fromJson(data.toString(), Array::class.java) + //encode the ApiMessage for sending + val json = message.encode() - //enqueue the messages - if (messages.isNotEmpty()) for (msg in messages) rcvQueue.add(msg) - } + //send the message + connection.doOutput = true + val post = DataOutputStream(connection.outputStream) + post.writeBytes(json) + post.flush() + post.close() - companion object { - - private fun createThread(): CancellableConnectionFollowThread { - return CancellableConnectionFollowThread( - { - CivilEngineering.logger!!.info("Connecting to bridge server @ " + Config.connectURL) - val httpConn = URL(Config.connectURL + "/api/stream").openConnection() as HttpURLConnection - if (Config.authToken.isNotBlank()) - httpConn.setRequestProperty("Authorization", "Bearer ${Config.authToken}") - httpConn - }, - { - rcvQueue.add( - ApiMessage.decode(it) - ) - CivilEngineering.logger!!.trace("received: " + it) - } - ) - } - - private var cancellableThread: CancellableConnectionFollowThread = createThread() - - private var xmitQueue = ConcurrentLinkedQueue() - - var rcvQueue = ConcurrentLinkedQueue() - - fun transmit(msg: ApiMessage) { - CivilEngineering.logger!!.info("transmitting " + msg) - transmitMessage(msg) - //TODO: create thread with Runnable(sendstuff).execute() - } - - fun stop() { - cancellableThread.abort() - CivilEngineering.logger!!.info("bridge closed ") - } - - fun start(): Boolean { - if (cancellableThread.isInterrupted) { - CivilEngineering.logger!!.info("brebuilding bridge") - cancellableThread = createThread() - } - if (!cancellableThread.isAlive) { - cancellableThread.start() - return true - } - return false - } - - @Throws(IOException::class) - private fun transmitMessage(message: ApiMessage) { - //open a connection - val url = URL(Config.connectURL + "/api/message") - val urlConnection = url.openConnection() - val connection = urlConnection as HttpURLConnection - - //configure the connection - connection.allowUserInteraction = false - connection.instanceFollowRedirects = true - connection.setRequestProperty("Content-Type", "application/json") - connection.requestMethod = "POST" - if (Config.authToken.isNotEmpty()) { - connection.setRequestProperty("Authorization", "Bearer " + Config.authToken) - } - - //encode the ApiMessage for sending - val json = message.encode() - - //send the message - connection.doOutput = true - val post = DataOutputStream(connection.outputStream) - post.writeBytes(json) - post.flush() - post.close() - - if (connection.responseCode != 200) { - CivilEngineering.logger!!.error("Server returned " + connection.responseCode) - } + if (connection.responseCode != 200) { + CivilEngineering.logger.error("Server returned " + connection.responseCode) } } } + diff --git a/src/main/kotlin/civilengineering/bridge/ServerChatHelper.kt b/src/main/kotlin/civilengineering/bridge/ServerChatHelper.kt index 1175571..5d779cf 100644 --- a/src/main/kotlin/civilengineering/bridge/ServerChatHelper.kt +++ b/src/main/kotlin/civilengineering/bridge/ServerChatHelper.kt @@ -7,12 +7,10 @@ import net.minecraftforge.fml.common.eventhandler.SubscribeEvent import net.minecraftforge.fml.common.gameevent.TickEvent object ServerChatHelper { - //public static ConcurrentLinkedQueue messages = new ConcurrentLinkedQueue(); - @SubscribeEvent fun onServerUpdate(event: TickEvent.ServerTickEvent) { if(MessageHandler.rcvQueue.isNotEmpty()) - CivilEngineering.logger!!.info("incoming: " + MessageHandler.rcvQueue.toString()) + CivilEngineering.logger.info("incoming: " + MessageHandler.rcvQueue.toString()) val nextMessage = MessageHandler.rcvQueue.poll() if (nextMessage != null) { diff --git a/src/main/kotlin/civilengineering/command/BridgeCommand.kt b/src/main/kotlin/civilengineering/command/BridgeCommand.kt index 87c82d8..1178439 100644 --- a/src/main/kotlin/civilengineering/command/BridgeCommand.kt +++ b/src/main/kotlin/civilengineering/command/BridgeCommand.kt @@ -40,9 +40,9 @@ class BridgeCommand : CommandBase() { val cmd = args[0].toLowerCase() when (cmd) { "connect" -> if (MessageHandler.start()) { - logger!!.info("connected to matterbridge") + logger.info("connected to matterbridge") } else { - logger!!.error("connection to matterbridge failed") + logger.error("connection to matterbridge failed") } "disconnect" -> MessageHandler.stop() }