make PH, aPH, CL selection
[jalview.git] / forester / java / src / org / forester / util / ForesterUtil.java
index 84be63a..48d973b 100644 (file)
@@ -42,6 +42,8 @@ import java.io.Writer;
 import java.math.BigDecimal;
 import java.net.URL;
 import java.net.URLConnection;
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
 import java.text.DateFormat;
 import java.text.DecimalFormat;
 import java.text.DecimalFormatSymbols;
@@ -62,14 +64,19 @@ import java.util.TreeSet;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-import org.forester.archaeopteryx.Constants;
+import org.forester.archaeopteryx.AptxConstants;
+import org.forester.io.parsers.PhylogenyParser;
+import org.forester.phylogeny.Phylogeny;
 import org.forester.phylogeny.PhylogenyNode;
 import org.forester.phylogeny.data.Distribution;
 import org.forester.phylogeny.data.Sequence;
 import org.forester.phylogeny.data.Taxonomy;
+import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
 import org.forester.protein.BasicProtein;
 import org.forester.protein.Domain;
 import org.forester.protein.Protein;
+import org.forester.sequence.MolecularSequence;
+import org.forester.sequence.MolecularSequence.TYPE;
 import org.forester.surfacing.SurfacingUtil;
 
 public final class ForesterUtil {
@@ -103,9 +110,6 @@ public final class ForesterUtil {
         FORMATTER_3 = new DecimalFormat( "#.###", dfs );
     }
 
-    private ForesterUtil() {
-    }
-
     final public static void appendSeparatorIfNotEmpty( final StringBuffer sb, final char separator ) {
         if ( sb.length() > 0 ) {
             sb.append( separator );
@@ -116,13 +120,13 @@ public final class ForesterUtil {
      * This calculates a color. If value is equal to min the returned color is
      * minColor, if value is equal to max the returned color is maxColor,
      * otherwise a color 'proportional' to value is returned.
-     * 
+     *
      * @param value
-     *            the value 
+     *            the value
      * @param min
-     *            the smallest value 
+     *            the smallest value
      * @param max
-     *            the largest value 
+     *            the largest value
      * @param minColor
      *            the color for min
      * @param maxColor
@@ -153,15 +157,15 @@ public final class ForesterUtil {
      * value is equal to mean the returned color is meanColor, otherwise a color
      * 'proportional' to value is returned -- either between min-mean or
      * mean-max
-     * 
+     *
      * @param value
      *            the value
      * @param min
      *            the smallest value
      * @param max
-     *            the largest value 
+     *            the largest value
      * @param mean
-     *            the mean/median value 
+     *            the mean/median value
      * @param minColor
      *            the color for min
      * @param maxColor
@@ -202,6 +206,39 @@ public final class ForesterUtil {
         }
     }
 
+    /**
+     * Helper method for calcColor methods.
+     *
+     * @param smallercolor_component_x
+     *            color component the smaller color
+     * @param largercolor_component_x
+     *            color component the larger color
+     * @param x
+     *            factor
+     * @return an int representing a color component
+     */
+    final private static int calculateColorComponent( final double smallercolor_component_x,
+                                                      final double largercolor_component_x,
+                                                      final double x ) {
+        return ( int ) ( smallercolor_component_x + ( ( x * ( largercolor_component_x - smallercolor_component_x ) ) / 255.0 ) );
+    }
+
+    /**
+     * Helper method for calcColor methods.
+     *
+     *
+     * @param value
+     *            the value
+     * @param larger
+     *            the largest value
+     * @param smaller
+     *            the smallest value
+     * @return a normalized value between larger and smaller
+     */
+    final private static double calculateColorFactor( final double value, final double larger, final double smaller ) {
+        return ( 255.0 * ( value - smaller ) ) / ( larger - smaller );
+    }
+
     public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
         int overlap_count = 0;
         for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
@@ -495,6 +532,22 @@ public final class ForesterUtil {
         return ForesterUtil.LINE_SEPARATOR;
     }
 
+    final public static MolecularSequence.TYPE guessMolecularSequenceType( final String mol_seq ) {
+        if ( mol_seq.contains( "L" ) || mol_seq.contains( "I" ) || mol_seq.contains( "E" ) || mol_seq.contains( "H" )
+                || mol_seq.contains( "D" ) || mol_seq.contains( "Q" ) ) {
+            return TYPE.AA;
+        }
+        else {
+            if ( mol_seq.contains( "T" ) ) {
+                return TYPE.DNA;
+            }
+            else if ( mol_seq.contains( "U" ) ) {
+                return TYPE.RNA;
+            }
+        }
+        return null;
+    }
+
     final public static void increaseCountingMap( final Map<String, Integer> counting_map, final String item_name ) {
         if ( !counting_map.containsKey( item_name ) ) {
             counting_map.put( item_name, 1 );
@@ -535,7 +588,7 @@ public final class ForesterUtil {
     /**
      * Returns true is Domain domain falls in an uninterrupted stretch of
      * covered positions.
-     * 
+     *
      * @param domain
      * @param covered_positions
      * @return
@@ -561,7 +614,7 @@ public final class ForesterUtil {
      * This determines whether String[] a and String[] b have at least one
      * String in common (intersect). Returns false if at least one String[] is
      * null or empty.
-     * 
+     *
      * @param a
      *            a String[] b a String[]
      * @return true if both a and b or not empty or null and contain at least
@@ -598,7 +651,7 @@ public final class ForesterUtil {
             return OS_NAME.toLowerCase().startsWith( "mac" );
         }
         catch ( final Exception e ) {
-            ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
+            ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, "minor error: " + e );
             return false;
         }
     }
@@ -635,7 +688,7 @@ public final class ForesterUtil {
             return OS_NAME.toLowerCase().indexOf( "win" ) > -1;
         }
         catch ( final Exception e ) {
-            ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
+            ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, "minor error: " + e );
             return false;
         }
     }
@@ -921,7 +974,7 @@ public final class ForesterUtil {
         }
         else {
             throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
-                    + "] (can only parse objects of type File, InputStream, String, or StringBuffer)" );
+                                                + "] (can only parse objects of type File, InputStream, String, or StringBuffer)" );
         }
         return reader;
     }
@@ -1050,17 +1103,31 @@ public final class ForesterUtil {
         System.out.println( "[" + prg_name + "] > " + message );
     }
 
+    public static List<String> readUrl( final String url_str ) throws IOException {
+        final URL url = new URL( url_str );
+        final URLConnection urlc = url.openConnection();
+        //urlc.setRequestProperty( "User-Agent", "" );
+        final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
+        String line;
+        final List<String> result = new ArrayList<String>();
+        while ( ( line = in.readLine() ) != null ) {
+            result.add( line );
+        }
+        in.close();
+        return result;
+    }
+
     /**
-     * 
+     *
      * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
      * domain with 0.3 is ignored
-     * 
+     *
      * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
-     * 
-     * 
+     *
+     *
      * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
      * ignored
-     * 
+     *
      * @param max_allowed_overlap
      *            maximal allowed overlap (inclusive) to be still considered not
      *            overlapping (zero or negative value to allow any overlap)
@@ -1074,7 +1141,7 @@ public final class ForesterUtil {
                                                     final boolean remove_engulfed_domains,
                                                     final Protein protein ) {
         final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
-                .getSpeciesId(), protein.getLength() );
+                                                         .getSpeciesId(), protein.getLength() );
         final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
         final List<Boolean> covered_positions = new ArrayList<Boolean>();
         for( final Domain domain : sorted ) {
@@ -1109,7 +1176,7 @@ public final class ForesterUtil {
 
     /**
      * Removes all white space from String s.
-     * 
+     *
      * @return String s with white space removed
      */
     final public static String removeWhiteSpace( String s ) {
@@ -1201,6 +1268,11 @@ public final class ForesterUtil {
         return false;
     }
 
+    final private static String[] splitString( final String str ) {
+        final String regex = "[\\s;,]+";
+        return str.split( regex );
+    }
+
     final public static String stringArrayToString( final String[] a ) {
         return stringArrayToString( a, ", " );
     }
@@ -1275,7 +1347,7 @@ public final class ForesterUtil {
     final public static void unexpectedFatalError( final String prg_name, final Exception e ) {
         System.err.println();
         System.err.println( "[" + prg_name
-                + "] > unexpected error; should not have occured! Please contact program author(s)." );
+                            + "] > unexpected error; should not have occured! Please contact program author(s)." );
         e.printStackTrace( System.err );
         System.err.println();
         System.exit( -1 );
@@ -1284,7 +1356,7 @@ public final class ForesterUtil {
     final public static void unexpectedFatalError( final String prg_name, final String message ) {
         System.err.println();
         System.err.println( "[" + prg_name
-                + "] > unexpected error: should not have occured! Please contact program author(s)." );
+                            + "] > unexpected error: should not have occured! Please contact program author(s)." );
         System.err.println( message );
         System.err.println();
         System.exit( -1 );
@@ -1293,7 +1365,7 @@ public final class ForesterUtil {
     final public static void unexpectedFatalError( final String prg_name, final String message, final Exception e ) {
         System.err.println();
         System.err.println( "[" + prg_name
-                + "] > unexpected error: should not have occured! Please contact program author(s)." );
+                            + "] > unexpected error: should not have occured! Please contact program author(s)." );
         System.err.println( message );
         e.printStackTrace( System.err );
         System.err.println();
@@ -1346,41 +1418,44 @@ public final class ForesterUtil {
         return sb.toString();
     }
 
-    /**
-     * Helper method for calcColor methods.
-     * 
-     * @param smallercolor_component_x
-     *            color component the smaller color
-     * @param largercolor_component_x
-     *            color component the larger color
-     * @param x
-     *            factor
-     * @return an int representing a color component
-     */
-    final private static int calculateColorComponent( final double smallercolor_component_x,
-                                                      final double largercolor_component_x,
-                                                      final double x ) {
-        return ( int ) ( smallercolor_component_x + ( ( x * ( largercolor_component_x - smallercolor_component_x ) ) / 255.0 ) );
-    }
 
-    /**
-     * Helper method for calcColor methods.
-     * 
-     * 
-     * @param value
-     *            the value
-     * @param larger
-     *            the largest value
-     * @param smaller
-     *            the smallest value
-     * @return a normalized value between larger and smaller
-     */
-    final private static double calculateColorFactor( final double value, final double larger, final double smaller ) {
-        return ( 255.0 * ( value - smaller ) ) / ( larger - smaller );
+    public final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
+                                                            final PhylogenyParser parser )
+            throws NoSuchAlgorithmException, IOException, KeyManagementException {
+        if ( url == null ) {
+            throw new IllegalArgumentException( "URL to read from must not be null" );
+        }
+        else if ( parser == null ) {
+            throw new IllegalArgumentException( "parser to use to read from URL must not be null" );
+        }
+        final URLConnection con;
+        if ( url.toString().startsWith( "https:" ) ) {    
+             con = TrustManager.makeHttpsURLConnection( url );
+        }
+        else if ( url.toString().startsWith( "http:" ) ) {
+            con = url.openConnection();
+        }
+        else {
+            throw new IllegalArgumentException( "Cannot deal with URL: " + url );
+        }
+        if ( con == null ) {    
+            throw new IOException( "could not create connection from " + url );
+        }
+        con.setDefaultUseCaches( false );
+        final InputStream is = con.getInputStream();
+        if ( is == null ) {    
+            throw new IOException( "could not create input stream from " + url );
+        }
+        final Phylogeny[] trees = ParserBasedPhylogenyFactory.getInstance().create( is, parser );
+        try {
+            is.close();
+        }
+        catch ( final Exception e ) {
+            // ignore  
+        }
+        return trees;
     }
-
-    final private static String[] splitString( final String str ) {
-        final String regex = "[\\s;,]+";
-        return str.split( regex );
+    
+    private ForesterUtil() {
     }
 }