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,186 +2,91 @@ 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) { private fun createThread(): CancellableConnectionFollowThread {
CivilEngineering.logger!!.info("Connection closed.") return CancellableConnectionFollowThread(
} else if (e is IOException) { {
CivilEngineering.logger!!.error("Error connecting to bridge server!") CivilEngineering.logger.info("Connecting to bridge server @ " + Config.connectURL)
CivilEngineering.logger!!.error(e.message) 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<ApiMessage>()
var rcvQueue = ConcurrentLinkedQueue<ApiMessage>()
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) @Throws(IOException::class)
private fun transmitFromQueue() { private fun transmitMessage(message: ApiMessage) {
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 //open a connection
val url = URL(Config.connectURL + "/api/messages") val url = URL(Config.connectURL + "/api/message")
val con = url.openConnection() as HttpURLConnection val urlConnection = url.openConnection()
val connection = urlConnection as HttpURLConnection
//configure the connection //configure the connection
con.allowUserInteraction = false connection.allowUserInteraction = false
con.instanceFollowRedirects = true connection.instanceFollowRedirects = true
connection.setRequestProperty("Content-Type", "application/json")
connection.requestMethod = "POST"
if (Config.authToken.isNotEmpty()) { if (Config.authToken.isNotEmpty()) {
con.setRequestProperty("Authorization", "Bearer " + Config.authToken) connection.setRequestProperty("Authorization", "Bearer " + Config.authToken)
} }
//read the messages //encode the ApiMessage for sending
val input = BufferedReader(InputStreamReader(con.inputStream)) val json = message.encode()
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 //send the message
if (messages.isNotEmpty()) for (msg in messages) rcvQueue.add(msg) connection.doOutput = true
} val post = DataOutputStream(connection.outputStream)
post.writeBytes(json)
post.flush()
post.close()
companion object { if (connection.responseCode != 200) {
CivilEngineering.logger.error("Server returned " + connection.responseCode)
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<ApiMessage>()
var rcvQueue = ConcurrentLinkedQueue<ApiMessage>()
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)
}
} }
} }
} }

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()
} }