1 2 24 25 26 27 28 29 package com.lutris.appserver.server.httpPresentation; 30 31 import java.io.FileNotFoundException ; 32 import java.io.IOException ; 33 import java.io.InputStream ; 34 35 import com.lutris.classloader.MultiClassLoader; 36 import com.lutris.classloader.Resource; 37 38 42 class CopyFilePresentation implements HttpPresentation { 43 private InputStream input; 44 private int contentLength; 45 private String mimeType; 46 47 private static final int FILE_BUFFER_SIZE = 4096; 48 49 52 private void copyFile(HttpPresentationComms comms) 53 throws FilePresentationException { 54 55 try { 56 byte [] buffer = new byte[FILE_BUFFER_SIZE]; 57 HttpPresentationOutputStream output = comms.response.getOutputStream(); 58 while (true) { 59 int readLen = input.read(buffer, 0, FILE_BUFFER_SIZE); 60 if (readLen < 0) { 61 break; 62 } 63 output.write(buffer, 0, readLen); 64 } 65 } catch (Exception except) { 66 throw new FilePresentationException(except); 67 } 68 } 69 70 73 protected CopyFilePresentation(ClassLoader classLoader, 74 String urlPath, 75 String fileMimeType) 76 throws FilePresentationException { 77 mimeType = fileMimeType; 78 79 84 try { 85 if (classLoader instanceof MultiClassLoader) { 86 Resource resource = ((MultiClassLoader)classLoader).getResourceAsIs(urlPath); 87 if (resource != null) { 88 input = resource.getInputStream(); 89 contentLength = (int)resource.getSize(); 90 } 91 } else { 92 input = classLoader.getResourceAsStream(urlPath); 93 contentLength = -1; 94 } 95 } catch (IOException except) { 96 throw new FilePresentationException("Error accessing \"" + urlPath + "\"", except); 97 } 98 if (input == null) { 99 throw new FilePresentationException 100 (new FileNotFoundException ("File \"" + urlPath 101 + "\" not found on application class path")); 102 } 103 } 104 105 108 protected void finalize() throws Throwable { 109 if (input != null) { 110 input.close(); 111 } 112 super.finalize(); 113 } 114 115 118 public void run(HttpPresentationComms comms) 119 throws FilePresentationException { 120 try { 121 comms.response.setContentType(mimeType); 122 comms.response.setContentLength(contentLength); 123 try { 124 if (!comms.request.getMethod().equals("HEAD")) { 125 copyFile(comms); 126 } 127 } finally { 128 input.close(); 129 input = null; 130 } 131 } catch (FilePresentationException except) { 132 throw except; 133 } catch (Exception except) { 134 throw new FilePresentationException(except); 135 } 136 } 137 } 138 | Popular Tags |