1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.monitoring.reporting.web;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.util.List;
24
25 import javax.servlet.ServletException;
26 import javax.servlet.http.HttpServletRequest;
27 import javax.servlet.http.HttpServletResponse;
28
29 import org.apache.commons.monitoring.reporting.Renderer;
30
31
32
33
34
35
36
37 public class WebUIServlet
38 extends MonitoringServlet
39 {
40 private static final long serialVersionUID = 1L;
41
42
43
44
45
46
47
48 @Override
49 protected void service( HttpServletRequest request, HttpServletResponse response )
50 throws ServletException, IOException
51 {
52 String pathInfo = request.getPathInfo();
53 if ( pathInfo.startsWith( "/resources" ) )
54 {
55 String path = pathInfo.substring( "/resources".length() );
56 InputStream resource = getClass().getResourceAsStream( path );
57 if ( resource != null )
58 {
59 response.setContentType( getMimeTypes( pathInfo ) );
60 response.addHeader( "Cache-Control", "max-age=1000" );
61 copy( resource, response.getOutputStream() );
62 }
63 return;
64 }
65 super.service( request, response );
66 }
67
68
69
70
71
72 protected String getMimeTypes( String pathInfo )
73 {
74 if ( pathInfo.endsWith( ".css" ) )
75 {
76 return "text/css";
77 }
78 if ( pathInfo.endsWith( ".js" ) )
79 {
80 return "text/javascript";
81 }
82 if ( pathInfo.endsWith( ".gif" ) )
83 {
84 return "image/gif";
85 }
86 return null;
87 }
88
89 private static final int DEFAULT_BUFFER_SIZE = 4 * 1024;
90
91 private void copy( InputStream input, OutputStream output )
92 throws IOException
93 {
94 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
95 int n = 0;
96 while ( -1 != ( n = input.read( buffer ) ) )
97 {
98 output.write( buffer, 0, n );
99 }
100 try
101 {
102 input.close();
103 }
104 catch ( IOException e )
105 {
106
107 }
108 }
109
110
111
112
113
114
115
116 @Override
117 protected Renderer getRenderer( HttpServletRequest request, HttpServletResponse response )
118 throws IOException
119 {
120 List<String> accept = getAcceptedMimeTypes( request );
121 if ( accept.contains( "text/html" ) )
122 {
123 response.setContentType( "text/html;charset=iso-8859-1" );
124 return new NiceHtmlRenderer( request.getContextPath() + request.getServletPath() );
125 }
126 return super.getRenderer( request, response );
127 }
128 }