|
| 1 | +package controllers; |
| 2 | + |
| 3 | +import play.Logger; |
| 4 | +import play.Play; |
| 5 | +import play.cache.Cache; |
| 6 | +import play.modules.spring.Spring; |
| 7 | +import play.mvc.Controller; |
| 8 | +import service.api.Counter; |
| 9 | + |
| 10 | +public class Mapper extends Controller { |
| 11 | + |
| 12 | + private static final int INSTANCE_ENCODING_RADIX = 32; |
| 13 | + private static final String KEY_PREFIX = "url-"; |
| 14 | + |
| 15 | + public static void index() { |
| 16 | + // render |
| 17 | + render(); |
| 18 | + } |
| 19 | + |
| 20 | + public static void use(final String id) { |
| 21 | + Logger.info(String.format("Received id: [%s]", id)); |
| 22 | + final Long count = Long.valueOf(id, INSTANCE_ENCODING_RADIX); |
| 23 | + final String key = String.format("%s%s", KEY_PREFIX, count); |
| 24 | + final String url = (String) Cache.get(key); |
| 25 | + if (url == null) { |
| 26 | + flash.error(String.format("No url mapping found for index: [%s]", id)); |
| 27 | + index(); |
| 28 | + } |
| 29 | + redirect(url); |
| 30 | + } |
| 31 | + |
| 32 | + public static void captureUrl(final String url) { |
| 33 | + final Counter counter = (Counter) Spring.getBean("counter"); |
| 34 | + final long count = counter.next(); |
| 35 | + |
| 36 | + // set the mapping in cache |
| 37 | + Cache.set(String.format("%s%s", KEY_PREFIX, count), url); |
| 38 | + |
| 39 | + // create short url |
| 40 | + // TODO: read the base url from configuration once DNS is in place |
| 41 | +// final String baseUrl = (String) Play.configuration.get("application.base.url"); |
| 42 | + final String baseUrl = request.getBase(); |
| 43 | + final String shortened = String.format("%s/%s", |
| 44 | + baseUrl, |
| 45 | + Long.toString(count, INSTANCE_ENCODING_RADIX)); |
| 46 | + |
| 47 | + render(shortened); |
| 48 | + } |
| 49 | +} |
0 commit comments