JAL-1807 - Bob's last(?) before leaving Dundee -- adds fast file loading
[jalviewjs.git] / src / jalview / io / AppletFormatAdapter.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  *
5  * This file is part of Jalview.
6  *
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *
12  * Jalview is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15  * PURPOSE.  See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import jalview.api.AlignExportSettingI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.AlignmentView;
29 import jalview.util.MessageManager;
30
31 import java.io.File;
32 import java.io.InputStream;
33 import java.util.List;
34
35 import javajs.J2SIgnoreImport;
36
37 import jalview.jsdev.GenericFileAdapter;
38
39 /**
40  * A low level class for alignment and feature IO with alignment formatting
41  * methods used by both applet and application for generating flat alignment
42  * files. It also holds the lists of magic format names that the applet and
43  * application will allow the user to read or write files with.
44  *
45  * @author $author$
46  * @version $Revision$
47  */
48 @J2SIgnoreImport({java.io.File.class})
49 public class AppletFormatAdapter
50 {
51   private AlignmentViewPanel viewpanel;
52
53   public static String FILE = "File";
54
55   public static String URL = "URL";
56
57   public static String PASTE = "Paste";
58
59   public static String CLASSLOADER = "ClassLoader";
60
61   /**
62    * add jalview-derived non-secondary structure annotation from PDB structure
63    */
64   boolean annotFromStructure = false;
65
66   /**
67    * add secondary structure from PDB data with built-in algorithms
68    */
69   boolean localSecondaryStruct = false;
70
71   /**
72    * process PDB data with web services
73    */
74   boolean serviceSecondaryStruct = false;
75
76   private AlignFile alignFile = null;
77
78   String inFile;
79
80   /**
81    * character used to write newlines
82    */
83   protected String newline = System.getProperty("line.separator");
84
85   private AlignExportSettingI exportSettings;
86
87   /**
88    * List of valid format strings used in the isValidFormat method
89    */
90   public static final String[] READABLE_FORMATS = new String[]
91   { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "STH",
92       "PDB", "JnetFile", "RNAML", GenericFileAdapter.Phylip_FILE_DESC, GenericFileAdapter.JSON_FILE_DESC, IdentifyFile.GFF3File,
93       "HTML" };
94
95   /**
96    * List of readable format file extensions by application in order
97    * corresponding to READABLE_FNAMES
98    */
99   public static final String[] READABLE_EXTENSIONS = new String[]
100   { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
101       "sto,stk", "xml,rnaml", GenericFileAdapter.Phylip_FILE_EXT, GenericFileAdapter.JSON_FILE_EXT,
102       ".gff2,gff3",
103       "jar,jvp", GenericFileAdapter.Html_FILE_EXT };
104
105   /**
106    * List of readable formats by application in order corresponding to
107    * READABLE_EXTENSIONS
108    */
109   public static final String[] READABLE_FNAMES = new String[]
110   { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Stockholm",
111       "RNAML", GenericFileAdapter.Phylip_FILE_DESC, GenericFileAdapter.JSON_FILE_DESC, IdentifyFile.GFF3File, "Jalview",
112       GenericFileAdapter.Html_FILE_DESC };
113
114   /**
115    * List of valid format strings for use by callers of the formatSequences
116    * method
117    */
118   public static final String[] WRITEABLE_FORMATS = new String[]
119           { "BLC", "CLUSTAL", "FASTA", "MSF", "PileUp", "PIR", "PFAM", "AMSA",
120     "STH", GenericFileAdapter.Phylip_FILE_DESC, GenericFileAdapter.JSON_FILE_DESC };
121
122   /**
123    * List of extensions corresponding to file format types in WRITABLE_FNAMES
124    * that are writable by the application.
125    */
126   public static final String[] WRITABLE_EXTENSIONS = new String[]
127   { "fa, fasta, mfa, fastq", "aln", "pfam", "msf", "pir", "blc", "amsa",
128       "sto,stk", GenericFileAdapter.Phylip_FILE_EXT, GenericFileAdapter.JSON_FILE_EXT, "jvp" };
129
130   /**
131    * List of writable formats by the application. Order must correspond with the
132    * WRITABLE_EXTENSIONS list of formats.
133    */
134   public static final String[] WRITABLE_FNAMES = new String[]
135   { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "STH",
136       GenericFileAdapter.Phylip_FILE_DESC, GenericFileAdapter.JSON_FILE_DESC, "Jalview" };
137
138   public static String INVALID_CHARACTERS = "Contains invalid characters";
139
140   // TODO: make these messages dynamic
141   public static String SUPPORTED_FORMATS = "Formats currently supported are\n"
142           + prettyPrint(READABLE_FORMATS);
143
144   public AppletFormatAdapter()
145   {
146   }
147
148   public AppletFormatAdapter(AlignmentViewPanel viewpanel)
149   {
150     this.viewpanel = viewpanel;
151   }
152
153   public AppletFormatAdapter(AlignmentViewPanel alignPanel,
154           AlignExportSettingI settings)
155   {
156     viewpanel = alignPanel;
157     exportSettings = settings;
158   }
159
160   /**
161    *
162    * @param els
163    * @return grammatically correct(ish) list consisting of els elements.
164    */
165   public static String prettyPrint(String[] els)
166   {
167     StringBuffer list = new StringBuffer();
168     for (int i = 0, iSize = els.length - 1; i < iSize; i++)
169     {
170       list.append(els[i]);
171       list.append(", ");
172     }
173     list.append(" and " + els[els.length - 1] + ".");
174     return list.toString();
175   }
176
177
178   public void setNewlineString(String nl)
179   {
180     newline = nl;
181   }
182
183   public String getNewlineString()
184   {
185     return newline;
186   }
187
188   /**
189    * check that this format is valid for reading
190    *
191    * @param format
192    *          a format string to be compared with READABLE_FORMATS
193    * @return true if format is readable
194    */
195   public static final boolean isValidFormat(String format)
196   {
197     return isValidFormat(format, false);
198   }
199
200   /**
201    * validate format is valid for IO
202    *
203    * @param format
204    *          a format string to be compared with either READABLE_FORMATS or
205    *          WRITEABLE_FORMATS
206    * @param forwriting
207    *          when true, format is checked for containment in WRITEABLE_FORMATS
208    * @return true if format is valid
209    */
210   public static final boolean isValidFormat(String format,
211           boolean forwriting)
212   {
213     boolean valid = false;
214     String[] format_list = (forwriting) ? WRITEABLE_FORMATS
215             : READABLE_FORMATS;
216     for (String element : format_list)
217     {
218       if (element.equalsIgnoreCase(format))
219       {
220         return true;
221       }
222     }
223
224     return valid;
225   }
226
227   /**
228    * Constructs the correct filetype parser for a characterised datasource
229    *
230    * @param inFile
231    *          data/data location
232    * @param type
233    *          type of datasource
234    * @param format
235    *          File format of data provided by datasource
236    *
237    * @return DOCUMENT ME!
238    */
239   public AlignmentI readFile(String inFile, String type, String format)
240           throws java.io.IOException
241   {
242     // TODO: generalise mapping between format string and io. class instances
243     // using Constructor.invoke reflection
244     this.inFile = inFile;
245     try
246     {
247       if (format.equals("FASTA"))
248       {
249         alignFile = GenericFileAdapter.getFile("FastaFile", inFile, type);
250       }
251       else if (format.equals("MSF"))
252       {
253         alignFile = GenericFileAdapter.getFile("MSFfile", inFile, type);
254       }
255       else if (format.equals("PileUp"))
256       {
257         alignFile = GenericFileAdapter.getFile("PileUpfile", inFile, type);
258       }
259       else if (format.equals("CLUSTAL"))
260       {
261         alignFile = GenericFileAdapter.getFile("ClustalFile", inFile, type);
262       }
263       else if (format.equals("BLC"))
264       {
265         alignFile = GenericFileAdapter.getFile("BLCFile", inFile, type);
266       }
267       else if (format.equals("PIR"))
268       {
269         alignFile = GenericFileAdapter.getFile("PIRFile", inFile, type);
270       }
271       else if (format.equals("PFAM"))
272       {
273         alignFile = GenericFileAdapter.getFile("PfamFile", inFile, type);
274       }
275       else if (format.equals("JnetFile"))
276       {
277         alignFile = GenericFileAdapter.getFile("JPredFile", inFile, type);
278         ((JPredFile) alignFile).removeNonSequences();
279       }
280       else if (format.equals("PDB"))
281       {
282         alignFile = new MCview.PDBfile(annotFromStructure,
283                 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
284         // Uncomment to test Jmol data based PDB processing: JAL-1213
285         // afile = new jalview.ext.jmol.PDBFileWithJmol(inFile, type);
286       }
287       else if (format.equals("STH"))
288       {
289         alignFile = GenericFileAdapter.getFile("StockholmFile", inFile, type);
290       }
291       else if (format.equals("SimpleBLAST"))
292       {
293         alignFile = GenericFileAdapter.getFile("SimpleBlastFile", inFile, type);
294       }
295       else if (format.equals(PhylipFile.FILE_DESC))
296       {
297         alignFile = GenericFileAdapter.getFile("PhylipFile", inFile, type);
298       }
299       else if (format.equals(GenericFileAdapter.JSON_FILE_DESC))
300       {
301         alignFile = GenericFileAdapter.getFile("JSONFile", inFile, type);
302       }
303       else if (format.equals(GenericFileAdapter.Html_FILE_DESC))
304       {
305         alignFile = GenericFileAdapter.getFile("HtmlFile", inFile, type);
306       }
307       else if (format.equals("RNAML"))
308       {
309         alignFile = GenericFileAdapter.getFile("RnamlFile", inFile, type);
310       }
311       else if (format.equals(IdentifyFile.GFF3File))
312       {
313         alignFile = GenericFileAdapter.getFile("Gff3File", inFile, type);
314       }
315       return buildAlignmentFrom(alignFile);
316     } catch (Exception e)
317     {
318       e.printStackTrace();
319       System.err.println("Failed to read alignment using the '" + format
320               + "' reader.\n" + e);
321
322       if (e.getMessage() != null
323               && e.getMessage().startsWith(INVALID_CHARACTERS))
324       {
325         throw new java.io.IOException(e.getMessage());
326       }
327
328       // Finally test if the user has pasted just the sequence, no id
329       if (type.equalsIgnoreCase("Paste"))
330       {
331         try
332         {
333           // Possible sequence is just residues with no label
334           alignFile = GenericFileAdapter.getFile("FastaFile", ">UNKNOWN\n" + inFile, "Paste");
335           return buildAlignmentFrom(alignFile);
336
337         } catch (Exception ex)
338         {
339           if (ex.toString().startsWith(INVALID_CHARACTERS))
340           {
341             throw new java.io.IOException(e.getMessage());
342           }
343
344           ex.printStackTrace();
345         }
346       }
347
348       // If we get to this stage, the format was not supported
349       throw new java.io.IOException(SUPPORTED_FORMATS);
350     }
351   }
352
353   /**
354    * Constructs the correct filetype parser for an already open datasource
355    *
356    * @param source
357    *          an existing datasource
358    * @param format
359    *          File format of data that will be provided by datasource
360    *
361    * @return DOCUMENT ME!
362    */
363   public AlignmentI readFromFile(FileParse source, String format)
364           throws java.io.IOException
365   {
366     // TODO: generalise mapping between format string and io. class instances
367     // using Constructor.invoke reflection
368     // This is exactly the same as the readFile method except we substitute
369     // 'inFile, type' with 'source'
370     this.inFile = source.getInFile();
371     String type = source.type;
372     try
373     {
374       if (format.equals("FASTA"))
375       {
376         alignFile = GenericFileAdapter.getFile("FastaFile", source);
377       }
378       else if (format.equals("MSF"))
379       {
380         alignFile = GenericFileAdapter.getFile("MSFfile", source);
381       }
382       else if (format.equals("PileUp"))
383       {
384         alignFile = GenericFileAdapter.getFile("PileUpfile", source);
385       }
386       else if (format.equals("CLUSTAL"))
387       {
388         alignFile = GenericFileAdapter.getFile("ClustalFile", source);
389       }
390       else if (format.equals("BLC"))
391       {
392         alignFile = GenericFileAdapter.getFile("BLCFile", source);
393       }
394       else if (format.equals("PIR"))
395       {
396         alignFile = GenericFileAdapter.getFile("PIRFile", source);
397       }
398       else if (format.equals("PFAM"))
399       {
400         alignFile = GenericFileAdapter.getFile("PfamFile", source);
401       }
402       else if (format.equals("JnetFile"))
403       {
404         alignFile = GenericFileAdapter.getFile("JPredFile", source);
405         ((JPredFile) alignFile).removeNonSequences();
406       }
407       else if (format.equals("PDB"))
408       {
409         alignFile = new MCview.PDBfile(annotFromStructure,
410                 localSecondaryStruct, serviceSecondaryStruct, source);
411       }
412       else if (format.equals("STH"))
413       {
414         alignFile = GenericFileAdapter.getFile("StockholmFile", source);
415       }
416       else if (format.equals("RNAML"))
417       {
418         alignFile = GenericFileAdapter.getFile("RnamlFile", source);
419       }
420       else if (format.equals("SimpleBLAST"))
421       {
422         alignFile = GenericFileAdapter.getFile("SimpleBlastFile", source);
423       }
424       else if (format.equals(GenericFileAdapter.Phylip_FILE_DESC))
425       {
426         alignFile = GenericFileAdapter.getFile("PhylipFile", source);
427       }
428       else if (format.equals(IdentifyFile.GFF3File))
429       {
430         alignFile = GenericFileAdapter.getFile("Gff3File", inFile, type);
431       }
432       else if (format.equals(GenericFileAdapter.JSON_FILE_DESC))
433       {
434         alignFile = GenericFileAdapter.getFile("JSONFile", source);
435       }
436       else if (format.equals(GenericFileAdapter.Html_FILE_DESC))
437       {
438         alignFile = GenericFileAdapter.getFile("HtmlFile", source);
439       }
440
441       return buildAlignmentFrom(alignFile);
442
443     } catch (Exception e)
444     {
445       e.printStackTrace();
446       System.err.println("Failed to read alignment using the '" + format
447               + "' reader.\n" + e);
448
449       if (e.getMessage() != null
450               && e.getMessage().startsWith(INVALID_CHARACTERS))
451       {
452         throw new java.io.IOException(e.getMessage());
453       }
454
455       // Finally test if the user has pasted just the sequence, no id
456       if (type.equalsIgnoreCase("Paste"))
457       {
458         try
459         {
460           // Possible sequence is just residues with no label
461           alignFile = GenericFileAdapter.getFile("FastaFile", ">UNKNOWN\n" + inFile, "Paste");
462           return buildAlignmentFrom(alignFile);
463
464         } catch (Exception ex)
465         {
466           if (ex.toString().startsWith(INVALID_CHARACTERS))
467           {
468             throw new java.io.IOException(e.getMessage());
469           }
470
471           ex.printStackTrace();
472         }
473       }
474
475       // If we get to this stage, the format was not supported
476       throw new java.io.IOException(SUPPORTED_FORMATS);
477     }
478   }
479
480
481   /**
482    * boilerplate method to handle data from an AlignFile and construct a new
483    * alignment or import to an existing alignment
484    * 
485    * @param alignFile2
486    * @return AlignmentI instance ready to pass to a UI constructor
487    */
488   private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
489   {
490     // Standard boilerplate for creating alignment from parser
491     // alignFile.configureForView(viewpanel);
492
493     AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
494
495     alignFile.addAnnotations(al);
496
497     alignFile.addGroups(al);
498
499     return al;
500   }
501
502   /**
503    * create an alignment flatfile from a Jalview alignment view
504    * @param format
505    * @param jvsuffix
506    * @param av
507    * @param selectedOnly
508    * @return flatfile in a string
509    */
510   public String formatSequences(String format, boolean jvsuffix,
511           AlignmentViewPanel ap, boolean selectedOnly)
512   {
513
514     AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
515             selectedOnly, false);
516     AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
517             .getGapCharacter());
518     List<AlignmentAnnotation> ala = (ap.getAlignViewport()
519             .getVisibleAlignmentAnnotation(selectedOnly));
520     if (ala != null)
521     {
522       for (AlignmentAnnotation aa : ala)
523       {
524         aselview.addAnnotation(aa);
525       }
526     }
527     viewpanel = ap;
528     return formatSequences(format, aselview, jvsuffix);
529   }
530
531   /**
532    * Construct an output class for an alignment in a particular filetype TODO:
533    * allow caller to detect errors and warnings encountered when generating
534    * output
535    *
536    * @param format
537    *          string name of alignment format
538    * @param alignment
539    *          the alignment to be written out
540    * @param jvsuffix
541    *          passed to AlnFile class controls whether /START-END is added to
542    *          sequence names
543    *
544    * @return alignment flat file contents
545    */
546   public String formatSequences(String format, AlignmentI alignment,
547           boolean jvsuffix)
548   {
549     try
550     {
551       AlignFile afile = null;
552       if (format.equalsIgnoreCase("FASTA"))
553       {
554         afile = GenericFileAdapter.getFile("FastaFile");
555       }
556       else if (format.equalsIgnoreCase("MSF"))
557       {
558         afile = GenericFileAdapter.getFile("MSFfile");
559       }
560       else if (format.equalsIgnoreCase("PileUp"))
561       {
562         afile = GenericFileAdapter.getFile("PileUpfile"); // BH NOTE LOWER CASE "file"
563       }
564       else if (format.equalsIgnoreCase("CLUSTAL"))
565       {
566         afile = GenericFileAdapter.getFile("ClustalFile");
567       }
568       else if (format.equalsIgnoreCase("BLC"))
569       {
570         afile = GenericFileAdapter.getFile("BLCFile");
571       }
572       else if (format.equalsIgnoreCase("PIR"))
573       {
574         afile = GenericFileAdapter.getFile("PIRFile");
575       }
576       else if (format.equalsIgnoreCase("PFAM"))
577       {
578         afile = GenericFileAdapter.getFile("PfamFile");
579       }
580       else if (format.equalsIgnoreCase("STH"))
581       {
582         afile = GenericFileAdapter.getFile("StockholmFile", alignment);
583       }
584       else if (format.equalsIgnoreCase("AMSA"))
585       {
586         afile = GenericFileAdapter.getFile("AMSAFile", alignment);
587       }
588       else if (format.equalsIgnoreCase(GenericFileAdapter.Phylip_FILE_DESC))
589       {
590         afile = GenericFileAdapter.getFile("PhylipFile");
591       }
592        else if (format.equalsIgnoreCase(GenericFileAdapter.JSON_FILE_DESC))
593        {
594         afile = GenericFileAdapter.getFile("JSONFile");
595        }
596       else if (format.equalsIgnoreCase("RNAML"))
597       {
598         afile = GenericFileAdapter.getFile("RnamlFile");
599       }
600
601       else
602       {
603         throw new Exception(MessageManager.getString("error.implementation_error_unknown_file_format_string"));
604       }
605
606       afile.setNewlineString(newline);
607       afile.addJVSuffix(jvsuffix);
608       afile.setExportSettings(exportSettings);
609       afile.configureForView(viewpanel);
610
611       // check whether we were given a specific alignment to export, rather than
612       // the one in the viewpanel
613       if (viewpanel == null || viewpanel.getAlignment() == null
614               || viewpanel.getAlignment() != alignment)
615       {
616         afile.setSeqs(alignment.getSequencesArray());
617       }
618       else
619       {
620         afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
621       }
622
623       String afileresp = afile.print();
624       if (afile.hasWarningMessage())
625       {
626         System.err.println("Warning raised when writing as " + format
627                 + " : " + afile.getWarningMessage());
628       }
629       return afileresp;
630     } catch (Exception e)
631     {
632       System.err.println("Failed to write alignment as a '" + format
633               + "' file\n");
634       e.printStackTrace();
635     }
636
637     return null;
638   }
639
640   public static String checkProtocol(String file)
641   {
642     String protocol = FILE;
643     String ft = file.toLowerCase().trim();
644     if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
645             || ft.indexOf("file:") == 0)
646     {
647       protocol = URL;
648     }
649     return protocol;
650   }
651
652   /**
653    * @j2sIgnore
654    * 
655    * @param args
656    */
657   public static void main(String[] args)
658   {
659     int i = 0;
660     while (i < args.length)
661     {
662       File f = new File(args[i]);
663       if (f.exists())
664       {
665         try
666         {
667           System.out.println("Reading file: " + f);
668           AppletFormatAdapter afa = new AppletFormatAdapter();
669           Runtime r = Runtime.getRuntime();
670           System.gc();
671           long memf = -r.totalMemory() + r.freeMemory();
672           long t1 = -System.currentTimeMillis();
673           AlignmentI al = afa.readFile(args[i], FILE,
674                   new IdentifyFile().Identify(args[i], FILE));
675           t1 += System.currentTimeMillis();
676           System.gc();
677           memf += r.totalMemory() - r.freeMemory();
678           if (al != null)
679           {
680             System.out.println("Alignment contains " + al.getHeight()
681                     + " sequences and " + al.getWidth() + " columns.");
682             try
683             {
684               System.out.println(new AppletFormatAdapter().formatSequences(
685                       "FASTA", al, true));
686             } catch (Exception e)
687             {
688               System.err
689               .println("Couln't format the alignment for output as a FASTA file.");
690               e.printStackTrace(System.err);
691             }
692           }
693           else
694           {
695             System.out.println("Couldn't read alignment");
696           }
697           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
698           System.out
699           .println("Difference between free memory now and before is "
700                   + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
701         } catch (Exception e)
702         {
703           System.err.println("Exception when dealing with " + i
704                   + "'th argument: " + args[i] + "\n" + e);
705         }
706       }
707       else
708       {
709         System.err.println("Ignoring argument '" + args[i] + "' (" + i
710                 + "'th)- not a readable file.");
711       }
712       i++;
713     }
714   }
715
716   /**
717    * try to discover how to access the given file as a valid datasource that
718    * will be identified as the given type.
719    *
720    * @param file
721    * @param format
722    * @return protocol that yields the data parsable as the given type
723    */
724   public static String resolveProtocol(String file, String format)
725   {
726     return resolveProtocol(file, format, false);
727   }
728
729   public static String resolveProtocol(String file, String format,
730           boolean debug)
731   {
732     // TODO: test thoroughly!
733     String protocol = null;
734     if (debug)
735     {
736       System.out.println("resolving datasource started with:\n>>file\n"
737               + file + ">>endfile");
738     }
739
740     // This might throw a security exception in certain browsers
741     // Netscape Communicator for instance.
742     try
743     {
744       boolean rtn = false;
745       InputStream is = System.getSecurityManager().getClass()
746               .getResourceAsStream("/" + file);
747       if (is != null)
748       {
749         rtn = true;
750         is.close();
751       }
752       if (debug)
753       {
754         System.err.println("Resource '" + file + "' was "
755                 + (rtn ? "" : "not") + " located by classloader.");
756       }
757       ;
758       if (rtn)
759       {
760         protocol = AppletFormatAdapter.CLASSLOADER;
761       }
762
763     } catch (Exception ex)
764     {
765       System.err
766       .println("Exception checking resources: " + file + " " + ex);
767     }
768
769     if (file.indexOf("://") > -1)
770     {
771       protocol = AppletFormatAdapter.URL;
772     }
773     else
774     {
775       // skipping codebase prepend check.
776       protocol = AppletFormatAdapter.FILE;
777     }
778     FileParse fp = null;
779     try
780     {
781       if (debug)
782       {
783         System.out.println("Trying to get contents of resource as "
784                 + protocol + ":");
785       }
786       fp = new FileParse(file, protocol);
787       if (!fp.isValid())
788       {
789         fp = null;
790       }
791       else
792       {
793         if (debug)
794         {
795           System.out.println("Successful.");
796         }
797       }
798     } catch (Exception e)
799     {
800       if (debug)
801       {
802         System.err.println("Exception when accessing content: " + e);
803       }
804       fp = null;
805     }
806     if (fp == null)
807     {
808       if (debug)
809       {
810         System.out.println("Accessing as paste.");
811       }
812       protocol = AppletFormatAdapter.PASTE;
813       fp = null;
814       try
815       {
816         fp = new FileParse(file, protocol);
817         if (!fp.isValid())
818         {
819           fp = null;
820         }
821       } catch (Exception e)
822       {
823         System.err.println("Failed to access content as paste!");
824         e.printStackTrace();
825         fp = null;
826       }
827     }
828     if (fp == null)
829     {
830       return null;
831     }
832     if (format == null || format.length() == 0)
833     {
834       return protocol;
835     }
836     else
837     {
838       try
839       {
840         String idformat = new IdentifyFile().Identify(file,
841                 protocol);
842         if (idformat == null)
843         {
844           if (debug)
845           {
846             System.out.println("Format not identified. Inaccessible file.");
847           }
848           return null;
849         }
850         if (debug)
851         {
852           System.out.println("Format identified as " + idformat
853                   + "and expected as " + format);
854         }
855         if (idformat.equals(format))
856         {
857           if (debug)
858           {
859             System.out.println("Protocol identified as " + protocol);
860           }
861           return protocol;
862         }
863         else
864         {
865           if (debug)
866           {
867             System.out
868             .println("File deemed not accessible via " + protocol);
869           }
870           fp.close();
871           return null;
872         }
873       } catch (Exception e)
874       {
875         if (debug)
876         {
877           System.err.println("File deemed not accessible via " + protocol);
878           e.printStackTrace();
879         }
880         ;
881
882       }
883     }
884     return null;
885   }
886
887   public AlignFile getAlignFile()
888   {
889     return alignFile;
890   }
891
892   public void setAlignFile(AlignFile alignFile)
893   {
894     this.alignFile = alignFile;
895   }
896 }