Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.49 KB | None | 0 0
  1. package nl.reader.csv;
  2.  
  3. import java.io.BufferedOutputStream;
  4. import java.io.BufferedReader;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10. import java.io.OutputStream;
  11. import java.io.PrintWriter;
  12. import java.net.ServerSocket;
  13. import java.net.Socket;
  14. import java.util.Date;
  15. import java.util.StringTokenizer;
  16.  
  17. import nl.valori.stubstore.customer.edsn.CKIdentification;
  18.  
  19.  
  20. // The tutorial can be found just here on the SSaurel's Blog :
  21. // https://www.ssaurel.com/blog/create-a-simple-http-web-server-in-java
  22. // Each Client Connection will be managed in a dedicated Thread
  23.  
  24. public class JavaHTTPServer implements Runnable{
  25.  
  26. //public ReadXML getXML = new ReadXML();
  27. static final String StubStore = System.getenv("StubStore");
  28. static final File WEB_ROOT = new File(StubStore +"stubstore/Templates");
  29. static final String DEFAULT_FILE = "/Output/index.html";
  30. static final String XML_FILE = "/Output/index.xml";
  31. static final String FILE_NOT_FOUND = "/Output/404.html";
  32. static final String METHOD_NOT_SUPPORTED = "/Output/not_supported.html";
  33. static final String METHOD_COMING_SOON = "/Output/coming_soon.html";
  34. static final String EDSN = "EDSN/CAR/CKIdentification.xml";
  35. // port to listen connection
  36. private static final int PORT = 8082;
  37.  
  38. // verbose mode
  39. private static final boolean verbose = true;
  40.  
  41. // Client Connection via Socket Class
  42. private Socket connect;
  43.  
  44. /**
  45. * ServerSocket object. Manages client connections.
  46. * @param c is the name of the socket
  47. */
  48. private JavaHTTPServer(Socket c) {
  49. connect = c;
  50. }
  51.  
  52. /**
  53. * Method that listens on port until server halts server execution. When a connection is created,
  54. * the Socket object is passed in the parameter of our javaHTTPServer class and then start
  55. * a dedicated Thread object
  56. * @param args
  57. */
  58. public static void main(String[] args) {
  59. try {
  60. ServerSocket serverConnect = new ServerSocket(PORT);
  61. System.out.println("Server started.\nListening for connections on port : " + PORT + " ...\n");
  62.  
  63. while (true) {
  64. JavaHTTPServer myServer = new JavaHTTPServer(serverConnect.accept());
  65.  
  66. if (verbose) {
  67. System.out.println("Connection opened. (" + new Date() + ")");
  68. }
  69.  
  70. Thread thread = new Thread(myServer);
  71. thread.start();
  72. }
  73.  
  74. } catch (IOException e) {
  75. System.err.println("Server Connection error : " + e.getMessage());
  76. }
  77. }
  78.  
  79. /**
  80. * For each Thread instance created, this method reads characters from the client via the getInputStream method
  81. * of the Socket instance. Then gets one character output stream to client for headers.
  82. * It also gets a binary output stream to client for requested data.
  83. * Only GET and HEAD methods are supported, else 'not implemented' file gets sent
  84. * connection finally gets closed
  85. */
  86. @Override
  87. public void run() {
  88. BufferedReader in = null; PrintWriter out = null; BufferedOutputStream dataOut = null;
  89. String fileRequested = null;
  90.  
  91. try {
  92. in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
  93. out = new PrintWriter(connect.getOutputStream());
  94. dataOut = new BufferedOutputStream(connect.getOutputStream());
  95.  
  96. String input = in.readLine();
  97. StringTokenizer parse = new StringTokenizer(input);
  98. String method = parse.nextToken().toUpperCase();
  99. fileRequested = parse.nextToken().toLowerCase();
  100. String payLoad = null;
  101.  
  102. // we support only GET and HEAD methods, we check
  103. if (!method.equals("GET") && !method.equals("HEAD")) {
  104. if (verbose) {
  105. System.out.println("501 Not Implemented : " + method + " method.");
  106. }
  107. if(method.equals("POST")) {
  108.  
  109. File file = new File(WEB_ROOT, METHOD_COMING_SOON);
  110. int fileLength = (int) file.length();
  111. String contentMimeType = "text/html";
  112. byte[] fileData = readFileData(file, fileLength);
  113.  
  114. out.println("HTTP/1.1 501 Not Implemented");
  115. out.println("Server: Java HTTP Server from SSaurel : 1.0");
  116. out.println("Date: " + new Date());
  117. out.println("Content-type: " + contentMimeType);
  118. out.println("Content-length: " + fileLength);
  119. out.println(); // blank line between headers and content, very important !
  120. out.flush(); // flush character output stream buffer file
  121. dataOut.write(fileData, 0, fileLength);
  122. dataOut.flush();
  123. } else {
  124.  
  125. // we return the not supported file to the client
  126. File file = new File(WEB_ROOT, METHOD_NOT_SUPPORTED);
  127. int fileLength = (int) file.length();
  128. String contentMimeType = "text/html";
  129. //read content to return to client
  130. byte[] fileData = readFileData(file, fileLength);
  131.  
  132. // we send HTTP Headers with data to client
  133. out.println("HTTP/1.1 501 Not Implemented");
  134. out.println("Server: Java HTTP Server from SSaurel : 1.0");
  135. out.println("Date: " + new Date());
  136. out.println("Content-type: " + contentMimeType);
  137. out.println("Content-length: " + fileLength);
  138. out.println(); // blank line between headers and content, very important !
  139. out.flush(); // flush character output stream buffer
  140. // file
  141. dataOut.write(fileData, 0, fileLength);
  142. dataOut.flush();
  143. }
  144. } else {
  145.  
  146. String client;
  147. String urlSplit[] = fileRequested.split("/");
  148. if (fileRequested.endsWith("/")) {
  149. client = "default";
  150. }else {
  151. client = urlSplit[1];
  152. }
  153.  
  154. switch (client) {
  155.  
  156. case "default" :
  157. fileRequested += DEFAULT_FILE;
  158. break;
  159. case "user":
  160. payLoad= ReadXML.getUser(urlSplit[2]);
  161. fileRequested = XML_FILE;
  162. break;
  163. case "edsn":
  164. payLoad= CKIdentification.getCKId();
  165. System.out.println(payLoad);
  166. fileRequested = EDSN;
  167. break;
  168. }
  169.  
  170. File file = new File(WEB_ROOT, fileRequested);
  171. int fileLength = (int) file.length();
  172. String content = null;
  173. if(getContentType(fileRequested)== "text/plain") {
  174. content = "text/xml";
  175. }else {
  176. content = getContentType(fileRequested);
  177. }
  178. if (method.equals("GET")) { // GET method so we return content
  179. byte[] fileData = readFileData(file, fileLength);
  180.  
  181. // send HTTP Headers
  182. out.println("HTTP/1.1 200 OK");
  183. out.println("Server: Java HTTP Server from SSaurel : 1.0");
  184. out.println("Date: " + new Date());
  185. out.println("Content-type: " + content);
  186. out.println("Content-length: " + fileLength);
  187. out.println(); // blank line between headers and content, very important !
  188.  
  189. out.println(payLoad);
  190. out.flush(); // flush character output stream buffer
  191. //dataOut.write(fileData, 0, fileLength);
  192. //dataOut.flush();
  193. }
  194.  
  195. if (verbose) {
  196. System.out.println("File " + fileRequested + " of type " + content + " returned");
  197. }
  198.  
  199. }
  200.  
  201. } catch (FileNotFoundException fnfe) {
  202. try {
  203. fileNotFound(out, dataOut, fileRequested);
  204. } catch (IOException ioe) {
  205. System.err.println("Error with file not found exception : " + ioe.getMessage());
  206. }
  207.  
  208. } catch (IOException ioe) {
  209. System.err.println("Server error : " + ioe);
  210. } finally {
  211. try {
  212. in.close();
  213. out.close();
  214. dataOut.close();
  215. connect.close(); // we close socket connection
  216. } catch (Exception e) {
  217. System.err.println("Error closing stream : " + e.getMessage());
  218. }
  219.  
  220. if (verbose) {
  221. System.out.println("Connection closed.\n");
  222. }
  223. }
  224.  
  225.  
  226. }
  227.  
  228. /**
  229. *
  230. * @param file file that's being returned
  231. * @param fileLength length of the file being returned
  232. * @return returns the fileData
  233. * @throws IOException
  234. */
  235. private byte[] readFileData(File file, int fileLength) throws IOException {
  236. FileInputStream fileIn = null;
  237. byte[] fileData = new byte[fileLength];
  238.  
  239. try {
  240. fileIn = new FileInputStream(file);
  241. fileIn.read(fileData);
  242. } finally {
  243. if (fileIn != null)
  244. fileIn.close();
  245. }
  246.  
  247. return fileData;
  248. }
  249.  
  250. /**
  251. * Returns the supported MIME type
  252. * @param fileRequested the file that needs to be checked for MIME type
  253. * @return MIME type corresponding with fileRequested
  254. */
  255. private String getContentType(String fileRequested) {
  256. if (fileRequested.endsWith(".htm") || fileRequested.endsWith(".html"))
  257. return "text/html";
  258. else
  259. return "text/plain";
  260. }
  261.  
  262. /**
  263. * Method that gets called when the file is not found
  264. * @param out print writer to print to console
  265. * @param dataOut the outputstream that gets written to the file
  266. * @param fileRequested the requested file, to print out in message when it's not found
  267. * @throws IOException
  268. */
  269. private void fileNotFound(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
  270. File file = new File(WEB_ROOT, FILE_NOT_FOUND);
  271. //File file = new File("index.html");
  272. int fileLength = (int) file.length();
  273. String content = "text/html";
  274. byte[] fileData = readFileData(file, fileLength);
  275.  
  276. out.println("HTTP/1.1 404 File Not Found");
  277. out.println("Server: Java HTTP Server from SSaurel : 1.0");
  278. out.println("Date: " + new Date());
  279. out.println("Content-type: " + content);
  280. out.println("Content-length: " + fileLength);
  281. out.println(); // blank line between headers and content, very important !
  282. out.flush(); // flush character output stream buffer
  283.  
  284. dataOut.write(fileData, 0, fileLength);
  285. dataOut.flush();
  286.  
  287. if (verbose) {
  288. System.out.println("File " + fileRequested + " not found");
  289. }
  290. }
  291. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement