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