/
sharp1024
/
homework7
Обзор
Документация
Войти
/
sharp1024
/
homework7
Код
Запросы
1
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
feature/homework7
src/main/java/sbp/server/RequestHandler.java
157 строк
5 KB
Single
homework7
08 янв 2026, 21:51
08 янв 2026, 21:51
23d4636
Код
Авторство
О чём код?
package sbp.server; import com.google.gson.Gson; import sbp.crud.Person; import sbp.crud.PersonRepository; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.List; public class RequestHandler implements Runnable { private final Socket clientSocket; private final PersonRepository personRepository; private final Gson gson; public RequestHandler(Socket clientSocket) { this.clientSocket = clientSocket; this.personRepository = new PersonRepository(); this.gson = new Gson(); try { personRepository.createTable(); } catch (SQLException e) { throw new RuntimeException(e); } } private String handleRequest(String action, String request) { StringBuilder result = new StringBuilder(); switch (action) { case "ping": { result.append("Sucess!"); break; } case "add" : { try { Person person = gson.fromJson(request, Person.class); String name = person.getName(); String city = person.getCity(); int age = person.getAge(); personRepository.create(name, city, age); result.append("Saved: "+name); } catch (Exception e) { return "Error while adding: " + e.getMessage(); } break; } case "delete" : { try { Person person = gson.fromJson(request, Person.class); String name = person.getName(); int recId = personRepository.findIdByName(name); if (recId != -1) { personRepository.deleteById(recId); result.append("Deleted: "+name); } else { result.append("Error not found: " + name); } } catch (Exception e) { return "Error while deletind: " + e.getMessage(); } break; } case "list": try { List<Person> persons = personRepository.findAll(); for (Person p : persons) { result.append(p.toString()).append("\n"); } if (persons.isEmpty()) result.append("<empty>"); } catch (SQLException e) { throw new RuntimeException(e); } break; default: result.append("Unsupported action: " + action); } return result.toString(); } private void sendResponse(PrintWriter printWriter, int statusCode, String body) { printWriter.println("HTTP/1.1 " + statusCode + " OK"); printWriter.println("Content-Type: text/plain; charset=UTF-8"); if (body != null && !body.isEmpty()) { printWriter.println("Content-Length: " + body.getBytes(StandardCharsets.UTF_8).length); printWriter.println(); printWriter.println(body); } printWriter.flush(); } @Override public void run() { try ( PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); ) { String requestLine = in.readLine(); if (requestLine == null || requestLine.isEmpty()) { return; } String[] parts = requestLine.split(" "); if (parts.length < 2) { sendResponse(out, 400, "Bad Request"); return; } String action = parts[0]; int contentLength = 0; while ((requestLine = in.readLine()) != null && !requestLine.isEmpty()) { if (requestLine.startsWith("Content-Length:")) { try { contentLength = Integer.parseInt(requestLine.substring("Content-Length:".length()).trim()); } catch (NumberFormatException e) { System.out.print("Invalid content length"); } } } String requestBody = ""; if (contentLength > 0) { char[] bodyChars = new char[contentLength]; int bytesRead = 0; while (bytesRead < contentLength) { int result = in.read(bodyChars, bytesRead, contentLength - bytesRead); if (result == -1) break; bytesRead += result; } requestBody = new String(bodyChars, 0, bytesRead); } String responseBody = handleRequest(action, requestBody); sendResponse(out, 200, responseBody); } catch (IOException e) { System.out.println("RequestHandler error: " + e); } finally { try { clientSocket.close(); } catch (IOException e) { System.out.println("ClientSocket closing error: " + e.getMessage()); } } } }