1717public class Server {
1818 private static final Logger logger = Logger .getLogger (Server .class .getName ());
1919 private static final Encoder encoder = new Encoder ();
20+ private static final NotADataBase nDb = new NotADataBase ();
2021 private static final AtomicLong counter = new AtomicLong (0 );
2122
2223 public static void main (String [] args ) {
@@ -81,13 +82,29 @@ private static void handleRequest(Socket clientSocket) {
8182 break ;
8283 }
8384
84- // TODO: Perform a validation if URL is already shortened before increementing
85- long counterValue = counter .incrementAndGet ();
86- String shortenedUrl = encoder .encode (counterValue );
87- responseBody .put ("shortedUrl" , shortenedUrl );
88- response = createResponse (200 , "OK" , stringifyJson (responseBody ));
85+ try {
86+ long counterValue = counter .incrementAndGet ();
87+ String shortenedUrl = encoder .encode (counterValue );
88+ nDb .write (shortenedUrl , urlPath );
89+ responseBody .put ("shortedUrl" , shortenedUrl );
90+ response = createResponse (200 , "OK" , stringifyJson (responseBody ));
91+ } catch (IOException e ) {
92+ response = createResponse (500 , "Failed to persist url" , "" );
93+ }
94+ break ;
95+ }
96+ case "GET" :
97+ String url = path .split ("/" )[1 ];
98+ String result = nDb .query (url );
99+ if (result == null ) {
100+ response = createResponse (400 , "Invalid URL" , "" );
89101 break ;
90102 }
103+
104+ logger .info ("Retrieved result is NOT null: " + result );
105+ responseBody .put ("result" , result );
106+ response = createResponse (200 , "OK" , stringifyJson (responseBody ));
107+ break ;
91108 default :
92109 responseBody .put ("errorMessage" , "Invalid request" );
93110 response = createResponse (400 , "Bad Request" , stringifyJson (responseBody ));
@@ -110,13 +127,15 @@ private static void handleRequest(Socket clientSocket) {
110127 private final class Constants {
111128 public static int CORE_POOL_SIZE = 10 ;
112129 public static int MAX_POOL_SIZE = 10 ;
113- public static long KEEP_ALIVE_TIME = 300 ;
130+ public static long KEEP_ALIVE_TIME = 1000 ;
114131 public static int QUEUE_SIZE = 10 ;
115132 }
116133
117134 private static String createResponse (int statusCode , String message , String body ) {
135+ int contentLength = body .getBytes (StandardCharsets .UTF_8 ).length ;
118136 return "HTTP/1.1 " + statusCode + " " + message + "\n " +
119137 "Content-Type: application/json\n " +
138+ "Content-Length: " + contentLength + "\n " +
120139 "\n " + body ;
121140 }
122141
0 commit comments