Advertisement
Guest User

Parsing HTTP Requests

a guest
Jan 23rd, 2019
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.33 KB | None | 0 0
  1. package _01ParsingHTTPRequests;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.nio.charset.StandardCharsets;
  7. import java.util.*;
  8. import java.util.stream.Collectors;
  9.  
  10. /**
  11.  * Created by IntelliJ IDEA.
  12.  * User: LAPD
  13.  * Date: 23.1.2019 г.
  14.  * Time: 16:41 ч.
  15.  */
  16. public class _01ParsingHTTPRequests {
  17.     public static void main(String[] args) throws IOException {
  18.  
  19.         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
  20.  
  21.         String[] urls = bufferedReader.readLine()
  22.                 .split("\\s+");
  23.  
  24.         String[] requestLineData = bufferedReader.readLine()
  25.                 .split("\\s+");
  26.  
  27.         Map<String, String> headersParams = parseHeadersParams(bufferedReader);
  28.  
  29.         String bodyParams = parseBodyParams(bufferedReader);
  30.  
  31.         String response = constructResponse(urls, requestLineData, headersParams, bodyParams);
  32.  
  33.         System.out.println(response);
  34.     }
  35.  
  36.     private static String constructResponse(String[] urls,
  37.                                             String[] requestLineData,
  38.                                             Map<String, String> headersParams,
  39.                                             String bodyParams) {
  40.         StringBuilder response = new StringBuilder();
  41.  
  42.         String requestMethod = requestLineData[0];
  43.         String url = requestLineData[1];
  44.         String httpVersion = requestLineData[2];
  45.  
  46.         String authResponse = getAuthResponse(headersParams);
  47.  
  48.         if (!Arrays.asList(urls).contains(url)) {
  49.  
  50.             response.append(httpVersion)
  51.                     .append(" ")
  52.                     .append("404 Not Found");
  53.             appendResponseHeaders(headersParams, response);
  54.             response.append("The requested functionality was not found.");
  55.  
  56.         } else if (authResponse.isEmpty()) {
  57.  
  58.             response.append(httpVersion)
  59.                     .append(" ")
  60.                     .append("401 Unauthorized");
  61.             appendResponseHeaders(headersParams, response);
  62.             response.append("You are not authorized to access the requested functionality.");
  63.  
  64.         } else if ("POST".equals(requestMethod)) {
  65.  
  66.             if (bodyParams.isEmpty()) {
  67.  
  68.                 response.append(httpVersion)
  69.                         .append(" ")
  70.                         .append("400 Bad Request");
  71.                 appendResponseHeaders(headersParams, response);
  72.                 response.append("There was an error with the requested functionality due to malformed request.");
  73.  
  74.             } else {
  75.  
  76.                 response.append(httpVersion)
  77.                         .append(" ")
  78.                         .append("200 OK");
  79.                 appendResponseHeaders(headersParams, response);
  80.                 response.append(authResponse)
  81.                         .append(" ")
  82.                         .append(bodyParams);
  83.             }
  84.  
  85.         } else if ("GET".equals(requestMethod)) {
  86.  
  87.             response.append(httpVersion)
  88.                     .append(" ")
  89.                     .append("200 OK");
  90.             appendResponseHeaders(headersParams, response);
  91.             response.append(authResponse);
  92.         }
  93.  
  94.         return response.toString();
  95.     }
  96.  
  97.     private static String getAuthResponse(Map<String, String> headersParams) {
  98.  
  99.         String authResponse = "";
  100.  
  101.         String authHeader = headersParams.get("Authorization");
  102.  
  103.         if (authHeader != null) {
  104.             String user = new String(Base64.getDecoder()
  105.                     .decode(authHeader
  106.                             .replace("Basic ",
  107.                                     "")),
  108.                     StandardCharsets.UTF_8);
  109.  
  110.             authResponse = String.format("Greetings %s!",
  111.                     user);
  112.         }
  113.  
  114.         return authResponse;
  115.     }
  116.  
  117.     private static void appendResponseHeaders(Map<String, String> headersParams,
  118.                                               StringBuilder response) {
  119.         response.append(System.lineSeparator())
  120.                 .append(headersParams.entrySet()
  121.                         .stream()
  122.                         .filter(k -> !k.getKey().equals("Authorization"))
  123.                         .map(kv -> String.format("%s: %s",
  124.                                 kv.getKey(), kv.getValue()))
  125.                         .collect(Collectors.joining(System.lineSeparator())))
  126.                 .append(System.lineSeparator())
  127.                 .append(System.lineSeparator());
  128.     }
  129.  
  130.     private static String parseBodyParams(BufferedReader bufferedReader) throws IOException {
  131.  
  132.         StringBuilder bodyParams = new StringBuilder();
  133.  
  134.         String input = bufferedReader.readLine();
  135.  
  136.         if ("".equals(input) || input == null) {
  137.             return bodyParams.toString();
  138.         }
  139.  
  140.         String[] bodyLine = input.split("[=&]");
  141.  
  142.         bodyParams.append(String
  143.                 .format("You have successfully created %s with ",
  144.                         bodyLine[1]));
  145.  
  146.         for (int i = 2; i < bodyLine.length - 1; i += 2) {
  147.             bodyParams.append(String.format("%s - %s, ",
  148.                     bodyLine[i], bodyLine[i + 1]));
  149.         }
  150.  
  151.         bodyParams.replace(bodyParams.length() - 2,
  152.                 bodyParams.length(), ".");
  153.  
  154.         return bodyParams.toString();
  155.     }
  156.  
  157.     private static Map<String, String> parseHeadersParams(BufferedReader bufferedReader) throws IOException {
  158.         Map<String, String> headersParams = new LinkedHashMap<>();
  159.  
  160.         String input;
  161.         while (true) {
  162.             if ("".equals(input = bufferedReader.readLine())
  163.                     || input == null) {
  164.                 break;
  165.             }
  166.  
  167.             String[] headerLine = input.split(":\\s+");
  168.  
  169.             switch (headerLine[0]) {
  170.                 case "Date":
  171.                     headersParams.put("Date", headerLine[1]);
  172.                     break;
  173.                 case "Host":
  174.                     headersParams.put("Host", headerLine[1]);
  175.                     break;
  176.                 case "Content-Type":
  177.                     headersParams.put("Content-Type", headerLine[1]);
  178.                     break;
  179.                 case "Authorization":
  180.                     headersParams.put("Authorization", headerLine[1]);
  181.                     break;
  182.             }
  183.         }
  184.  
  185.         return headersParams;
  186.     }
  187. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement