1 29 30 package nextapp.echo2.webrender.service; 31 32 import java.io.IOException ; 33 34 import nextapp.echo2.webrender.Connection; 35 import nextapp.echo2.webrender.Service; 36 import nextapp.echo2.webrender.util.GZipCompressor; 37 import nextapp.echo2.webrender.util.JavaScriptCompressor; 38 import nextapp.echo2.webrender.util.Resource; 39 40 43 public class JavaScriptService 44 implements Service { 45 46 55 public static JavaScriptService forResource(String id, String resourceName) { 56 String content = Resource.getResourceAsString(resourceName); 57 return new JavaScriptService(id, content); 58 } 59 60 61 private String id; 62 63 64 private String content; 65 66 67 private byte[] gzipContent; 68 69 75 public JavaScriptService(String id, String content) { 76 super(); 77 this.id = id; 78 this.content = JavaScriptCompressor.compress(content); 79 try { 80 gzipContent = GZipCompressor.compress(this.content); 81 } catch (IOException ex) { 82 throw new RuntimeException ("Exception compressing JavaScript source.", ex); 84 } 85 } 86 87 90 public String getId() { 91 return id; 92 } 93 94 101 public int getVersion() { 102 return DO_NOT_CACHE; 103 } 104 105 108 public void service(Connection conn) 109 throws IOException { 110 String userAgent = conn.getRequest().getHeader("user-agent"); 111 if (userAgent == null || userAgent.indexOf("MSIE") != -1) { 112 servicePlain(conn); 118 } else { 119 String acceptEncoding = conn.getRequest().getHeader("accept-encoding"); 120 if (acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1) { 121 serviceGZipCompressed(conn); 122 } else { 123 servicePlain(conn); 124 } 125 } 126 } 127 128 133 private void serviceGZipCompressed(Connection conn) 134 throws IOException { 135 conn.getResponse().setContentType("text/plain"); 136 conn.getResponse().setHeader("Content-Encoding", "gzip"); 137 conn.getOutputStream().write(gzipContent); 138 } 139 140 145 private void servicePlain(Connection conn) 146 throws IOException { 147 conn.getResponse().setContentType("text/plain"); 148 conn.getWriter().print(content); 149 } 150 } 151 | Popular Tags |