KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openlaszlo > iv > flash > util > Util


1 /*
2  * $Id: Util.java,v 1.8 2002/07/15 02:15:03 skavish Exp $
3  *
4  * ===========================================================================
5  *
6  * The JGenerator Software License, Version 1.0
7  *
8  * Copyright (c) 2000 Dmitry Skavish (skavish@usa.net). All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if
22  * any, must include the following acknowlegement:
23  * "This product includes software developed by Dmitry Skavish
24  * (skavish@usa.net, http://www.flashgap.com/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The name "The JGenerator" must not be used to endorse or promote
29  * products derived from this software without prior written permission.
30  * For written permission, please contact skavish@usa.net.
31  *
32  * 5. Products derived from this software may not be called "The JGenerator"
33  * nor may "The JGenerator" appear in their names without prior written
34  * permission of Dmitry Skavish.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL DMITRY SKAVISH OR THE OTHER
40  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  *
49  */

50
51 package org.openlaszlo.iv.flash.util;
52
53 import org.openlaszlo.iv.flash.api.*;
54
55 import org.openlaszlo.iv.flash.cache.*;
56 import org.openlaszlo.iv.flash.url.*;
57 import org.openlaszlo.iv.flash.context.*;
58
59 import java.awt.geom.Rectangle2D JavaDoc;
60 import java.awt.geom.AffineTransform JavaDoc;
61 import java.io.*;
62 import java.net.*;
63 import java.util.*;
64 import java.lang.reflect.*;
65
66 /**
67  * Utility class.
68  *
69  * @author Dmitry Skavish
70  */

