2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
26 package org.forester.util;
28 import java.awt.Color;
29 import java.io.BufferedReader;
30 import java.io.BufferedWriter;
32 import java.io.FileInputStream;
33 import java.io.FileNotFoundException;
34 import java.io.FileOutputStream;
35 import java.io.FileReader;
36 import java.io.FileWriter;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.InputStreamReader;
40 import java.io.StringReader;
41 import java.io.Writer;
42 import java.math.BigDecimal;
44 import java.text.DateFormat;
45 import java.text.DecimalFormat;
46 import java.text.DecimalFormatSymbols;
47 import java.text.NumberFormat;
48 import java.text.ParseException;
49 import java.text.SimpleDateFormat;
50 import java.util.ArrayList;
51 import java.util.Collection;
52 import java.util.Date;
53 import java.util.Iterator;
54 import java.util.List;
56 import java.util.Map.Entry;
58 import java.util.SortedMap;
59 import java.util.SortedSet;
60 import java.util.TreeMap;
61 import java.util.TreeSet;
62 import java.util.regex.Pattern;
64 public final class ForesterUtil {
66 public final static String FILE_SEPARATOR = System.getProperty( "file.separator" );
67 public final static String LINE_SEPARATOR = System.getProperty( "line.separator" );
68 public final static String JAVA_VENDOR = System.getProperty( "java.vendor" );
69 public final static String JAVA_VERSION = System.getProperty( "java.version" );
70 public final static String OS_ARCH = System.getProperty( "os.arch" );
71 public final static String OS_NAME = System.getProperty( "os.name" );
72 public final static String OS_VERSION = System.getProperty( "os.version" );
73 public final static Pattern PARANTHESESABLE_NH_CHARS_PATTERN = Pattern.compile( "[(),;\\s]" );
74 public final static double ZERO_DIFF = 1.0E-9;
75 public static final BigDecimal NULL_BD = new BigDecimal( 0 );
76 public static final NumberFormat FORMATTER_9;
77 public static final NumberFormat FORMATTER_6;
78 public static final NumberFormat FORMATTER_06;
79 public static final NumberFormat FORMATTER_3;
81 final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
82 dfs.setDecimalSeparator( '.' );
83 // dfs.setGroupingSeparator( ( char ) 0 );
84 FORMATTER_9 = new DecimalFormat( "#.#########", dfs );
85 FORMATTER_6 = new DecimalFormat( "#.######", dfs );
86 FORMATTER_06 = new DecimalFormat( "0.######", dfs );
87 FORMATTER_3 = new DecimalFormat( "#.###", dfs );
90 private ForesterUtil() {
93 final public static void appendSeparatorIfNotEmpty( final StringBuffer sb, final char separator ) {
94 if ( sb.length() > 0 ) {
95 sb.append( separator );
100 * This calculates a color. If value is equal to min the returned color is
101 * minColor, if value is equal to max the returned color is maxColor,
102 * otherwise a color 'proportional' to value is returned.
116 final public static Color calcColor( double value,
119 final Color minColor,
120 final Color maxColor ) {
127 final double x = ForesterUtil.calculateColorFactor( value, max, min );
128 final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), maxColor.getRed(), x );
129 final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), maxColor.getGreen(), x );
130 final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), maxColor.getBlue(), x );
131 return new Color( red, green, blue );
135 * This calculates a color. If value is equal to min the returned color is
136 * minColor, if value is equal to max the returned color is maxColor, if
137 * value is equal to mean the returned color is meanColor, otherwise a color
138 * 'proportional' to value is returned -- either between min-mean or
148 * the mean/median value
157 final public static Color calcColor( double value,
161 final Color minColor,
162 final Color maxColor,
163 final Color meanColor ) {
170 if ( value < mean ) {
171 final double x = ForesterUtil.calculateColorFactor( value, mean, min );
172 final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), meanColor.getRed(), x );
173 final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), meanColor.getGreen(), x );
174 final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), meanColor.getBlue(), x );
175 return new Color( red, green, blue );
177 else if ( value > mean ) {
178 final double x = ForesterUtil.calculateColorFactor( value, max, mean );
179 final int red = ForesterUtil.calculateColorComponent( meanColor.getRed(), maxColor.getRed(), x );
180 final int green = ForesterUtil.calculateColorComponent( meanColor.getGreen(), maxColor.getGreen(), x );
181 final int blue = ForesterUtil.calculateColorComponent( meanColor.getBlue(), maxColor.getBlue(), x );
182 return new Color( red, green, blue );
190 * Helper method for calcColor methods.
192 * @param smallercolor_component_x
193 * color component the smaller color
194 * @param largercolor_component_x
195 * color component the larger color
198 * @return an int representing a color component
200 final private static int calculateColorComponent( final double smallercolor_component_x,
201 final double largercolor_component_x,
203 return ( int ) ( smallercolor_component_x + ( ( x * ( largercolor_component_x - smallercolor_component_x ) ) / 255.0 ) );
207 * Helper method for calcColor methods.
216 * @return a normalized value between larger and smaller
218 final private static double calculateColorFactor( final double value, final double larger, final double smaller ) {
219 return ( 255.0 * ( value - smaller ) ) / ( larger - smaller );
222 final public static String collapseWhiteSpace( final String s ) {
223 return s.replaceAll( "[\\s]+", " " );
226 final public static void collection2file( final File file, final Collection<?> data, final String separator )
228 final Writer writer = new BufferedWriter( new FileWriter( file ) );
229 collection2writer( writer, data, separator );
233 final public static void collection2writer( final Writer writer, final Collection<?> data, final String separator )
235 boolean first = true;
236 for( final Object object : data ) {
238 writer.write( separator );
243 writer.write( object.toString() );
247 final public static String colorToHex( final Color color ) {
248 final String rgb = Integer.toHexString( color.getRGB() );
249 return rgb.substring( 2, rgb.length() );
252 synchronized public static void copyFile( final File in, final File out ) throws IOException {
253 final FileInputStream in_s = new FileInputStream( in );
254 final FileOutputStream out_s = new FileOutputStream( out );
256 final byte[] buf = new byte[ 1024 ];
258 while ( ( i = in_s.read( buf ) ) != -1 ) {
259 out_s.write( buf, 0, i );
262 catch ( final IOException e ) {
266 if ( in_s != null ) {
269 if ( out_s != null ) {
275 final public static int countChars( final String str, final char c ) {
277 for( int i = 0; i < str.length(); ++i ) {
278 if ( str.charAt( i ) == c ) {
285 final public static BufferedWriter createBufferedWriter( final File file ) throws IOException {
286 if ( file.exists() ) {
287 throw new IOException( "[" + file + "] already exists" );
289 return new BufferedWriter( new FileWriter( file ) );
292 final public static BufferedWriter createBufferedWriter( final String name ) throws IOException {
293 return new BufferedWriter( new FileWriter( createFileForWriting( name ) ) );
296 final public static File createFileForWriting( final String name ) throws IOException {
297 final File file = new File( name );
298 if ( file.exists() ) {
299 throw new IOException( "[" + name + "] already exists" );
304 public static void fatalError( final String prg_name, final String message ) {
305 System.err.println();
306 System.err.println( "[" + prg_name + "] > " + message );
307 System.err.println();
311 public static String[] file2array( final File file ) throws IOException {
312 final List<String> list = file2list( file );
313 final String[] ary = new String[ list.size() ];
315 for( final String s : list ) {
321 final public static List<String> file2list( final File file ) throws IOException {
322 final List<String> list = new ArrayList<String>();
323 final BufferedReader in = new BufferedReader( new FileReader( file ) );
325 while ( ( str = in.readLine() ) != null ) {
327 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
328 for( final String s : splitString( str ) ) {
337 final public static SortedSet<String> file2set( final File file ) throws IOException {
338 final SortedSet<String> set = new TreeSet<String>();
339 final BufferedReader in = new BufferedReader( new FileReader( file ) );
341 while ( ( str = in.readLine() ) != null ) {
343 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
344 for( final String s : splitString( str ) ) {
353 final public static String getCurrentDateTime() {
354 final DateFormat format = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
355 return format.format( new Date() );
358 final public static String getFileSeparator() {
359 return ForesterUtil.FILE_SEPARATOR;
362 final public static String getFirstLine( final Object source ) throws FileNotFoundException, IOException {
363 BufferedReader reader = null;
364 if ( source instanceof File ) {
365 final File f = ( File ) source;
367 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
369 else if ( !f.isFile() ) {
370 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
372 else if ( !f.canRead() ) {
373 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
375 reader = new BufferedReader( new FileReader( f ) );
377 else if ( source instanceof InputStream ) {
378 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
380 else if ( source instanceof String ) {
381 reader = new BufferedReader( new StringReader( ( String ) source ) );
383 else if ( source instanceof StringBuffer ) {
384 reader = new BufferedReader( new StringReader( source.toString() ) );
386 else if ( source instanceof URL ) {
387 reader = new BufferedReader( new InputStreamReader( ( ( URL ) source ).openStream() ) );
390 throw new IllegalArgumentException( "dont know how to read [" + source.getClass() + "]" );
393 while ( ( line = reader.readLine() ) != null ) {
395 if ( !ForesterUtil.isEmpty( line ) ) {
396 if ( reader != null ) {
402 if ( reader != null ) {
408 final public static String getLineSeparator() {
409 return ForesterUtil.LINE_SEPARATOR;
412 final public static void increaseCountingMap( final Map<String, Integer> counting_map, final String item_name ) {
413 if ( !counting_map.containsKey( item_name ) ) {
414 counting_map.put( item_name, 1 );
417 counting_map.put( item_name, counting_map.get( item_name ) + 1 );
421 final public static boolean isContainsParanthesesableNhCharacter( final String nh ) {
422 return PARANTHESESABLE_NH_CHARS_PATTERN.matcher( nh ).find();
425 final public static boolean isEmpty( final List<?> l ) {
426 if ( ( l == null ) || l.isEmpty() ) {
429 for( final Object o : l ) {
437 final public static boolean isEmpty( final Set<?> s ) {
438 if ( ( s == null ) || s.isEmpty() ) {
441 for( final Object o : s ) {
449 final public static boolean isEmpty( final String s ) {
450 return ( ( s == null ) || ( s.length() < 1 ) );
453 final public static boolean isEqual( final double a, final double b ) {
454 return ( ( Math.abs( a - b ) ) < ZERO_DIFF );
457 final public static boolean isEven( final int n ) {
462 * This determines whether String[] a and String[] b have at least one
463 * String in common (intersect). Returns false if at least one String[] is
467 * a String[] b a String[]
468 * @return true if both a and b or not empty or null and contain at least
469 * one element in common false otherwise
471 final public static boolean isIntersecting( final String[] a, final String[] b ) {
472 if ( ( a == null ) || ( b == null ) ) {
475 if ( ( a.length < 1 ) || ( b.length < 1 ) ) {
478 for( int i = 0; i < a.length; ++i ) {
479 final String ai = a[ i ];
480 for( int j = 0; j < b.length; ++j ) {
481 if ( ( ai != null ) && ( b[ j ] != null ) && ai.equals( b[ j ] ) ) {
489 final public static double isLargerOrEqualToZero( final double d ) {
498 final public static boolean isNull( final BigDecimal s ) {
499 return ( ( s == null ) || ( s.compareTo( NULL_BD ) == 0 ) );
502 final public static String isReadableFile( final File f ) {
504 return "file [" + f + "] does not exist";
506 if ( f.isDirectory() ) {
507 return "[" + f + "] is a directory";
510 return "[" + f + "] is not a file";
512 if ( !f.canRead() ) {
513 return "file [" + f + "] is not readable";
515 if ( f.length() < 1 ) {
516 return "file [" + f + "] is empty";
521 final public static String isReadableFile( final String s ) {
522 return isReadableFile( new File( s ) );
525 final public static String isWritableFile( final File f ) {
526 if ( f.isDirectory() ) {
527 return "[" + f + "] is a directory";
530 return "[" + f + "] already exists";
536 * Helper for method "stringToColor".
538 * (Last modified: 12/20/03)
540 final public static int limitRangeForColor( int i ) {
550 final public static SortedMap<Object, Integer> listToSortedCountsMap( final List list ) {
551 final SortedMap<Object, Integer> map = new TreeMap<Object, Integer>();
552 for( final Object key : list ) {
553 if ( !map.containsKey( key ) ) {
557 map.put( key, map.get( key ) + 1 );
563 final public static void map2file( final File file,
564 final Map<?, ?> data,
565 final String entry_separator,
566 final String data_separator ) throws IOException {
567 final Writer writer = new BufferedWriter( new FileWriter( file ) );
568 map2writer( writer, data, entry_separator, data_separator );
572 final public static void map2writer( final Writer writer,
573 final Map<?, ?> data,
574 final String entry_separator,
575 final String data_separator ) throws IOException {
576 boolean first = true;
577 for( final Entry<?, ?> entry : data.entrySet() ) {
579 writer.write( data_separator );
584 writer.write( entry.getKey().toString() );
585 writer.write( entry_separator );
586 writer.write( entry.getValue().toString() );
590 final public static StringBuffer mapToStringBuffer( final Map map, final String key_value_separator ) {
591 final StringBuffer sb = new StringBuffer();
592 for( final Iterator iter = map.keySet().iterator(); iter.hasNext(); ) {
593 final Object key = iter.next();
594 sb.append( key.toString() );
595 sb.append( key_value_separator );
596 sb.append( map.get( key ).toString() );
597 sb.append( ForesterUtil.getLineSeparator() );
602 final public static String normalizeString( final String s,
604 final boolean left_pad,
605 final char pad_char ) {
606 if ( s.length() > length ) {
607 return s.substring( 0, length );
610 final StringBuffer pad = new StringBuffer( length - s.length() );
611 for( int i = 0; i < ( length - s.length() ); ++i ) {
612 pad.append( pad_char );
623 final public static BufferedReader obtainReader( final Object source ) throws IOException, FileNotFoundException {
624 BufferedReader reader = null;
625 if ( source instanceof File ) {
626 final File f = ( File ) source;
628 throw new IOException( "\"" + f.getAbsolutePath() + "\" does not exist" );
630 else if ( !f.isFile() ) {
631 throw new IOException( "\"" + f.getAbsolutePath() + "\" is not a file" );
633 else if ( !f.canRead() ) {
634 throw new IOException( "\"" + f.getAbsolutePath() + "\" is not a readable" );
636 reader = new BufferedReader( new FileReader( f ) );
638 else if ( source instanceof InputStream ) {
639 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
641 else if ( source instanceof String ) {
642 reader = new BufferedReader( new StringReader( ( String ) source ) );
644 else if ( source instanceof StringBuffer ) {
645 reader = new BufferedReader( new StringReader( source.toString() ) );
648 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
649 + "] (can only parse objects of type File, InputStream, String, or StringBuffer)" );
654 final public static StringBuffer pad( final double number, final int size, final char pad, final boolean left_pad ) {
655 return pad( new StringBuffer( number + "" ), size, pad, left_pad );
658 final public static StringBuffer pad( final String string, final int size, final char pad, final boolean left_pad ) {
659 return pad( new StringBuffer( string ), size, pad, left_pad );
662 final public static StringBuffer pad( final StringBuffer string,
665 final boolean left_pad ) {
666 final StringBuffer padding = new StringBuffer();
667 final int s = size - string.length();
669 return new StringBuffer( string.substring( 0, size ) );
671 for( int i = 0; i < s; ++i ) {
672 padding.append( pad );
675 return padding.append( string );
678 return string.append( padding );
682 final public static double parseDouble( final String str ) throws ParseException {
683 if ( ForesterUtil.isEmpty( str ) ) {
686 return Double.parseDouble( str );
689 final public static int parseInt( final String str ) throws ParseException {
690 if ( ForesterUtil.isEmpty( str ) ) {
693 return Integer.parseInt( str );
696 final public static void printArray( final Object[] a ) {
697 for( int i = 0; i < a.length; ++i ) {
698 System.out.println( "[" + i + "]=" + a[ i ] );
702 final public static void printCountingMap( final Map<String, Integer> counting_map ) {
703 for( final String key : counting_map.keySet() ) {
704 System.out.println( key + ": " + counting_map.get( key ) );
708 final public static void printErrorMessage( final String prg_name, final String message ) {
709 System.out.println( "[" + prg_name + "] > error: " + message );
712 final public static void printProgramInformation( final String prg_name, final String prg_version, final String date ) {
713 final int l = prg_name.length() + prg_version.length() + date.length() + 4;
714 System.out.println();
715 System.out.println( prg_name + " " + prg_version + " (" + date + ")" );
716 for( int i = 0; i < l; ++i ) {
717 System.out.print( "_" );
719 System.out.println();
722 final public static void printProgramInformation( final String prg_name,
723 final String prg_version,
727 final int l = prg_name.length() + prg_version.length() + date.length() + 4;
728 System.out.println();
729 System.out.println( prg_name + " " + prg_version + " (" + date + ")" );
730 for( int i = 0; i < l; ++i ) {
731 System.out.print( "_" );
733 System.out.println();
734 System.out.println();
735 System.out.println( "WWW : " + www );
736 System.out.println( "Contact: " + email );
737 if ( !ForesterUtil.isEmpty( ForesterUtil.JAVA_VERSION ) && !ForesterUtil.isEmpty( ForesterUtil.JAVA_VENDOR ) ) {
738 System.out.println();
739 System.out.println( "[running on Java " + ForesterUtil.JAVA_VERSION + " " + ForesterUtil.JAVA_VENDOR + "]" );
741 System.out.println();
744 final public static void printWarningMessage( final String prg_name, final String message ) {
745 System.out.println( "[" + prg_name + "] > warning: " + message );
748 final public static void programMessage( final String prg_name, final String message ) {
749 System.out.println( "[" + prg_name + "] > " + message );
752 final public static String removeSuffix( final String file_name ) {
753 final int i = file_name.lastIndexOf( '.' );
755 return file_name.substring( 0, i );
761 * Removes all white space from String s.
763 * @return String s with white space removed
765 final public static String removeWhiteSpace( String s ) {
767 for( i = 0; i <= s.length() - 1; i++ ) {
768 if ( ( s.charAt( i ) == ' ' ) || ( s.charAt( i ) == '\t' ) || ( s.charAt( i ) == '\n' )
769 || ( s.charAt( i ) == '\r' ) ) {
770 s = s.substring( 0, i ) + s.substring( i + 1 );
777 final public static String replaceIllegalNhCharacters( final String nh ) {
781 return nh.trim().replaceAll( "[\\[\\]:]+", "_" );
784 final public static String replaceIllegalNhxCharacters( final String nhx ) {
788 return nhx.trim().replaceAll( "[\\[\\](),:;\\s]+", "_" );
791 final public static double round( final double value, final int decimal_place ) {
792 BigDecimal bd = new BigDecimal( value );
793 bd = bd.setScale( decimal_place, BigDecimal.ROUND_HALF_UP );
794 return bd.doubleValue();
798 * Rounds d to an int.
800 final public static int roundToInt( final double d ) {
801 return ( int ) ( d + 0.5 );
804 final public static int roundToInt( final float f ) {
805 return ( int ) ( f + 0.5f );
808 final public static short roundToShort( final double d ) {
809 return ( short ) ( d + 0.5 );
812 final public static String sanitizeString( final String s ) {
821 final private static String[] splitString( final String str ) {
822 final String regex = "[\\s;,]+";
823 return str.split( regex );
826 final public static String stringArrayToString( final String[] a ) {
827 return stringArrayToString( a, ", " );
830 final public static String stringArrayToString( final String[] a, final String separator ) {
831 final StringBuilder sb = new StringBuilder();
832 if ( ( a != null ) && ( a.length > 0 ) ) {
833 for( int i = 0; i < a.length - 1; ++i ) {
834 sb.append( a[ i ] + separator );
836 sb.append( a[ a.length - 1 ] );
838 return sb.toString();
841 final public static String[] stringListToArray( final List<String> list ) {
842 if ( list != null ) {
843 final String[] str = new String[ list.size() ];
845 for( final String l : list ) {
853 final public static String stringListToString( final List<String> l, final String separator ) {
854 final StringBuilder sb = new StringBuilder();
855 if ( ( l != null ) && ( l.size() > 0 ) ) {
856 for( int i = 0; i < l.size() - 1; ++i ) {
857 sb.append( l.get( i ) + separator );
859 sb.append( l.get( l.size() - 1 ) );
861 return sb.toString();
864 final public static String[] stringSetToArray( final Set<String> strings ) {
865 final String[] str_array = new String[ strings.size() ];
867 for( final String e : strings ) {
868 str_array[ i++ ] = e;
873 final public static void unexpectedFatalError( final String prg_name, final Exception e ) {
874 System.err.println();
875 System.err.println( "[" + prg_name
876 + "] > unexpected error (Should not have occured! Please contact program author(s).)" );
877 e.printStackTrace( System.err );
878 System.err.println();
882 final public static void unexpectedFatalError( final String prg_name, final String message ) {
883 System.err.println();
884 System.err.println( "[" + prg_name
885 + "] > unexpected error. Should not have occured! Please contact program author(s)." );
886 System.err.println( message );
887 System.err.println();
891 final public static void unexpectedFatalError( final String prg_name, final String message, final Exception e ) {
892 System.err.println();
893 System.err.println( "[" + prg_name
894 + "] > unexpected error. Should not have occured! Please contact program author(s)." );
895 System.err.println( message );
896 e.printStackTrace( System.err );
897 System.err.println();
901 public final static String wordWrap( final String str, final int width ) {
902 final StringBuilder sb = new StringBuilder( str );
906 while ( i < sb.length() ) {
907 if ( sb.charAt( i ) == ' ' ) {
910 if ( sb.charAt( i ) == '\n' ) {
914 if ( i > start + width - 1 ) {
916 sb.setCharAt( ls, '\n' );
921 sb.insert( i, '\n' );
927 return sb.toString();