1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.jmonit.web;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22 import java.util.List;
23
24 import javax.servlet.FilterChain;
25 import javax.servlet.FilterConfig;
26 import javax.servlet.ServletException;
27 import javax.servlet.http.HttpServletRequest;
28 import javax.servlet.http.HttpServletResponse;
29
30 import org.jmonit.log.Log;
31
32
33
34
35
36
37 public class JMonitFilterWithWebUI
38 extends JMonitFilter
39 {
40
41 private static Log log = Log.getLog( JMonitFilterWithWebUI.class );
42
43
44 private RestServlet restServlet;
45
46
47
48
49
50
51 public void init( FilterConfig filterConfig )
52 throws ServletException
53 {
54 super.init( filterConfig );
55 restServlet = new RestServlet();
56 }
57
58
59
60
61 private static final String CONTEXT = "/jMonit/";
62
63 public void doFilter( HttpServletRequest request, HttpServletResponse response,
64 FilterChain chain )
65 throws IOException, ServletException
66 {
67 String uri = getRequestedUri( request );
68 if ( !uri.startsWith( CONTEXT ) )
69 {
70 super.doFilter( request, response, chain );
71 return;
72 }
73 if ( log.isDebugEnabled() )
74 {
75 log.debug( "request to jMonit Web UI " + uri );
76 }
77 uri = uri.substring( CONTEXT.length() );
78 InputStream resource = getClass().getResourceAsStream( uri );
79 if ( resource != null )
80 {
81 List<String> types = MimeUtils.getMimeTypes( request );
82 if ( !types.isEmpty() )
83 {
84 response.setContentType( types.get( 0 ) );
85 }
86 response.addHeader( "Cache-Control", "max-age=1000" );
87 copy( resource, response.getOutputStream() );
88 }
89 else
90 {
91 final String pathInfo = "/" + uri;
92 restServlet.restService( pathInfo, MimeUtils.getMimeTypes( request ), response );
93 }
94 }
95
96
97
98 private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
99
100
101
102
103
104
105 private void copy( InputStream input, OutputStream output )
106 throws IOException
107 {
108 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
109 int n = 0;
110 while ( -1 != ( n = input.read( buffer ) ) )
111 {
112 output.write( buffer, 0, n );
113 }
114 try
115 {
116 input.close();
117 }
118 catch ( IOException e )
119 {
120 log.warn( "failed to copy resource", e );
121
122 }
123 }
124
125 }