Debian Codegraph @

src/java/org/astrogrid/samp/httpd/UtilServer.java

raw
1 package org.astrogrid.samp.httpd;
2
3 import java.io.File;
4 import java.io.FileNotFoundException;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.net.BindException;
9 import java.net.MalformedURLException;
10 import java.net.ServerSocket;
11 import java.net.URL;
12 import java.util.HashSet;
13 import java.util.Set;
14 import java.util.logging.Logger;
15 import java.util.regex.Matcher;
16 import java.util.regex.Pattern;
17
18 /**
19 * Utility class for use with HttpServer.
20 *
21 * <p>This class performs two functions. Firstly it provides a static
22 * {@link #getInstance} method which allows its use in a singleton-like way.
23 * The constructor is public, so singleton use is not enforced, but if
24 * you need a server but don't need exclusive control over it, obtaining
25 * one in this way will ensure that you don't start a new server
26 * (which requires a new socket and other resources) if a suitable one
27 * is already available.
28 *
29 * <p>Secondly, it provides some utility methods,
30 * {@link #exportResource} and {@link #exportFile},
31 * useful for turning files or classpath resources into
32 * publicly viewable URLs, which is sometimes useful within a SAMP
33 * context (for instance when providing an Icon URL in metadata).
34 *
35 * @author Mark Taylor
36 * @since 22 Jul 2009
37 */
38 public class UtilServer {
39
40 private final HttpServer server_;
41 private final Set baseSet_;
42 private MultiURLMapperHandler mapperHandler_;
43 private ResourceHandler resourceHandler_;
44
45 /**
46 * System Property key giving a preferred port number for the server.
47 * If unset, or 0, or the chosen port is occupied, a system-chosen
48 * value will be used.
49 * The property name is {@value}.
50 */
51 public static final String PORT_PROP = "jsamp.server.port";
52
53 /** Buffer size for copy data from input to output stream. */
54 private static int BUFSIZ = 16 * 1024;
55
56 /** Default instance of this class. */
57 private static UtilServer instance_;
58
59 private static final Pattern SLASH_REGEX =
60 Pattern.compile( "(/*)(.*?)(/*)" );
61 private static final Pattern NUMBER_REGEX =
62 Pattern.compile( "(.*?)([0-9]+)" );
63 private static final Logger logger_ =
64 Logger.getLogger( UtilServer.class.getName() );
65
66 /**
67 * Constructor.
68 * Note, it may be more appropriate to use the {@link #getInstance} method.
69 *
70 * @param server HTTP server providing base services
71 */
72 public UtilServer( HttpServer server ) throws IOException {
73 server_ = server;
74 baseSet_ = new HashSet();
75 }
76
77 /**
78 * Returns the HttpServer associated with this object.
79 *
80 * @return a running server instance
81 */
82 public HttpServer getServer() {
83 return server_;
84 }
85
86 /**
87 * Returns a handler for mapping local to external URLs associated with
88 * this server.
89 *
90 * @return url mapping handler
91 */
92 public synchronized MultiURLMapperHandler getMapperHandler() {
93 if ( mapperHandler_ == null ) {
94 try {
95 mapperHandler_ =
96 new MultiURLMapperHandler( server_,
97 getBasePath( "/export" ) );
98 }
99 catch ( MalformedURLException e ) {
100 throw (AssertionError) new AssertionError().initCause( e );
101 }
102 server_.addHandler( mapperHandler_ );
103 }
104 return mapperHandler_;
105 }
106
107 /**
108 * Returns a handler for general purpose resource serving associated with
109 * this server.
110 *
111 * @return resource serving handler
112 */
113 public synchronized ResourceHandler getResourceHandler() {
114 if ( resourceHandler_ == null ) {
115 resourceHandler_ =
116 new ResourceHandler( server_, getBasePath( "/docs" ) );
117 server_.addHandler( resourceHandler_ );
118 }
119 return resourceHandler_;
120 }
121
122 /**
123 * Exposes a resource from a given URL as a publicly visible URL.
124 * This is typically used if the given <code>localUrl</code> is
125 * only visible locally, for instance on this JVM's classpath.
126 *
127 * @param localUrl URL visible at least within this JVM
128 * @return URL for external reference to the resource
129 */
130 public URL exportResource( URL localUrl ) throws IOException {
131 return getMapperHandler().addLocalUrl( localUrl );
132 }
133
134 /**
135 * Exposes a resource from the JVM's classpath as a publicly visible URL.
136 * The classloader of this class is used, which may not be the right one
137 * for the resource in question.
138 * For that reason, this utility method is deprecated
139 * in favour of the overloaded method that takes a URL.
140 *
141 * @param resource fully qualified path to a resource in the current
142 * classpath; separators are "/" characters
143 * @return URL for external reference to the resource
144 * @deprecated since after 1.3.5,
145 * use instead {@link #exportResource(java.net.URL)}
146 */
147 public URL exportResource( String resource ) throws IOException {
148 URL localUrl = UtilServer.class.getResource( resource );
149 if ( localUrl != null ) {
150 return getMapperHandler().addLocalUrl( localUrl );
151 }
152 else {
153 throw new IOException( "Not found on classpath: " + resource );
154 }
155 }
156
157 /**
158 * Exposes a file in the local filesystem as a publicly visible URL.
159 *
160 * @param file a file on a filesystem visible from the local host
161 * @return URL for external reference to the resource
162 */
163 public URL exportFile( File file ) throws IOException {
164 if ( file.exists() ) {
165 return getMapperHandler().addLocalUrl( file.toURL() );
166 }
167 else {
168 throw new FileNotFoundException( "No such file: " + file );
169 }
170 }
171
172 /**
173 * May be used to return a unique base path for use with this class's
174 * HttpServer. If all users of this server use this method
175 * to get base paths for use with different handlers, nameclash
176 * avoidance is guaranteed.
177 *
178 * @param txt basic text for base path
179 * @return base path; will likely bear some resemblance to
180 * <code>txt</code>, but may be adjusted to ensure uniqueness
181 */
182 public synchronized String getBasePath( String txt ) {
183 Matcher slashMatcher = SLASH_REGEX.matcher( txt );
184 String pre;
185 String body;
186 String post;
187 if ( slashMatcher.matches() ) {
188 pre = slashMatcher.group( 1 );
189 body = slashMatcher.group( 2 );
190 post = slashMatcher.group( 3 );
191 }
192 else {
193 assert false;
194 pre = "";
195 body = txt;
196 post = "";
197 }
198 if ( baseSet_.contains( body ) ) {
199 String stem = body;
200 int i = 1;
201 while ( baseSet_.contains( stem + "-" + i ) ) {
202 i++;
203 }
204 body = stem + "-" + i;
205 }
206 baseSet_.add( body );
207 return pre + body + post;
208 }
209
210 /**
211 * Returns the default instance of this class.
212 * The first time this method is called a new daemon UtilServer
213 * is (lazily) created, and started. Any subsequent calls will
214 * return the same object, unless {@link #getInstance} is called.
215 *
216 * @return default instance of this class
217 */
218 public static synchronized UtilServer getInstance() throws IOException {
219 if ( instance_ == null ) {
220 ServerSocket sock = null;
221 String sPort = System.getProperty( PORT_PROP );
222 if ( sPort != null && sPort.length() > 0 ) {
223 int port = Integer.parseInt( sPort );
224 try {
225 sock = new ServerSocket( port );
226 }
227 catch ( BindException e ) {
228 logger_.warning( "Can't open socket on port " + port
229 + " (" + e + ") - use another one" );
230 }
231 }
232 if ( sock == null ) {
233 sock = new ServerSocket( 0 );
234 }
235 HttpServer server = new HttpServer( sock );
236 server.setDaemon( true );
237 server.start();
238 instance_ = new UtilServer( server );
239 }
240 return instance_;
241 }
242
243 /**
244 * Sets the default instance of this class.
245 *
246 * @param server default instance to be returned by {@link #getInstance}
247 */
248 public static synchronized void setInstance( UtilServer server ) {
249 instance_ = server;
250 }
251
252 /**
253 * Copies the content of an input stream to an output stream.
254 * The input stream is always closed on exit; the output stream is not.
255 *
256 * @param in input stream
257 * @param out output stream
258 */
259 public static void copy( InputStream in, OutputStream out )
260 throws IOException {
261 byte[] buf = new byte[ BUFSIZ ];
262 try {
263 for ( int nb; ( nb = in.read( buf ) ) >= 0; ) {
264 out.write( buf, 0, nb );
265 }
266 out.flush();
267 }
268 finally {
269 in.close();
270 }
271 }
272 }