1 15 package org.apache.activemq.web; 16 17 import java.io.ByteArrayOutputStream ; 18 import java.io.IOException ; 19 import java.io.InputStream ; 20 import java.net.URL ; 21 import java.util.HashMap ; 22 import java.util.Map ; 23 24 import javax.servlet.ServletException ; 25 import javax.servlet.http.HttpServletRequest ; 26 import javax.servlet.http.HttpServletResponse ; 27 28 29 30 38 public class AjaxServlet extends MessageListenerServlet { 39 40 private Map jsCache = new HashMap (); 41 private long jsLastModified = 1000*(System.currentTimeMillis()/1000); 42 43 44 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { 45 if (request.getPathInfo()!=null && request.getPathInfo().endsWith(".js")) 46 doJavaScript(request,response); 47 else 48 super.doGet(request, response); 49 } 50 51 protected void doJavaScript(HttpServletRequest request, HttpServletResponse response)throws IOException , ServletException { 52 53 String js = request.getServletPath()+request.getPathInfo(); 55 URL url = getServletContext().getResource(js); 56 if (url!=null) 57 { 58 getServletContext().getNamedDispatcher("default").forward(request,response); 59 return; 60 } 61 62 String resource="org/apache/activemq/web"+request.getPathInfo(); 64 synchronized(jsCache){ 65 66 byte[] data = (byte[])jsCache.get(resource); 67 if (data==null) { 68 InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); 69 if (in!=null) 70 { 71 ByteArrayOutputStream out = new ByteArrayOutputStream (); 72 byte[] buf=new byte[4096]; 73 int len=in.read(buf); 74 while (len>=0) { 75 out.write(buf, 0, len); 76 len=in.read(buf); 77 } 78 in.close(); 79 out.close(); 80 data=out.toByteArray(); 81 jsCache.put(resource, data); 82 } 83 } 84 85 if (data!=null){ 86 87 long if_modified = request.getDateHeader("If-Modified-Since"); 88 89 if (if_modified == jsLastModified) { 90 response.sendError(HttpServletResponse.SC_NOT_MODIFIED); 91 } 92 else { 93 response.setContentType("application/x-javascript"); 94 response.setContentLength(data.length); 95 response.setDateHeader("Last-Modified",jsLastModified); 96 response.getOutputStream().write(data); 97 } 98 } 99 else 100 response.sendError(HttpServletResponse.SC_NOT_FOUND); 101 } 102 } 103 } 104 | Popular Tags |