more cleanup

This commit is contained in:
Nikky Ai 2018-01-21 08:16:54 +01:00
parent eb2887bb46
commit 47f014c344
5 changed files with 75 additions and 171 deletions

View File

@ -41,7 +41,8 @@ object CivilEngineering {
} }
var config: Configuration = Configuration() var config: Configuration = Configuration()
// var messageNetworkThread = Thread(MessageHandler())
//create fake logger to get around Nullability
var logger: Logger = SimpleLogger ("", var logger: Logger = SimpleLogger ("",
Level.OFF, Level.OFF,
false, false,
@ -56,9 +57,9 @@ object CivilEngineering {
@Mod.EventHandler @Mod.EventHandler
fun preInit(event: FMLPreInitializationEvent) { fun preInit(event: FMLPreInitializationEvent) {
logger = event.modLog 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 val directory = event.modConfigurationDirectory
config = Configuration(File(directory.path, "CivilEngineering.cfg")) config = Configuration(File(directory.path, "CivilEngineering.cfg"))
Config.readConfig() Config.readConfig()
@ -66,7 +67,7 @@ object CivilEngineering {
@Mod.EventHandler @Mod.EventHandler
fun init(event: FMLInitializationEvent) { fun init(event: FMLInitializationEvent) {
logger!!.info("Bridge building init.") logger.info("Bridge building init.")
} }
@Mod.EventHandler @Mod.EventHandler
@ -81,7 +82,7 @@ object CivilEngineering {
@Mod.EventHandler @Mod.EventHandler
fun serverStarting(event: FMLServerStartingEvent) { fun serverStarting(event: FMLServerStartingEvent) {
event.registerServerCommand(BridgeCommand()) event.registerServerCommand(BridgeCommand())
logger!!.info("Bridge building starting.") logger.info("Bridge building starting.")
MessageHandler.start() MessageHandler.start()
//maybe try registering them manually //maybe try registering them manually
@ -92,7 +93,7 @@ object CivilEngineering {
@Mod.EventHandler @Mod.EventHandler
fun serverStopping(event: FMLServerStoppingEvent) { fun serverStopping(event: FMLServerStoppingEvent) {
logger!!.info("Bridge shutting down.") logger.info("Bridge shutting down.")
MessageHandler.stop() MessageHandler.stop()
} }
} }

View File

@ -9,7 +9,7 @@ import java.net.HttpURLConnection
* @version 1.0 * @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() val cancelGuard = Object()
var waitingOnNetwork = true var waitingOnNetwork = true
var cancelled = false var cancelled = false

View File

@ -2,114 +2,19 @@ package civilengineering.bridge
import civilengineering.CivilEngineering import civilengineering.CivilEngineering
import civilengineering.Config import civilengineering.Config
import com.google.gson.Gson
import java.io.BufferedReader
import java.io.DataOutputStream import java.io.DataOutputStream
import java.io.IOException import java.io.IOException
import java.io.InputStreamReader
import java.lang.Thread.sleep
import java.net.HttpURLConnection import java.net.HttpURLConnection
import java.net.URL import java.net.URL
import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ConcurrentLinkedQueue
class MessageHandler : Runnable {
override fun run() { object MessageHandler {
CivilEngineering.logger!!.info("Connecting to bridge server @ " + Config.connectURL)
try {
while (true) {
transmitFromQueue()
// receiveToQueue()
sleep(1000)
}
} catch (e: Exception) {
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)
}
}
}
@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<ApiMessage>
//open a connection
val url = URL(Config.connectURL + "/api/messages")
val con = url.openConnection() as HttpURLConnection
//configure the connection
con.allowUserInteraction = false
con.instanceFollowRedirects = true
if (Config.authToken.isNotEmpty()) {
con.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<ApiMessage>::class.java)
//enqueue the messages
if (messages.isNotEmpty()) for (msg in messages) rcvQueue.add(msg)
}
companion object {
private fun createThread(): CancellableConnectionFollowThread { private fun createThread(): CancellableConnectionFollowThread {
return CancellableConnectionFollowThread( return CancellableConnectionFollowThread(
{ {
CivilEngineering.logger!!.info("Connecting to bridge server @ " + Config.connectURL) CivilEngineering.logger.info("Connecting to bridge server @ " + Config.connectURL)
val httpConn = URL(Config.connectURL + "/api/stream").openConnection() as HttpURLConnection val httpConn = URL(Config.connectURL + "/api/stream").openConnection() as HttpURLConnection
if (Config.authToken.isNotBlank()) if (Config.authToken.isNotBlank())
httpConn.setRequestProperty("Authorization", "Bearer ${Config.authToken}") httpConn.setRequestProperty("Authorization", "Bearer ${Config.authToken}")
@ -119,7 +24,7 @@ class MessageHandler : Runnable {
rcvQueue.add( rcvQueue.add(
ApiMessage.decode(it) ApiMessage.decode(it)
) )
CivilEngineering.logger!!.trace("received: " + it) CivilEngineering.logger.trace("received: " + it)
} }
) )
} }
@ -131,19 +36,19 @@ class MessageHandler : Runnable {
var rcvQueue = ConcurrentLinkedQueue<ApiMessage>() var rcvQueue = ConcurrentLinkedQueue<ApiMessage>()
fun transmit(msg: ApiMessage) { fun transmit(msg: ApiMessage) {
CivilEngineering.logger!!.info("transmitting " + msg) CivilEngineering.logger.info("transmitting " + msg)
transmitMessage(msg) transmitMessage(msg)
//TODO: create thread with Runnable(sendstuff).execute() //TODO: create thread with Runnable(sendstuff).execute()
} }
fun stop() { fun stop() {
cancellableThread.abort() cancellableThread.abort()
CivilEngineering.logger!!.info("bridge closed ") CivilEngineering.logger.info("bridge closed ")
} }
fun start(): Boolean { fun start(): Boolean {
if (cancellableThread.isInterrupted) { if (cancellableThread.isInterrupted) {
CivilEngineering.logger!!.info("brebuilding bridge") CivilEngineering.logger.info("rebuilding bridge")
cancellableThread = createThread() cancellableThread = createThread()
} }
if (!cancellableThread.isAlive) { if (!cancellableThread.isAlive) {
@ -180,8 +85,8 @@ class MessageHandler : Runnable {
post.close() post.close()
if (connection.responseCode != 200) { if (connection.responseCode != 200) {
CivilEngineering.logger!!.error("Server returned " + connection.responseCode) CivilEngineering.logger.error("Server returned " + connection.responseCode)
}
} }
} }
} }

View File

@ -7,12 +7,10 @@ import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import net.minecraftforge.fml.common.gameevent.TickEvent import net.minecraftforge.fml.common.gameevent.TickEvent
object ServerChatHelper { object ServerChatHelper {
//public static ConcurrentLinkedQueue<ApiMessage> messages = new ConcurrentLinkedQueue();
@SubscribeEvent @SubscribeEvent
fun onServerUpdate(event: TickEvent.ServerTickEvent) { fun onServerUpdate(event: TickEvent.ServerTickEvent) {
if(MessageHandler.rcvQueue.isNotEmpty()) if(MessageHandler.rcvQueue.isNotEmpty())
CivilEngineering.logger!!.info("incoming: " + MessageHandler.rcvQueue.toString()) CivilEngineering.logger.info("incoming: " + MessageHandler.rcvQueue.toString())
val nextMessage = MessageHandler.rcvQueue.poll() val nextMessage = MessageHandler.rcvQueue.poll()
if (nextMessage != null) { if (nextMessage != null) {

View File

@ -40,9 +40,9 @@ class BridgeCommand : CommandBase() {
val cmd = args[0].toLowerCase() val cmd = args[0].toLowerCase()
when (cmd) { when (cmd) {
"connect" -> if (MessageHandler.start()) { "connect" -> if (MessageHandler.start()) {
logger!!.info("connected to matterbridge") logger.info("connected to matterbridge")
} else { } else {
logger!!.error("connection to matterbridge failed") logger.error("connection to matterbridge failed")
} }
"disconnect" -> MessageHandler.stop() "disconnect" -> MessageHandler.stop()
} }