71 public class Util {
72
73     public static String JavaDoc genVersion = "2.0";
74
75     public static double javaVersion = 1.2;
76     public static char fileSeparator = '/';
77     public static char pathSeparator = ':';
78     public static String JavaDoc lineSeparator = "\n";
79
80     private static String JavaDoc installDir;
81
82     /**
83      * Initialize JGenerator
84      * <P>
85      * Usually you need to call this method from standalone applications only
86      */

87     public static void init() {
88
89         // try to find jgenerator install directory
90
String JavaDoc installDir = System.getProperty("org.openlaszlo.iv.flash.installDir");
91
92         if( installDir == null ) installDir = System.getProperty("iv.flash.installDir");
93
94         // try to figure out install dir from classloader
95
if( installDir == null ) {
96             String JavaDoc resource = "/"+Util.class.getName().replace('.','/')+".class";
97             URL classFileURL = getResource(resource);
98             String JavaDoc path = classFileURL.getPath();
99             if( path.startsWith("file:" ) ) {
100                 path = path.substring(5);
101                 int idx = path.lastIndexOf( "/lib/" );
102                 if( idx != -1 ) {
103                     installDir = path.substring(0,idx);
104                 }
105             } else {
106                 int idx = path.lastIndexOf( "/classes/" );
107                 if( idx != -1 ) {
108                     installDir = path.substring(0,idx);
109                 }
110             }
111         }
112
113         if( installDir == null ) installDir = "";
114
115         init( installDir );
116     }
117
118     /**
119      * Initialize JGenerator.
120      * <P>
121      * Sets installation directory and reads and caches some
122      * basic properties and iv.properties file
123      *
124      * @param installDir jgenerator installation directory
125      * @param propFileName iv.properties file name
126      */

127     public static void init( String JavaDoc installDir, String JavaDoc propFileName ) {
128         Util.installDir = translatePath(installDir);
129
130         PropertyManager.init(propFileName);
131
132         try {
133             String JavaDoc jVersion = System.getProperty("java.version").substring(0, 3);
134             javaVersion = toDouble(jVersion, 1.2);
135             fileSeparator = System.getProperty("file.separator","/").charAt(0);
136             pathSeparator = System.getProperty("path.separator",":").charAt(0);
137             lineSeparator = System.getProperty("line.separator","\n");
138         } catch( Throwable JavaDoc e ) {
139             Log.error(Resource.get(Resource.CANTLOADSYSPROPS));
140         }
141     }
142
143     /**
144      * Initialize JGenerator.
145      * <P>
146      * Sets installation directory and reads and caches some
147      * basic properties and iv.properties file
148      *
149      * @param installDir jgenerator installation directory
150      */

151     public static void init( String JavaDoc installDir ) {
152         init(installDir, null);
153     }
154
155     /**
156      * Gets resource's URL
157      *
158      * @param resource resource name
159      * @return resource URL
160      */

161     public static URL getResource( String JavaDoc resource ) {
162         ClassLoader JavaDoc classLoader = null;
163         URL url = null;
164
165         try {
166             classLoader = Thread.currentThread().getContextClassLoader();
167             if( classLoader != null ) {
168                 url = classLoader.getResource(resource);
169                 if( url != null ) {
170                     return url;
171                 }
172             }
173
174             // We could not find resource. Ler us now try with the
175
// classloader that loaded this class.
176
classLoader = Util.class.getClassLoader();
177
178             url = classLoader.getResource(resource);
179             if( url != null ) {
180                 return url;
181             }
182         } catch( Throwable JavaDoc t ) {
183         }
184
185         // get the resource from the class path
186
return ClassLoader.getSystemResource(resource);
187     }
188
189     /**
190      * Returns true if the specified string is "default" in some language
191      *
192      * @param s string to be tested for "default"
193      * @return true if the specified string is "default"
194      */

195     public static boolean isDefault( String JavaDoc s ) {
196         return s.equalsIgnoreCase("default") || s.equalsIgnoreCase("\u30c7\u30d5\u30a9\u30eb\u30c8") ||
197                s.equalsIgnoreCase("Standard") || s.equalsIgnoreCase("D\u00e9faut") ||
198                s.equalsIgnoreCase("Padr\u00e3o") || s.equalsIgnoreCase("Predeterminado") ||
199                s.equalsIgnoreCase("Predefinita");
200     }
201
202     /**
203      * Converts specified string to int.
204      *
205      * @param v string to be converted
206      * @param def default value to be used if there are some problems during conversion
207      * @return int value
208      */

209     public static int toInt( String JavaDoc v, int def ) {
210         if( v == null ) return def;
211         try {
212             return Integer.valueOf( v ).intValue();
213         } catch( NumberFormatException JavaDoc e ) {
214             return def;
215         }
216     }
217
218     /**
219      * Converts specified string to long.
220      *
221      * @param v string to be converted
222      * @param def default value to be used if there are some problems during conversion
223      * @return long value
224      */

225     public static long toLong( String JavaDoc v, long def ) {
226         if( v == null ) return def;
227         try {
228             return Long.valueOf( v ).longValue();
229         } catch( NumberFormatException JavaDoc e ) {
230             return def;
231         }
232     }
233
234     /**
235      * Converts specified string to double.
236      *
237      * @param v string to be converted
238      * @param def default value to be used if there are some problems during conversion
239      * @return double value
240      */

241     public static double toDouble( String JavaDoc v, double def ) {
242         if( v == null ) return def;
243         try {
244             return Double.valueOf( v ).doubleValue();
245         } catch( NumberFormatException JavaDoc e ) {
246             return def;
247         }
248     }
249
250     /**
251      * Converts specified string to boolean.
252      *
253      * @param v string to be converted
254      * @param def default value to be used if there are some problems during conversion
255      * @return boolean value
256      */

257     public static boolean toBool( String JavaDoc v, boolean def ) {
258         if( v == null ) return def;
259         return v.equalsIgnoreCase("TRUE") || v.equalsIgnoreCase("YES") || v.equalsIgnoreCase("1") || v.equalsIgnoreCase("ON");
260     }
261
262     /**
263      * Converts specified string to color.
264      *
265      * @param v string to be converted
266      * @param def default value to be used if there are some problems during conversion
267      * @return color
268      */

269     public static AlphaColor toColor( String JavaDoc v, AlphaColor def ) {
270         if( v == null || v.length() == 0 ) return def;
271         if( v.charAt(0) == '#' ) {
272             try {
273                 long rgba = Long.parseLong( v.substring(1), 16 );
274                 if( v.length() <= 7 ) rgba |= 0xff000000L; // + alpha
275
//System.out.println( v+"->"+Util.d2h((int)rgba) );
276
return new AlphaColor( (int) rgba );
277             } catch( NumberFormatException JavaDoc e ) {
278                 return def;
279             }
280         } else {
281             AlphaColor c = null;
282             try {
283                 int value = (int) Double.parseDouble(v);
284                 c = new AlphaColor(value);
285                 c.setAlpha(0xFF);
286             } catch (NumberFormatException JavaDoc ex) {
287                 c = AlphaColor.getColor(v);
288             }
289             if( c == null ) return def;
290             return c;
291         }
292     }
293
294     /**
295      * Processes escapes in the specified string.
296      * <P>
297      * Escapes to be processed:<br>
298      * <UL>
299      * <LI>\n - newline
300      * <LI>\r - carriage return
301      * <LI>\0x... - hex value
302      * <LI>\0... - octal value
303      * </UL>
304      *
305      * @param line string to be processed
306      * @return escape-processed string
307      */

308     public static String JavaDoc processEscapes( String JavaDoc line ) {
309
310         if( line == null ) return null;
311         int cur = line.indexOf('\\');
312         if( cur < 0 ) return line;
313
314         int length = line.length();
315         StringBuffer JavaDoc sb = new StringBuffer JavaDoc( line );
316         sb.setLength( cur++ );
317
318         for(; cur < length; ) {
319             char ch = line.charAt(cur);
320             switch( ch ) {
321                 case 'n':
322                     sb.append('\n');
323                     break;
324                 case 'r':
325                     sb.append('\r');
326                     break;
327                 case '0':
328                     cur++;
329                     if( cur >= length ) sb.append( 0 );
330                     else {
331                         if( line.charAt(cur) == 'x' || line.charAt(cur) == 'X' ) {
332                             // hex
333
int code = 0;;
334                             for( int l=++cur; cur<length && cur-l<4; cur++ ) {
335                                 char c = line.charAt(cur);
336                                 if( c >= '0' && c <= '9' ) {
337                                     code = (code<<4) + (c-'0');
338                                 } else if( c >= 'a' && c <= 'f' ) {
339                                     code = (code<<4) + (c-'a'+10);
340                                 } else if( c >= 'A' && c <= 'F' ) {
341                                     code = (code<<4) + (c-'A'+10);
342                                 } else {
343                                     break;
344                                 }
345                             }
346                             cur--;
347                             sb.append( (char) code );
348                         } else {
349                             // oct
350
int code = 0;;
351                             for( int l=cur; cur<length && cur-l<6; cur++ ) {
352                                 char c = line.charAt(cur);
353                                 if( c >= '0' && c <= '7' ) {
354                                     code = (code<<3) + (c-'0');
355                                 } else {
356                                     break;
357                                 }
358                             }
359                             cur--;
360                             sb.append( (char) code );
361                         }
362                     }
363                     break;
364                 default:
365                     sb.append(ch);
366                     break;
367             }
368             cur++;
369             int end = line.indexOf( '\\', cur );
370             if( end < 0 ) {
371                 sb.append( line.substring( cur, length) );
372                 break;
373             }
374             int l = end-cur;
375             if( l == 0 ) {
376                 cur++;
377             } else {
378                 sb.append( line.substring( cur, end) );
379                 cur = end+1;
380             }
381         }
382
383         return new String JavaDoc( sb );
384     }
385
386     /**
387      * Converts byte to unsigned byte.
388      */

389     public static int getUByte(byte a) {
390         return a & 0xff;
391     }
392
393     /**
394      * Creates signed word from two bytes.
395      *
396      * @param a low byte
397      * @param b high byte
398      * @return signed word
399      */

400     public static int getWord(byte a, byte b) {
401         return (a&0xff) | (b << 8);
402     }
403
404     /**
405      * Creates unsigned word from two bytes.
406      *
407      * @param a low byte
408      * @param b high byte
409      * @return unsigned word
410      */

411     public static int getUWord(byte a, byte b) {
412         return (a&0xff) | ((b&0xff) << 8);
413     }
414
415     /**
416      * Creates signed dword from four bytes.
417      *
418      * @param a 0 byte (low)
419      * @param b 1 byte
420      * @param c 2 byte
421      * @param d 3 byte (high)
422      * @return signed dword
423      */

424     public static int getDWord(byte a, byte b, byte c, byte d) {
425         return (a&0xff) | ((b&0xff) << 8) | ((c&0xff) << 16) | (d << 24);
426     }
427
428     /**
429      * Creates unsigned dword from four bytes.
430      *
431      * @param a 0 byte (low)
432      * @param b 1 byte
433      * @param c 2 byte
434      * @param d 3 byte (high)
435      * @return unsigned dword
436      */

437     public static int getUDWord(byte a, byte b, byte c, byte d) {
438         return (a&0xff) | ((b&0xff) << 8) | ((c&0xff) << 16) | ((d&0xff) << 24);
439     }
440
441     /**
442      * Returns maximum element of array.
443      *
444      * @param arr array to be searched for maximum
445      * @param size size of the array
446      * @return maximim element of the array
447      */

448     public static int getMax( int[] arr, int size ) {
449         int max = Integer.MIN_VALUE;
450         for( int i=0; i<size; i++ ) {
451             if( arr[i] > max ) max = arr[i];
452         }
453         return max;
454     }
455
456     /**
457      * Returns maximum element of array.
458      *
459      * @param arr array to be searched for maximum
460      * @return maximim element of the array
461      */

462     public static int getMax( int[] arr ) {
463         return getMax( arr, arr.length );
464     }
465
466     /**
467      * Returns maximum of absolute values of two numbers.
468      *
469      * @param a specified number
470      * @param b specified number
471      * @return maximum of two numbers
472      */

473     public static int getMax( int a, int b ) {
474         if( a < 0 ) a = -a;
475         if( b < 0 ) b = -b;
476         if( a >= b ) return a;
477         return b;
478     }
479
480     /**
481      * Returns maximum of absolute values of three numbers.
482      *
483      * @param a specified number
484      * @param b specified number
485      * @param c specified number
486      * @return maximum of three numbers
487      */

488     public static int getMax( int a, int b, int c ) {
489         if( a < 0 ) a = -a;
490         if( b < 0 ) b = -b;
491         if( c < 0 ) c = -c;
492         if( a >= b && a >= c ) return a;
493         if( b >= a && b >= c ) return b;
494         return c;
495     }
496
497     /**
498      * Returns maximum of absolute values of four numbers.
499      *
500      * @param a specified number
501      * @param b specified number
502      * @param c specified number
503      * @param d specified number
504      * @return maximum of four specified numbers
505      */

506     public static int getMax( int a, int b, int c, int d ) {
507         if( a < 0 ) a = -a;
508         if( b < 0 ) b = -b;
509         if( c < 0 ) c = -c;
510         if( d < 0 ) d = -d;
511
512         if( a > b ) {
513             if( a > c ) {
514                 if( a > d ) {
515                     return a;
516                 } else {
517                     return d;
518                 }
519             } else {
520                 if( c > d ) {
521                     return c;
522                 } else {
523                     return d;
524                 }
525             }
526         } else {
527             if( b > c ) {
528                 if( b > d ) {
529                     return b;
530                 } else {
531                     return d;
532                 }
533             } else {
534                 if( c > d ) {
535                     return c;
536                 } else {
537                     return d;
538                 }
539             }
540         }
541     }
542
543     /**
544      * Returns number of significant bits for signed integer.
545      *
546      * @param v signed integer
547      * @return number of significant bits for signed integer
548      */

549     public static int getMinBitsS( int v ) {
550         if( v < 0 ) v = -v;
551         return getMinBitsU( v )+1;
552     }
553
554     private static final int[] BITS_LENGTH = {
555     // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
556
0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4
557     };
558
559     /**
560      * Returns number of significant bits for unsigned integer.
561      *
562      * @param v unsigned integer
563      * @return number of significant bits for unsigned integer
564      */

565     public static int getMinBitsU( int v ) {
566         int n = 0;
567         if( (v & ~0xffff) != 0 ) {
568             n+=16; v >>>= 16;
569         }
570         if( (v & ~0x00ff) != 0 ) {
571             n+= 8; v >>>= 8;
572         }
573         if( (v & ~0x000f) != 0 ) {
574             n+= 4; v >>>= 4;
575         }
576         // for( ; v != 0; n++ ) v >>>= 1;
577
n += BITS_LENGTH[v];
578         return n;
579     }
580
581     /* --------------------------------------------------------------------------
582      * Double, float, fixed, twips conversion helpers
583      * -------------------------------------------------------------------------- */

584
585     private static final double FRACTION_DBL = (double) 0x10000;
586     private static final float FRACTION_FLT = (float) 0x10000;
587
588     /**
589      * Converts fixed Flash value into double
590      *
591      * @param value fixed Flash value
592      * @return double value
593      */

594     public static double fixed2double( int value ) {
595         return (double)value / FRACTION_DBL;
596     }
597
598     /**
599      * Converts fixed Flash value into float
600      *
601      * @param value fixed Flash value
602      * @return float value
603      */

604     public static float fixed2float( int value ) {
605         return (float)value / FRACTION_FLT;
606     }
607
608     /**
609      * Converts double to fixed value
610      *
611      * @param value double value
612      * @return fixed value
613      */

614     public static int double2fixed( double value ) {
615         return (int) (value * FRACTION_DBL);
616     }
617
618     /**
619      * Converts float to fixed value
620      *
621      * @param value float value
622      * @return fixed value
623      */

624     public static int float2fixed( float value ) {
625         return (int) (value * FRACTION_FLT);
626     }
627
628     /**
629      * Converts twips to double
630      *
631      * @param value twips value
632      * @return double value
633      */

634     public static double twips2double( int value ) {
635         return (double)value / 20.0;
636     }
637
638     /**
639      * Converts twips to float
640      *
641      * @param value twips value
642      * @return float value
643      */

644     public static float twips2float( int value ) {
645         return (float)value / 20.0f;
646     }
647
648     /**
649      * Converts double to twips
650      *
651      * @param value double value
652      * @return twips value
653      */

654     public static int double2twips( double value ) {
655         return (int) (value * 20.0);
656     }
657
658     /**
659      * Converts float to twips
660      *
661      * @param value float value
662      * @return twips value
663      */

664     public static int float2twips( float value ) {
665         return (int) (value * 20.0f);
666     }
667
668     private static final char[] digits = {
669         '0' , '1' , '2' , '3' , '4' , '5' ,
670         '6' , '7' , '8' , '9' , 'a' , 'b' ,
671         'c' , 'd' , 'e' , 'f'
672     };
673
674     /**
675      * Returns hexadecimal representation of specified byte
676      *
677      * @param v specified byte
678      * @return hex repsentation of specified byte
679      */

680     public static String JavaDoc b2h( int v ) {
681         char[] r = new char[2];
682         r[0] = digits[ (v&0xf0)>>4 ];
683         r[1] = digits[ (v&0x0f) ];
684         return new String JavaDoc( r );
685     }
686
687     /**
688      * Returns hexadecimal representation of specified word
689      *
690      * @param v specified word
691      * @return hex repsentation of specified word
692      */

693     public static String JavaDoc w2h( int v ) {
694         char[] r = new char[4];
695         r[0] = digits[ (v&0xf000)>>12 ];
696         r[1] = digits[ (v&0x0f00)>>8 ];
697         r[2] = digits[ (v&0x00f0)>>4 ];
698         r[3] = digits[ (v&0x000f) ];
699         return new String JavaDoc( r );
700     }
701
702     /**
703      * Returns hexadecimal representation of specified dword
704      *
705      * @param v specified dword
706      * @return hex repsentation of specified dword
707      */

708     public static String JavaDoc d2h( int v ) {
709         char[] r = new char[8];
710         r[0] = digits[ (v&0xf0000000)>>>28 ];
711         r[1] = digits[ (v&0x0f000000)>>24 ];
712         r[2] = digits[ (v&0x00f00000)>>20 ];
713         r[3] = digits[ (v&0x000f0000)>>16 ];
714         r[4] = digits[ (v&0x0000f000)>>12 ];
715         r[5] = digits[ (v&0x00000f00)>>8 ];
716         r[6] = digits[ (v&0x000000f0)>>4 ];
717         r[7] = digits[ (v&0x0000000f) ];
718         return new String JavaDoc( r );
719     }
720
721     /**
722      * Returns specified char if it's printable or '.'
723      *
724      * @param ch char to be converted to printable char
725      * @return printable char
726      */

727     public static char toPrint( char ch ) {
728         if( Character.isISOControl(ch) ) return '.';
729         return ch;
730     }
731
732     private static void _dump( byte[] buffer, int pos, int size, PrintStream out ) {
733         if( size == 0 ) return;
734         for( int i=0; i<16; i++ ) {
735             if( i >= size ) {
736                 out.print( ".. " );
737             } else {
738                 out.print( b2h(buffer[pos+i])+' ' );
739             }
740         }
741         for( int i=0; i<16; i++ ) {
742             if( i >= size ) {
743                 out.print( " " );
744             } else {
745                 out.print( toPrint( (char) buffer[pos+i] ) );
746             }
747         }
748     }
749
750     /**
751      * Prints hex dump of part of byte array to specified stream
752      *
753      * @param buffer buffer to be dumped
754      * @param start offset in the buffer to start the dump from
755      * @param size size of the dumped area
756      * @param out stream to print the dump to
757      */

758     public static void dump( byte[] buffer, int start, int size, PrintStream out ) {
759         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
760         int pos = 0;
761         for( int i=0; i<size/16; i++ ) {
762             _dump( buffer, start+pos, 16, out );
763             pos += 16;
764             out.println();
765         }
766         _dump( buffer, start+pos, size-pos, out );
767         out.println();
768     }
769
770     /**
771      * Returns whether specified string has generator variable or not.
772      *
773      * @param s string to be searched for generator variable
774      * @return true if the specified string has generator variable
775      */

776     public static boolean hasVar( String JavaDoc s ) {
777         return s != null && s.indexOf('{') != -1;
778     }
779
780     /**
781      * Returns concatenation of path and filename.
782      *
783      * @param path path
784      * @param name filename
785      * @return concatenation of specified path and specified filename
786      */

787     public static String JavaDoc concatFileNames( String JavaDoc path, String JavaDoc name ) {
788         if( path.length() == 0 ) return name;
789         char ch = path.charAt( path.length()-1 );
790         if( ch != '\\' && ch != '/' ) path += fileSeparator;
791         if( name.charAt(0) == '/' || name.charAt(0) == '\\' ) return path+name.substring(1);
792         return path+name;
793     }
794
795     /**
796      * Returns directory where jgenerator is installed
797      *
798      * @return directory where jgenerator is installed
799      */

800     public static String JavaDoc getInstallDir() {
801         if( installDir == null ) {
802             init();
803         }
804         return installDir;
805     }
806
807     /**
808      * Returns jgenerator file by its name.
809      * <P>
810      * If name is relative returns absolute path constructing
811      * with {@link #installDir} and the specified name
812      *
813      * @param name file name
814      * @return jgenerator absolute file
815      */

816     public static File getSysFile( String JavaDoc name ) {
817         name = translatePath( name );
818         File file = new File( name );
819         if( file.isAbsolute() ) return file;
820         return new File( installDir, name );
821     }
822
823     /**
824      * Translates file separator in the specified string into
825      * file separator of the system jgenerator is running on.
826      *
827      * @param path path to be translated
828      * @return translated path
829      */

830     public static String JavaDoc translatePath( String JavaDoc path ) {
831         if( fileSeparator == '\\' ) {
832             path = path.replace('/', '\\');
833         } else if( fileSeparator == '/' ) {
834             path = path.replace('\\', '/');
835         }
836         return path;
837     }
838
839     /**
840      * Creates URL from specified file.
841      *
842      * @param file file to be used to create URL
843      * @return created URL from File
844      * @exception MalformedURLException
845      */

846     public static URL toURL( File file ) throws MalformedURLException {
847         String JavaDoc path = file.getAbsolutePath();
848         if( fileSeparator != '/' ) {
849             path = path.replace( fileSeparator, '/' );
850         }
851         if( path.charAt(0) != '/' ) {
852             path = '/'+path;
853         }
854         if( !path.endsWith("/") && file.isDirectory() ) {
855             path = path+'/';
856         }
857         return new URL("file", "", path);
858     }
859
860     /**
861      * Reads data from specified url into FlashBuffer.
862      *
863      * @param url IVUrl to read from
864      * @return FlashBuffer with data read
865      * @exception IOException
866      */

867     public static FlashBuffer readUrl( IVUrl url ) throws IOException {
868         FlashBuffer fob = null;
869         InputStream is = null;
870         try {
871             is = url.getInputStream();
872             fob = new FlashBuffer( is );
873         } finally {
874             try {
875                 if( is != null ) is.close();
876             } catch( Exception JavaDoc e ) {}
877         }
878
879         return fob;
880     }
881
882     /**
883      * Creates new instance of an specified class
884      *
885      * @param className specified class name
886      * @param parmsCls parameters types of constructor
887      * @param parms parameters of constructor
888      * @return new instance
889      * @exception Exception
890      */

891     public static Object JavaDoc newInstance( String JavaDoc className, Class JavaDoc[] parmsCls, Object JavaDoc[] parms ) throws Exception JavaDoc {
892         Class JavaDoc clazz = Class.forName(className);
893         if( parmsCls == null ) {
894             return clazz.newInstance();
895         } else {
896             Constructor constr = clazz.getConstructor(parmsCls);
897             return constr.newInstance(parms);
898         }
899     }
900
901     /**
902      * Executes specified javascript text in given Context
903      *
904      * @param context specified context
905      * @param js_text javascript text
906      * @param parms parameters for javascript
907      * @return result of "printing" in javascript
908      */

909     public static String JavaDoc executeJSString( Context context, String JavaDoc js_text, String JavaDoc[] parms ) {
910         return executeJSHelperMethod("execString", context, js_text, parms);
911     }
912
913     /**
914      * Executes specified javascript file in given Context
915      *
916      * @param context specified context
917      * @param js_text javascript text
918      * @param parms parameters for javascript
919      * @return result of "printing" in javascript
920      */

921     public static String JavaDoc executeJSFile( Context context, String JavaDoc fileName, String JavaDoc[] parms ) {
922         return executeJSHelperMethod("execFile", context, fileName, parms);
923     }
924
925     private static String JavaDoc executeJSHelperMethod( String JavaDoc method, Context context, String JavaDoc s, String JavaDoc[] parms ) {
926         FlashBuffer fb = new FlashBuffer(400);
927         try {
928             PrintStream out = new PrintStream(fb.getOutputStream());
929             Class JavaDoc clazz = Class.forName("org.openlaszlo.iv.flash.js.JSHelper");
930             Method exec = clazz.getMethod(method,
931                                     new Class JavaDoc[] {String JavaDoc.class, String JavaDoc[].class,
932                                                  PrintStream.class, Context.class});
933             exec.invoke(null, new Object JavaDoc[] {s, parms, out, context});
934             out.flush();
935             return fb.toString();
936         } catch( Throwable JavaDoc e ) {
937             Log.log(e);
938             return null;
939         }
940     }
941
942     /**
943      * Parses parameters of url-string begining after the specified index (usually index of '?')
944      * <p>
945      * Parameters are pairs: name=value, separated by ampersand
946      *
947      * @param s url
948      * @param idx specified index
949      * @return hashtable of parameter
950      * @exception IVException
951      */

952     public static Hashtable parseUrlParms( String JavaDoc s, int idx ) {
953         s = s.substring(idx+1);
954         Hashtable parms = new Hashtable();
955         StringTokenizer st = new StringTokenizer(s,"&");
956         while( st.hasMoreTokens() ) {
957             String JavaDoc token = st.nextToken();
958             idx = token.indexOf('=');
959             if( idx == -1 ) {
960                 parms.put(decodeURLEncoded(token).toLowerCase(), "");
961             } else {
962                 String JavaDoc name = decodeURLEncoded(token.substring(0, idx)).toLowerCase();
963                 String JavaDoc value = decodeURLEncoded(token.substring(idx+1));
964                 parms.put(name, value);
965             }
966         }
967         return parms;
968     }
969
970     /**
971      * Decodes url-encoded string
972      *
973      * @param s url-encoded string
974      * @return decoded string
975      */

976     public static String JavaDoc decodeURLEncoded( String JavaDoc s ) {
977         if( s.indexOf('+')<0 && s.indexOf('%')<0 ) return s;
978
979         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(s.length());
980         for( int i=0; i<s.length(); i++ ) {
981             char ch = s.charAt(i);
982             if( ch == '+' ) {
983                 sb.append(' ');
984             } else if( ch == '%' ) {
985                 ch = (char) Integer.parseInt(s.substring(i+1,i+3), 16);
986                 sb.append(ch);
987                 i+=2;
988             } else {
989                 sb.append(ch);
990             }
991         }
992         return new String JavaDoc(sb);
993     }
994
995     /**
996      * Returns Reader of specified IVUrl using encoding either
997      * from specified IVUrl or specified FlashFile
998      *
999      * @param file file
1000     * @param url url
1001     * @return Reader
1002     */

1003    public static LineReader getUrlReader( FlashFile file, IVUrl url ) throws IOException {
1004        String JavaDoc encoding;
1005
1006        String JavaDoc url_encoding = url.getEncoding();
1007        if( url_encoding != null ) {
1008            encoding = url_encoding;
1009        } else {
1010            encoding = file == null? null: file.getEncoding();
1011            if( encoding == null ) {
1012                encoding = PropertyManager.defaultEncoding;
1013            }
1014        }
1015
1016        return getInputStreamReader(url.getInputStream(), encoding);
1017    }
1018
1019    /**
1020     * Returns Reader of specified String using encoding from specified FlashFile
1021     *
1022     * @param file file
1023     * @param buf buffer
1024     * @param offset offset in the buffer
1025     * @param length buffer length
1026     * @return reader
1027     * @exception IOException
1028     */

1029    public static LineReader getArrayReader( FlashFile file, byte[] buf, int offset, int length ) throws IOException {
1030
1031        String JavaDoc encoding = file == null? null: file.getEncoding();
1032        if( encoding == null ) {
1033            encoding = PropertyManager.defaultEncoding;
1034        }
1035
1036        return getInputStreamReader(new ByteArrayInputStream(buf, offset, length), encoding);
1037    }
1038
1039    /**
1040     * Returns BufferedReader of specified InputStream and encoding
1041     *
1042     * @param is input stream
1043     * @param encoding encoding (may be null)
1044     * @return reader
1045     */

1046    public static LineReader getInputStreamReader( InputStream is, String JavaDoc encoding ) throws IOException {
1047        Reader reader = null;
1048        if( encoding != null ) {
1049            try {
1050                reader = new InputStreamReader(is, encoding);
1051            } catch( UnsupportedEncodingException e ) {
1052                Log.log(e);
1053                // fall through
1054
}
1055        }
1056
1057        if( reader == null ) {
1058            reader = new InputStreamReader(is);
1059        }
1060
1061        return new BufferedLineReader(new BufferedReader(reader));
1062    }
1063
1064    /**
1065     * Returns version of JGenerator.
1066     *
1067     * @return version of JGenerator
1068     */

1069    public static String JavaDoc getVersion() {
1070        return genVersion;
1071    }
1072
1073}
1074
Popular Tags