package code; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.json.JSONException; import org.json.JSONObject; import com.sun.net.httpserver.HttpExchange; public class Helper { public static void sendResponse(String response, HttpExchange exchange) throws IOException { System.out.println(response); exchange.sendResponseHeaders(200, response.getBytes().length); OutputStream os = exchange.getResponseBody(); os.write(response.getBytes()); os.close(); } public static void badRequest(HttpExchange exchange) throws IOException { System.out.println("Errors in the request!"); // exchange.getResponseHeaders().remove("content-type"); String response = "{\"message\":\"Errors in the request!\"}"; exchange.sendResponseHeaders(400, response.getBytes().length); OutputStream os = exchange.getResponseBody(); os.write(response.getBytes()); os.close(); } public static void pageNotFound(HttpExchange exchange) throws IOException { System.out.println("Page not found!"); // exchange.getResponseHeaders().remove("content-type"); String response = "{\"message\":\"Page not found!\"}"; exchange.sendResponseHeaders(404, response.getBytes().length); OutputStream os = exchange.getResponseBody(); os.write(response.getBytes()); os.close(); } public static void methodNotAllowed(HttpExchange exchange) throws IOException { System.out.println("Method not allowed!"); // exchange.getResponseHeaders().remove("content-type"); String response = "{\"message\":\"Method not allowed!\"}"; exchange.sendResponseHeaders(405, response.getBytes().length); OutputStream os = exchange.getResponseBody(); os.write(response.getBytes()); os.close(); } public static boolean compareText(String a, String b){ return a.compareToIgnoreCase(b) == 0; } public static String readBody(InputStream requestBody) { int req; StringBuffer sb = new StringBuffer(); try { while((req = requestBody.read()) != -1) sb.append(Character.toString((char)req)); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } public static boolean checkJSON(String body) { try { new JSONObject(body); return true; } catch (JSONException e) { return false; } } }