1 2 24 25 26 27 28 29 package com.lutris.appserver.server.httpPresentation; 30 31 import java.io.ByteArrayOutputStream ; 32 import java.io.ByteArrayInputStream ; 33 import java.io.FileNotFoundException ; 34 import java.io.InputStream ; 35 36 39 class CachedFilePresentation implements HttpPresentation { 40 private String mimeType; 41 private int contentLen = 0; 42 private ByteArrayInputStream fileData; 43 44 private static final int READ_BUFFER_SIZE = 4096; 45 46 49 protected CachedFilePresentation(ClassLoader classLoader, 50 String urlPath, 51 String fileMimeType) 52 throws FilePresentationException { 53 mimeType = fileMimeType; 54 InputStream input = classLoader.getResourceAsStream(urlPath); 55 if (input == null) { 56 throw new FilePresentationException 57 (new FileNotFoundException ("File \"" + urlPath 58 + "\" not found on application class path")); 59 } 60 61 ByteArrayOutputStream inData = new ByteArrayOutputStream (); 62 try { 63 try { 65 byte [] buffer = new byte[READ_BUFFER_SIZE]; 66 while (true) { 67 int readLen = input.read(buffer, 0, READ_BUFFER_SIZE); 68 if (readLen < 0) 69 break; 70 inData.write(buffer, 0, readLen); 71 contentLen += readLen; 72 } 73 } finally { 74 fileData = new ByteArrayInputStream (inData.toByteArray()); 75 input.close(); 76 } 77 } catch (Exception except) { 78 throw new FilePresentationException(except); 79 } 80 } 81 82 85 public void run(HttpPresentationComms comms) 86 throws FilePresentationException { 87 try { 88 comms.response.setContentLength(contentLen); 89 comms.response.setContentType(mimeType); 90 91 if (!comms.request.getMethod().equals("HEAD")) { 92 byte [] buffer = new byte[READ_BUFFER_SIZE]; 93 HttpPresentationOutputStream output = comms.response.getOutputStream(); 94 while (true) { 95 int readLen = fileData.read(buffer, 0, READ_BUFFER_SIZE); 96 if (readLen < 0) { 97 break; 98 } 99 output.write(buffer, 0, readLen); 100 } 101 } 102 } catch (Exception except) { 103 throw new FilePresentationException(except); 104 } finally { 105 fileData.reset(); 106 } 107 } 108 } 109 | Popular Tags |