Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Grapes([
- @Grab("io.undertow:undertow-core:2.0.0.Alpha1"),
- @Grab("org.apache.commons:commons-dbcp2:2.1.1"),
- @Grab("org.postgresql:postgresql:9.3-1102-jdbc41"),
- @GrabConfig(systemClassLoader=true)
- ])
- import io.undertow.Undertow
- import io.undertow.server.HttpHandler
- import io.undertow.server.HttpServerExchange
- import io.undertow.util.Headers
- import org.apache.commons.dbcp2.BasicDataSourceFactory
- import groovy.sql.Sql
- class App implements HttpHandler {
- Sql sql
- def tableName
- def run() {
- initDataSource()
- tableName = sql.expand(env("TABLE_NAME", "short_urls"))
- runServer()
- }
- def initDataSource() {
- println "Initializing DB connection pool..."
- Class.forName("org.postgresql.Driver")
- def dbProperties = new Properties([
- driverClassName: "org.postgresql.Driver",
- url: "jdbc:postgresql://${env("PG_PATH")}" as String,
- username: env("PG_USERNAME"),
- password: env("PG_PASSWORD"),
- ])
- println dbProperties
- def dataSource = BasicDataSourceFactory.createDataSource(dbProperties)
- sql = new Sql(dataSource)
- }
- def runServer() {
- println "Running web server..."
- def port = env("SERVER_PORT", "8080") as Integer
- def host = env("SERVER_HOST", "localhost")
- Undertow.builder()
- .addHttpListener(port, host)
- .setHandler(this).build().start()
- }
- @Override
- void handleRequest(HttpServerExchange exchange) throws Exception {
- def url = exchange.queryParameters?.get("url")?.first
- if (!url) {
- exchange.responseSender.send("Please specify `url` parameter in the query string")
- exchange.statusCode = 400
- return
- }
- def response = "Method $exchange.requestMethod is not supported"
- switch (exchange.requestMethod as String) {
- case "GET":
- response = readFull(url) ?: "NO_FULL_URL"
- break;
- case "POST":
- response = createFull(url)
- break
- default:
- exchange.statusCode = 400
- }
- exchange.responseHeaders.put(Headers.CONTENT_TYPE, "text/plain")
- exchange.responseSender.send(response as String)
- }
- def readFull(shortLink) {
- def id = Long.parseLong(shortLink, Character.MAX_RADIX)
- def result = sql.firstRow("SELECT url FROM $tableName WHERE id=$id AND NOW() < expires_on LIMIT 1")
- result?.url
- }
- def createFull(shortLink) {
- def id = sql.firstRow("""
- UPDATE $tableName SET url=$shortLink, expires_on=DEFAULT
- FROM(SELECT id FROM $tableName WHERE NOW() > expires_on LIMIT 1 FOR UPDATE) expired
- WHERE ${tableName}.id = expired.id
- RETURNING ${tableName}.id""")?.id
- id = id?: sql.firstRow("INSERT INTO $tableName(url) VALUES ($shortLink) RETURNING id").id
- Long.toString(id, Character.MAX_RADIX)
- }
- def env(varname, defaultValue = null) {
- System.getenv(varname) ?: System.getProperty(varname) ?: defaultValue
- }
- }
- new App().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement