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

View File

@ -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

View File

@ -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<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)
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>
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<ApiMessage>::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<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)
}
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
object ServerChatHelper {
//public static ConcurrentLinkedQueue<ApiMessage> 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) {

View File

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