Created
January 30, 2013 23:59
-
-
Save jcheype/4678559 to your computer and use it in GitHub Desktop.
restsimple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.jcheype.codeStory | |
import scala.util.DynamicVariable | |
import com.jcheype.webServer._ | |
import org.scalatra._ | |
import org.jboss.netty.bootstrap.ServerBootstrap | |
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory | |
import java.util.concurrent.Executors | |
import com.jcheype.webServer.Route | |
import java.net.InetSocketAddress | |
/** | |
* Created with IntelliJ IDEA. | |
* User: juliencheype | |
* Date: 31/5/13 | |
* Time: 00:47 | |
* To change this template use File | Settings | File Templates. | |
*/ | |
object RestSimple { | |
val restHandler = new SimpleRestHandler | |
def start(port:Int) { | |
val bootstrap = new ServerBootstrap( | |
new NioServerSocketChannelFactory( | |
Executors.newCachedThreadPool(), | |
Executors.newCachedThreadPool())) | |
val delfaultChannelHandler = new HttpApiServerHandler(RestSimple.restHandler) | |
bootstrap.setPipelineFactory(new WebServerPipelinefactory(delfaultChannelHandler)) | |
val channel = bootstrap.bind(new InetSocketAddress(port)) | |
} | |
} | |
class RestSimple { | |
protected val _request = new DynamicVariable[Request](null) | |
protected val _response = new DynamicVariable[Response](null) | |
def request: Request = { | |
_request.value | |
} | |
def response: Response = { | |
_response.value | |
} | |
def get(routeString: String)(action: => Any) { | |
addRoute(Get, routeString, action) | |
} | |
def post(routeString: String)(action: => Any) { | |
addRoute(Post, routeString, action) | |
} | |
def put(routeString: String)(action: => Any) { | |
addRoute(Put, routeString, action) | |
} | |
def delete(routeString: String)(action: => Any) { | |
addRoute(Delete, routeString, action) | |
} | |
def addRoute(method: HttpMethod, routeString: String, action: => Any) { | |
val route = new Route(routeString) { | |
override def handle(requestJ: Request, responseJ: Response, _map: java.util.Map[String, String]) { | |
_request.withValue(requestJ) { | |
_response.withValue(responseJ) { | |
action | |
} | |
} | |
} | |
} | |
method match { | |
case Get => RestSimple.restHandler.get(route) | |
case Post => RestSimple.restHandler.post(route) | |
case Put => RestSimple.restHandler.put(route) | |
case Delete => RestSimple.restHandler.delete(route) | |
case _ => throw new UnsupportedOperationException | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment