1
1
package com .ufscar .psor ;
2
2
3
- import java .io .File ;
4
- import java .io .FileInputStream ;
5
3
import java .io .IOException ;
6
4
import java .io .InputStream ;
7
5
import java .io .OutputStream ;
@@ -13,7 +11,6 @@ public class Main {
13
11
private static final int PORT = 8080 ;
14
12
private static final String PROXY_ADRESS = "localhost" ;
15
13
private static final int PROXY_PORT = 8081 ;
16
- private static final String ROOT = "reverse-proxy-file-server/public" ; // diretorio base para os arquivos
17
14
private static final String INDEX = "index.html" ; // nome do arquivo
18
15
19
16
public static void main (String [] args ) {
@@ -60,16 +57,15 @@ public static void handleRequest(Socket clientSocket) throws IOException {
60
57
requestedFile = "/" + INDEX ;
61
58
}
62
59
63
- // caminho do arquivo solicitado parseado
64
- File file = new File (ROOT + requestedFile );
60
+ InputStream fileStream = Main .class .getClassLoader ().getResourceAsStream (requestedFile .substring (1 ));
65
61
66
62
//debug
67
63
//System.out.println("arquivo solicitado: " + file.getAbsolutePath());
68
64
69
65
if (requestedFile .equals ("/proxy" )) {
70
66
handleProxyRequest (request , outputStream );
71
- } else if (file . exists () && ! file . isDirectory () ) {
72
- handleLocalRequest (file , outputStream );
67
+ } else if (fileStream != null ) {
68
+ handleLocalRequest (fileStream , outputStream );
73
69
} else {
74
70
String notFound = "HTTP/1.1 404 Not Found\r \n \r \n <h1>404 File Not Found locally</h1>" ;
75
71
outputStream .write (notFound .getBytes ());
@@ -81,19 +77,15 @@ public static void handleRequest(Socket clientSocket) throws IOException {
81
77
}
82
78
}
83
79
84
- public static void handleLocalRequest (File file , OutputStream outputStream ) throws IOException {
80
+ public static void handleLocalRequest (InputStream fileStream , OutputStream outputStream ) throws IOException {
85
81
86
82
outputStream .write ("HTTP/1.1 200 OK\r \n " .getBytes ());
87
83
outputStream .write ("Content-Type: text/html\r \n \r \n " .getBytes ());
88
84
89
- try (FileInputStream fileInputStream = new FileInputStream (file )) {
90
- byte [] buffer = new byte [2048 ];
91
- int bytesRead ;
92
- while ((bytesRead = fileInputStream .read (buffer )) != -1 ) {
93
- outputStream .write (buffer , 0 , bytesRead );
94
- }
95
- } catch (IOException e ) {
96
- e .printStackTrace (System .out );
85
+ byte [] buffer = new byte [2048 ];
86
+ int bytesRead ;
87
+ while ((bytesRead = fileStream .read (buffer )) != -1 ) {
88
+ outputStream .write (buffer , 0 , bytesRead );
97
89
}
98
90
}
99
91
0 commit comments