Skip to content

Commit a89c9f7

Browse files
committed
Add GET request
1 parent 5c53ee3 commit a89c9f7

5 files changed

Lines changed: 106 additions & 8 deletions

File tree

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
*.class
1+
*.class
2+
*.bin

BTree.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ public Optional<String> search(String key) {
6868
i++;
6969
}
7070

71-
if (i < this.keySize && key == this.keys[i].key) {
71+
if (i < this.keySize && key.equals(this.keys[i].key)) {
7272
return Optional.of(this.keys[i].path);
7373
}
7474

FileManager.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.io.RandomAccessFile;
2+
import java.nio.charset.StandardCharsets;
3+
import java.util.logging.Logger;
4+
import java.io.IOException;
5+
6+
public class FileManager {
7+
private static final Logger logger = Logger.getLogger(FileManager.class.getName());
8+
9+
private static final int BLOCK_SIZE = 4096;
10+
11+
public FileManager() {}
12+
13+
public void write(String filePath, String data) throws IOException {
14+
try (RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw")) {
15+
byte[] paddedData = padToBlockSize(data);
16+
randomAccessFile.write(paddedData);
17+
logger.info(String.format("Successfully persisted data to path: %s", filePath));
18+
}
19+
}
20+
21+
public String read(String filePath) throws IOException {
22+
try (RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r")) {
23+
byte[] bytes = new byte[BLOCK_SIZE];
24+
randomAccessFile.read(bytes);
25+
return new String(bytes, StandardCharsets.UTF_8).trim();
26+
}
27+
}
28+
29+
// We pad to block size to ensure each string clearly takes one block.
30+
// Not the most efficient way, you could also store multiple strings within a
31+
// single block and maintain its offset but we are not doing that here.
32+
private static byte[] padToBlockSize(String data) {
33+
byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
34+
if (bytes.length > BLOCK_SIZE) {
35+
throw new RuntimeException(String.format("You shall not proceed, data is too big: %s - %s", bytes, bytes.length));
36+
}
37+
38+
if (bytes.length == BLOCK_SIZE) {
39+
return bytes;
40+
}
41+
42+
byte[] paddedData = new byte[BLOCK_SIZE];
43+
System.arraycopy(bytes, 0, paddedData, 0, bytes.length);
44+
return paddedData;
45+
}
46+
}

NotADataBase.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.io.IOException;
2+
import java.util.Optional;
3+
4+
public class NotADataBase {
5+
private BTree bTree;
6+
private FileManager fileManager;
7+
8+
public NotADataBase() {
9+
// Ideally you can choose the degree of the tree in such a way that each
10+
// tree node nicely fits into block. However, we are storing the tree
11+
// in-memory and not to disk :( Therefore, we don't have to put too much thought
12+
// into degree
13+
bTree = new BTree(50);
14+
fileManager = new FileManager();
15+
}
16+
17+
public String query(String id) throws IOException {
18+
Optional<String> path = bTree.search(id);
19+
if (path.isEmpty()) {
20+
return null;
21+
}
22+
23+
String result = fileManager.read(path.get());
24+
return result;
25+
}
26+
27+
public void write(String id, String data) throws IOException {
28+
String filePath = String.format("%s.bin", id);
29+
bTree.insert(id, filePath);
30+
fileManager.write(filePath, data);
31+
}
32+
}

Server.java

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
public 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

Comments
 (0)