Skip to content

Instantly share code, notes, and snippets.

@mitsuji
Created September 30, 2010 01:40
Show Gist options
  • Save mitsuji/603884 to your computer and use it in GitHub Desktop.
Save mitsuji/603884 to your computer and use it in GitHub Desktop.
package org.mitsuji
import java.net._
import java.io._
import java.util.Date
import java.util.concurrent._
object FlashPolicyServer {
val server = new FlashPolicyServer()
server.port = 843
server.policyFile = "misc\\flashpolicy.xml"
server.poolSize = 7
def start() = server.start()
def stop() = server.stop()
}
/**
* Server
*
*/
class FlashPolicyServer() {
var port:Int = 843
var policyFile:String = ""
var poolSize:Int = 5
def setPort(port:String) = { this.port = port.toInt }
def setPolicyFile(policyFile:String) = { this.policyFile = policyFile }
def setPoolSize(poolSize:String) = { this.poolSize = poolSize.toInt }
var thread:Thread = _
def start() = {
thread = new Thread( Server )
thread.start()
}
def stop() = Server.stop()
def join() = thread.join()
/**
* Server Thread
*
*/
object Server extends Runnable {
private var lsocket:ServerSocket = _
private var pool:ExecutorService = _
private var cacheCreated:Long = 0
private var cache:Array[Byte] =_
override def run() = {
loadCache()
pool = Executors.newFixedThreadPool(poolSize)
lsocket = new ServerSocket(port)
var isRunning = true
while(isRunning) {
try {
val socket = lsocket.accept()
if( new File(policyFile).lastModified() > cacheCreated ) loadCache()
pool.execute( new Response(socket) )
} catch {
case e:SocketException => ( isRunning = false )
}
}
}
def stop() = {
lsocket.close()
pool.shutdown()
}
private def loadCache() = {
cacheCreated = new Date().getTime()
val out = new ByteArrayOutputStream()
val in = new FileInputStream(policyFile)
var len = 0
var buffer = new Array[Byte](1024)
while( in.available() > 0 ) {
len = in.read(buffer)
out.write(buffer, 0, len)
}
in.close()
out.close()
cache = out.toByteArray()
}
/**
* Server Thread
*
*/
class Response(val socket:Socket ) extends Runnable {
override def run() = {
val out = socket.getOutputStream()
val in = new ByteArrayInputStream( cache )
var len = 0
var buffer = new Array[Byte](1024)
while( in.available() > 0 ) {
len = in.read(buffer)
out.write(buffer, 0, len)
}
in.close()
out.close()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment