package dev.peerat.framework; import java.net.Socket; import dev.peerat.framework.auth.AuthException; public class Client extends Thread{ private HttpReader reader; private HttpWriter writer; private Router router; public Client(Socket socket, Router router) throws Exception{ this.reader = new HttpReader(socket); this.writer = new HttpWriter(socket); this.router = router; } @Override public void run(){ Context context = null; try{ String[] headers = reader.readLine().split("\\s"); reader.readHeaders(); RequestType type = RequestType.valueOf(headers[0]); context = new Context(type, headers[1], isLogin(type, reader), writer, router.getDefaultHeaders(type)); router.exec(context, reader, writer); writer.flush(); writer.close(); }catch(AuthException e){ this.router.getExceptionLogger().setValue(e); }catch(Throwable e){ this.router.getExceptionLogger().setValue(e); if(context != null && context.getResponseCode() == 0){ try{ context.response(500); writer.flush(); writer.close(); }catch(Exception ex){ this.router.getExceptionLogger().setValue(ex); } } } if(context != null) router.getLogger().setValue(context); } private User isLogin(RequestType type, HttpReader reader) throws AuthException{ try{ return this.router.getUser(type, reader); }catch(Exception e){ try{ writer.response(401, this.router.getDefaultHeaders(type)); writer.flush(); writer.close(); }catch(Exception ex){ this.router.getExceptionLogger().setValue(ex); } throw new AuthException(e); } } }