Debian Codegraph @

src/java/org/astrogrid/samp/SampUtils.java

raw
1 package org.astrogrid.samp;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.UnsupportedEncodingException;
7 import java.net.ConnectException;
8 import java.net.InetAddress;
9 import java.net.MalformedURLException;
10 import java.net.ServerSocket;
11 import java.net.Socket;
12 import java.net.URL;
13 import java.net.URLDecoder;
14 import java.net.URLEncoder;
15 import java.net.UnknownHostException;
16 import java.util.Arrays;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.logging.Level;
21 import java.util.logging.Logger;
22
23 /**
24 * Contains static utility methods for use with the SAMP toolkit.
25 *
26 * @author Mark Taylor
27 * @since 15 Jul 2008
28 */
29 public class SampUtils {
30
31 /**
32 * Property which can be used to set name used for localhost in server
33 * endpoints.
34 * Value is {@value}.
35 * @see #getLocalhost
36 */
37 public static final String LOCALHOST_PROP = "jsamp.localhost";
38
39 private static final Logger logger_ =
40 Logger.getLogger( SampUtils.class.getName() );
41 private static String sampVersion_;
42 private static String softwareVersion_;
43 private static File lockFile_;
44 private static final String NEWLINE = getLineSeparator();
45
46 /**
47 * Private constructor prevents instantiation.
48 */
49 private SampUtils() {
50 }
51
52 /**
53 * Returns a <em>SAMP int</em> string representation of an integer.
54 *
55 * @param i integer value
56 * @return SAMP int string
57 */
58 public static String encodeInt( int i ) {
59 return Integer.toString( i );
60 }
61
62 /**
63 * Returns the integer value for a <em>SAMP int</em> string.
64 *
65 * @param s SAMP int string
66 * @return integer value
67 * @throws NumberFormatException if conversion fails
68 */
69 public static int decodeInt( String s ) {
70 return Integer.parseInt( s );
71 }
72
73 /**
74 * Returns a <em>SAMP int</em> string representation of a long integer.
75 *
76 * @param i integer value
77 * @return SAMP int string
78 */
79 public static String encodeLong( long i ) {
80 return Long.toString( i );
81 }
82
83 /**
84 * Returns the integer value as a <code>long</code> for a <em>SAMP int</em>
85 * string.
86 *
87 * @param s SAMP int string
88 * @return long integer value
89 * @throws NumberFormatException if conversion fails
90 */
91 public static long decodeLong( String s ) {
92 return Long.parseLong( s );
93 }
94
95 /**
96 * Returns a <em>SAMP float</em> string representation of a floating point
97 * value.
98 *
99 * @param d double value
100 * @return SAMP double string
101 * @throws IllegalArgumentException if <code>d</code> is NaN or infinite
102 */
103 public static String encodeFloat( double d ) {
104 if ( Double.isInfinite( d ) ) {
105 throw new IllegalArgumentException( "Infinite value "
106 + "not permitted" );
107 }
108 if ( Double.isNaN( d ) ) {
109 throw new IllegalArgumentException( "NaN not permitted" );
110 }
111 return Double.toString( d );
112 }
113
114 /**
115 * Returns the double value for a <em>SAMP float</em> string.
116 *
117 * @param s SAMP float string
118 * @return double value
119 * @throws NumberFormatException if conversion fails
120 */
121 public static double decodeFloat( String s ) {
122 return Double.parseDouble( s );
123 }
124
125 /**
126 * Returns a <em>SAMP boolean</em> string representation of a boolean value.
127 *
128 * @param b boolean value
129 * @return SAMP boolean string
130 */
131 public static String encodeBoolean( boolean b ) {
132 return encodeInt( b ? 1 : 0 );
133 }
134
135 /**
136 * Returns the boolean value for a <em>SAMP boolean</em> string.
137 *
138 * @param s SAMP boolean string
139 * @return false iff <code>s</code> is equal to zero
140 */
141 public static boolean decodeBoolean( String s ) {
142 try {
143 return decodeInt( s ) != 0;
144 }
145 catch ( NumberFormatException e ) {
146 return false;
147 }
148 }
149
150 /**
151 * Checks that a given object is legal for use in a SAMP context.
152 * This checks that it is either a String, List or Map, that
153 * any Map keys are Strings, and that Map values and List elements are
154 * themselves legal (recursively).
155 *
156 * @param obj object to check
157 * @throws DataException in case of an error
158 */
159 public static void checkObject( Object obj ) {
160 if ( obj instanceof Map ) {
161 checkMap( (Map) obj );
162 }
163 else if ( obj instanceof List ) {
164 checkList( (List) obj );
165 }
166 else if ( obj instanceof String ) {
167 checkString( (String) obj );
168 }
169 else if ( obj == null ) {
170 throw new DataException( "Bad SAMP object: contains a null" );
171 }
172 else {
173 throw new DataException( "Bad SAMP object: contains a "
174 + obj.getClass().getName() );
175 }
176 }
177
178 /**
179 * Checks that a given Map is legal for use in a SAMP context.
180 * All its keys must be strings, and its values must be legal
181 * SAMP objects.
182 *
183 * @param map map to check
184 * @throws DataException in case of an error
185 * @see #checkObject
186 */
187 public static void checkMap( Map map ) {
188 for ( Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
189 Map.Entry entry = (Map.Entry) it.next();
190 Object key = entry.getKey();
191 if ( key instanceof String ) {
192 checkString( (String) key );
193 checkObject( entry.getValue() );
194 }
195 else if ( key == null ) {
196 throw new DataException( "Map key null" );
197 }
198 else {
199 throw new DataException( "Map key not a string ("
200 + key.getClass().getName() + ")" );
201 }
202 }
203 }
204
205 /**
206 * Checks that a given List is legal for use in a SAMP context.
207 * All its elements must be legal SAMP objects.
208 *
209 * @param list list to check
210 * @throws DataException in case of error
211 * @see #checkObject
212 */
213 public static void checkList( List list ) {
214 for ( Iterator it = list.iterator(); it.hasNext(); ) {
215 checkObject( it.next() );
216 }
217 }
218
219 /**
220 * Checks that a given String is legal for use in a SAMP context.
221 * All its characters must be in the range 0x01 - 0x7f.
222 *
223 * @param string string to check
224 * @throws DataException in case of error
225 */
226 public static void checkString( String string ) {
227 int leng = string.length();
228 for ( int i = 0; i < leng; i++ ) {
229 char c = string.charAt( i );
230 if ( ! isStringChar( c ) ) {
231 throw new DataException( "Bad SAMP string; contains character "
232 + "0x" + Integer.toHexString( c ) );
233 }
234 }
235 }
236
237 /**
238 * Indicates whether a given character is legal to include in a SAMP
239 * string.
240 *
241 * @return true iff c is 0x09, 0x0a, 0x0d or 0x20--0x7f
242 */
243 public static boolean isStringChar( char c ) {
244 switch ( c ) {
245 case 0x09:
246 case 0x0a:
247 case 0x0d:
248 return true;
249 default:
250 return c >= 0x20 && c <= 0x7f;
251 }
252 }
253
254 /**
255 * Checks that a string is a legal URL.
256 *
257 * @param url string to check
258 * @throws DataException if <code>url</code> is not a legal URL
259 */
260 public static void checkUrl( String url ) {
261 if ( url != null ) {
262 try {
263 new URL( (String) url );
264 }
265 catch ( MalformedURLException e ) {
266 throw new DataException( "Bad URL " + url, e );
267 }
268 }
269 }
270
271 /**
272 * Returns a string representation of a client object.
273 * The name is used if present, otherwise the ID.
274 *
275 * @param client client object
276 * @return string
277 */
278 public static String toString( Client client ) {
279 Metadata meta = client.getMetadata();
280 if ( meta != null ) {
281 String name = meta.getName();
282 if ( name != null && name.trim().length() > 0 ) {
283 return name;
284 }
285 }
286 return client.getId();
287 }
288
289 /**
290 * Pretty-prints a SAMP object.
291 *
292 * @param obj SAMP-friendly object
293 * @param indent base indent for text block
294 * @return string containing formatted object
295 */
296 public static String formatObject( Object obj, int indent ) {
297 checkObject( obj );
298 return new JsonWriter( indent, true ).toJson( obj );
299 }
300
301 /**
302 * Parses a command-line string as a SAMP object.
303 * If it can be parsed as a SAMP-friendly JSON string, that interpretation
304 * will be used. Otherwise, the value is just the string as presented.
305 *
306 * @param str command-line argument
307 * @return SAMP object
308 */
309 public static Object parseValue( String str ) {
310 if ( str == null || str.length() == 0 ) {
311 return null;
312 }
313 else {
314 try {
315 Object obj = fromJson( str );
316 checkObject( obj );
317 return obj;
318 }
319 catch ( RuntimeException e ) {
320 logger_.config( "String not JSON (" + e + ")" );
321 }
322 Object sval = str;
323 checkObject( sval );
324 return sval;
325 }
326 }
327
328 /**
329 * Returns a string denoting the local host to be used for communicating
330 * local server endpoints and so on.
331 *
332 * <p>The value returned by default is the loopback address, "127.0.0.1".
333 * However this behaviour can be overridden by setting the
334 * {@link #LOCALHOST_PROP} system property to the string which should
335 * be returned instead.
336 * This may be necessary if the loopback address is not appropriate,
337 * for instance in the case of multiple configured loopback interfaces(?)
338 * or where SAMP communication is required across different machines.
339 * There are two special values which may be used for this property:
340 * <ul>
341 * <li><code>[hostname]</code>:
342 * uses the fully qualified domain name of the host</li>
343 * <li><code>[hostnumber]</code>:
344 * uses the IP number of the host</li>
345 * </ul>
346 * If these determinations fail for some reason, a fallback value of
347 * 127.0.0.1 will be used.
348 *
349 * <p>In JSAMP version 0.3-1 and prior versions, the [hostname]
350 * behaviour was the default.
351 * Although this might be seen as more correct, in practice it could cause
352 * a lot of problems with DNS configurations which are incorrect or
353 * unstable (common in laptops outside their usual networks).
354 * See, for instance, AstroGrid bugzilla tickets
355 * <a href="http://www.astrogrid.org/bugzilla/show_bug.cgi?id=1799"
356 * >1799</a>,
357 * <a href="http://www.astrogrid.org/bugzilla/show_bug.cgi?id=2151"
358 * >2151</a>.
359 *
360 * <p>In JSAMP version 0.3-1 and prior versions, the property was
361 * named <code>samp.localhost</code> rather than
362 * <code>jsamp.localhost</code>. This name is still accepted for
363 * backwards compatibility.
364 *
365 * @return local host name
366 */
367 public static String getLocalhost() {
368 final String defaultHost = "127.0.0.1";
369 String hostname =
370 System.getProperty( LOCALHOST_PROP,
371 System.getProperty( "samp.localhost", "" ) );
372 if ( hostname.length() == 0 ) {
373 hostname = defaultHost;
374 }
375 else if ( "[hostname]".equals( hostname ) ) {
376 try {
377 hostname = InetAddress.getLocalHost().getCanonicalHostName();
378 }
379 catch ( UnknownHostException e ) {
380 logger_.log( Level.WARNING,
381 "Local host determination failed - fall back to "
382 + defaultHost, e );
383 hostname = defaultHost;
384 }
385 }
386 else if ( "[hostnumber]".equals( hostname ) ) {
387 try {
388 hostname = InetAddress.getLocalHost().getHostAddress();
389 }
390 catch ( UnknownHostException e ) {
391 logger_.log( Level.WARNING,
392 "Local host determination failed - fall back to "
393 + defaultHost, e );
394 hostname = defaultHost;
395 }
396 }
397 logger_.config( "Local host is " + hostname );
398 return hostname;
399 }
400
401 /**
402 * Returns an unused port number on the local host.
403 *
404 * @param startPort suggested port number; may or may not be used
405 * @return unused port
406 */
407 public static int getUnusedPort( int startPort ) throws IOException {
408
409 // Current implementation ignores the given startPort and uses
410 // findAnyPort.
411 return true ? findAnyPort()
412 : scanForPort( startPort, 20 );
413 }
414
415 /**
416 * Turns a File into a URL.
417 * Unlike Sun's J2SE, this gives you a URL which conforms to RFC1738 and
418 * looks like "<code>file://localhost/abs-path</code>" rather than
419 * "<code>file:abs-or-rel-path</code>".
420 * For non-ASCII characters, UTF-8 encoding is used.
421 *
422 * @param file file
423 * @return URL
424 * @see "RFC 1738"
425 * @see <a
426 * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6356783"
427 * >Sun Java bug 6356783</a>
428 */
429 public static URL fileToUrl( File file ) {
430 try {
431 String path = file.toURI().toURL().getPath();
432 StringBuffer pbuf = new StringBuffer();
433 for ( int ic = 0; ic < path.length(); ic++ ) {
434 char c = path.charAt( ic );
435 if ( c == '/' ) {
436 pbuf.append( c );
437 }
438 else {
439 pbuf.append( uriEncode( new String( new char[] { c } ) ) );
440 }
441 }
442 return new URL( "file", "localhost", pbuf.toString() );
443 }
444 catch ( MalformedURLException e ) {
445 throw new AssertionError();
446 }
447 }
448
449 /**
450 * Reverses URI-style character escaping (%xy) on a string.
451 * Note, unlike {@link java.net.URLDecoder},
452 * this does not turn "+" characters into spaces.
453 * For non-ASCII characters, UTF-8 encoding is used.
454 *
455 * @see "RFC 2396, Section 2.4"
456 * @param text escaped text
457 * @return unescaped text
458 */
459 public static String uriDecode( String text ) {
460 try {
461 return URLDecoder.decode( replaceChar( text, '+', "%2B" ),
462 "UTF-8" );
463 }
464 catch ( UnsupportedEncodingException e ) {
465 throw new AssertionError( "UTF-8 unsupported??" );
466 }
467 }
468
469 /**
470 * Performs URI-style character escaping (%xy) on a string.
471 * Note, unlike {@link java.net.URLEncoder},
472 * this encodes spaces as "%20" and not "+".
473 * For non-ASCII characters, UTF-8 encoding is used.
474 *
475 * @see "RFC 2396, Section 2.4"
476 * @param text unescaped text
477 * @return escaped text
478 */
479 public static String uriEncode( String text ) {
480 try {
481 return replaceChar( URLEncoder.encode( text, "UTF-8" ),
482 '+', "%20" );
483 }
484 catch ( UnsupportedEncodingException e ) {
485 throw new AssertionError( "UTF-8 unsupported??" );
486 }
487 }
488
489 /**
490 * Attempts to interpret a URL as a file.
491 * If the URL does not have the "file:" protocol, null is returned.
492 *
493 * @param url URL, may or may not be file: protocol
494 * @return file, or null
495 */
496 public static File urlToFile( URL url ) {
497 if ( url.getProtocol().equals( "file" ) && url.getRef() == null
498 && url.getQuery() == null ) {
499 String path = uriDecode( url.getPath() );
500 String filename = File.separatorChar == '/'
501 ? path
502 : path.replace( '/', File.separatorChar );
503 return new File( filename );
504 }
505 else {
506 return null;
507 }
508 }
509
510 /**
511 * Parses JSON text to give a SAMP object.
512 * Note that double-quoted strings are the only legal scalars
513 * (no unquoted numbers or booleans).
514 *
515 * @param str string to parse
516 * @return SAMP object
517 */
518 public static Object fromJson( String str ) {
519 return new JsonReader().read( str );
520 }
521
522 /**
523 * Serializes a SAMP object to a JSON string.
524 *
525 * @param item to serialize
526 * @param multiline true for formatted multiline output, false for a
527 * single line
528 */
529 public static String toJson( Object item, boolean multiline ) {
530 checkObject( item );
531 return new JsonWriter( multiline ? 2 : -1, true ).toJson( item );
532 }
533
534 /**
535 * Returns a string giving the version of the SAMP standard which this
536 * software implements.
537 *
538 * @return SAMP standard version
539 */
540 public static String getSampVersion() {
541 if ( sampVersion_ == null ) {
542 sampVersion_ = readResource( "samp.version" );
543 }
544 return sampVersion_;
545 }
546
547 /**
548 * Returns a string giving the version of this software package.
549 *
550 * @return JSAMP version
551 */
552 public static String getSoftwareVersion() {
553 if ( softwareVersion_ == null ) {
554 softwareVersion_ = readResource( "jsamp.version" );
555 }
556 return softwareVersion_;
557 }
558
559 /**
560 * Returns the contents of a resource as a string.
561 *
562 * @param rname resource name
563 * (in the sense of {@link java.lang.Class#getResource})
564 */
565 private static String readResource( String rname ) {
566 URL url = SampUtils.class.getResource( rname );
567 if ( url == null ) {
568 logger_.warning( "No such resource " + rname );
569 return "??";
570 }
571 else {
572 try {
573 InputStream in = url.openStream();
574 StringBuffer sbuf = new StringBuffer();
575 for ( int c; ( c = in.read() ) >= 0; ) {
576 sbuf.append( (char) c );
577 }
578 in.close();
579 return sbuf.toString().trim();
580 }
581 catch ( IOException e ) {
582 logger_.warning( "Failed to read resource " + url );
583 return "??";
584 }
585 }
586 }
587
588 /**
589 * Returns the system-dependent line separator sequence.
590 *
591 * @return line separator
592 */
593 private static String getLineSeparator() {
594 try {
595 return System.getProperty( "line.separator", "\n" );
596 }
597 catch ( SecurityException e ) {
598 return "\n";
599 }
600 }
601
602 /**
603 * Replaces all occurrences of a single character with a given replacement
604 * string.
605 *
606 * @param in input string
607 * @param oldChar character to replace
608 * @param newText replacement string
609 * @return modified string
610 */
611 private static String replaceChar( String in, char oldChar,
612 String newTxt ) {
613 int len = in.length();
614 StringBuffer sbuf = new StringBuffer( len );
615 for ( int i = 0; i < len; i++ ) {
616 char c = in.charAt( i );
617 if ( c == oldChar ) {
618 sbuf.append( newTxt );
619 }
620 else {
621 sbuf.append( c );
622 }
623 }
624 return sbuf.toString();
625 }
626
627 /**
628 * Locates an unused server port on the local host.
629 * Potential problem: between when this method completes and when
630 * the return value of this method is used by its caller, it's possible
631 * that the port will get used by somebody else.
632 * Probably this will not happen much in practice??
633 *
634 * @return unused server port
635 */
636 private static int findAnyPort() throws IOException {
637 ServerSocket socket = new ServerSocket( 0 );
638 try {
639 return socket.getLocalPort();
640 }
641 finally {
642 try {
643 socket.close();
644 }
645 catch ( IOException e ) {
646 }
647 }
648 }
649
650 /**
651 * Two problems with this one - it may be a bit inefficient, and
652 * there's an annoying bug in the Apache XML-RPC WebServer class
653 * which causes it to print "java.util.NoSuchElementException" to
654 * the server's System.err for every port scanned by this routine
655 * that an org.apache.xmlrpc.WebServer server is listening on.
656 *
657 * @param startPort port to start scanning upwards from
658 * @param nTry number of ports in sequence to try before admitting defeat
659 * @return unused server port
660 */
661 private static int scanForPort( int startPort, int nTry )
662 throws IOException {
663 for ( int iPort = startPort; iPort < startPort + nTry; iPort++ ) {
664 try {
665 Socket trySocket = new Socket( "localhost", iPort );
666 if ( ! trySocket.isClosed() ) {
667 trySocket.shutdownOutput();
668 trySocket.shutdownInput();
669 trySocket.close();
670 }
671 }
672 catch ( ConnectException e ) {
673
674 /* Can't connect - this hopefully means that the socket is
675 * unused. */
676 return iPort;
677 }
678 }
679 throw new IOException( "Can't locate an unused port in range " +
680 startPort + " ... " + ( startPort + nTry ) );
681 }
682 }