1a639f12e84c380c6420a09dd639ad6735a2ef17
[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 = false;
284         if (isParseWithJMOL)
285         {
286           StructureViewSettings.addSettings(annotFromStructure,
287                   localSecondaryStruct, serviceSecondaryStruct);
288           alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
289                   localSecondaryStruct, serviceSecondaryStruct, inFile,
290                   type);
291         }
292         else
293         {
294           StructureViewSettings.setShowSeqFeatures(true);
295           alignFile = new MCview.PDBfile(annotFromStructure,
296                   localSecondaryStruct, serviceSecondaryStruct, inFile,
297                   type);
298         }
299       }
300       else if (format.equals("mmCIF"))
301       {
302         StructureViewSettings.addSettings(annotFromStructure,
303                 localSecondaryStruct, serviceSecondaryStruct);
304         alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
305                 localSecondaryStruct, serviceSecondaryStruct, inFile, type);
306       }
307       else if (format.equals("STH"))
308       {
309         alignFile = new StockholmFile(inFile, type);
310       }
311       else if (format.equals("SimpleBLAST"))
312       {
313         alignFile = new SimpleBlastFile(inFile, type);
314       }
315       else if (format.equals(PhylipFile.FILE_DESC))
316       {
317         alignFile = new PhylipFile(inFile, type);
318       }
319       else if (format.equals(JSONFile.FILE_DESC))
320       {
321         alignFile = new JSONFile(inFile, type);
322       }
323       else if (format.equals(HtmlFile.FILE_DESC))
324       {
325         alignFile = new HtmlFile(inFile, type);
326       }
327       else if (format.equals("RNAML"))
328       {
329         alignFile = new RnamlFile(inFile, type);
330       }
331       else if (format.equals(IdentifyFile.FeaturesFile))
332       {
333         alignFile = new FeaturesFile(true, inFile, type);
334       }
335       return buildAlignmentFrom(alignFile);
336     } catch (Exception e)
337     {
338       e.printStackTrace();
339       System.err.println("Failed to read alignment using the '" + format
340               + "' reader.\n" + e);
341
342       if (e.getMessage() != null
343               && e.getMessage().startsWith(INVALID_CHARACTERS))
344       {
345         throw new java.io.IOException(e.getMessage());
346       }
347
348       // Finally test if the user has pasted just the sequence, no id
349       if (type.equalsIgnoreCase("Paste"))
350       {
351         try
352         {
353           // Possible sequence is just residues with no label
354           alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
355           return buildAlignmentFrom(alignFile);
356
357         } catch (Exception ex)
358         {
359           if (ex.toString().startsWith(INVALID_CHARACTERS))
360           {
361             throw new java.io.IOException(e.getMessage());
362           }
363
364           ex.printStackTrace();
365         }
366       }
367       if (format.equalsIgnoreCase("HTML"))
368       {
369         throw new IOException(e.getMessage());
370       }
371       // If we get to this stage, the format was not supported
372       throw new java.io.IOException(SUPPORTED_FORMATS);
373     }
374   }
375
376   /**
377    * Constructs the correct filetype parser for an already open datasource
378    *
379    * @param source
380    *          an existing datasource
381    * @param format
382    *          File format of data that will be provided by datasource
383    *
384    * @return DOCUMENT ME!
385    */
386   public AlignmentI readFromFile(FileParse source, String format)
387           throws java.io.IOException
388   {
389     // TODO: generalise mapping between format string and io. class instances
390     // using Constructor.invoke reflection
391     // This is exactly the same as the readFile method except we substitute
392     // 'inFile, type' with 'source'
393     this.inFile = source.getInFile();
394     String type = source.type;
395     try
396     {
397       if (format.equals("FASTA"))
398       {
399         alignFile = new FastaFile(source);
400       }
401       else if (format.equals("MSF"))
402       {
403         alignFile = new MSFfile(source);
404       }
405       else if (format.equals("PileUp"))
406       {
407         alignFile = new PileUpfile(source);
408       }
409       else if (format.equals("CLUSTAL"))
410       {
411         alignFile = new ClustalFile(source);
412       }
413       else if (format.equals("BLC"))
414       {
415         alignFile = new BLCFile(source);
416       }
417       else if (format.equals("PIR"))
418       {
419         alignFile = new PIRFile(source);
420       }
421       else if (format.equals("PFAM"))
422       {
423         alignFile = new PfamFile(source);
424       }
425       else if (format.equals("JnetFile"))
426       {
427         alignFile = new JPredFile(source);
428         ((JPredFile) alignFile).removeNonSequences();
429       }
430       else if (format.equals("PDB"))
431       {
432         // TODO obtain config value from preference settings
433         boolean isParseWithJMOL = false;
434         if (isParseWithJMOL)
435         {
436           StructureViewSettings.addSettings(annotFromStructure,
437                   localSecondaryStruct, serviceSecondaryStruct);
438           alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
439                   localSecondaryStruct, serviceSecondaryStruct, source);
440         }
441         else
442         {
443           StructureViewSettings.setShowSeqFeatures(true);
444           alignFile = new MCview.PDBfile(annotFromStructure,
445                   localSecondaryStruct, serviceSecondaryStruct, source);
446         }
447       }
448       else if (format.equals("mmCIF"))
449       {
450         StructureViewSettings.addSettings(annotFromStructure,
451                 localSecondaryStruct, serviceSecondaryStruct);
452         alignFile = new jalview.ext.jmol.JmolParser(annotFromStructure,
453                 localSecondaryStruct, serviceSecondaryStruct, source);
454       }
455       else if (format.equals("STH"))
456       {
457         alignFile = new StockholmFile(source);
458       }
459       else if (format.equals("RNAML"))
460       {
461         alignFile = new RnamlFile(source);
462       }
463       else if (format.equals("SimpleBLAST"))
464       {
465         alignFile = new SimpleBlastFile(source);
466       }
467       else if (format.equals(PhylipFile.FILE_DESC))
468       {
469         alignFile = new PhylipFile(source);
470       }
471       else if (format.equals(IdentifyFile.FeaturesFile))
472       {
473         alignFile = new FeaturesFile(inFile, type);
474       }
475       else if (format.equals(JSONFile.FILE_DESC))
476       {
477         alignFile = new JSONFile(source);
478       }
479       else if (format.equals(HtmlFile.FILE_DESC))
480       {
481         alignFile = new HtmlFile(source);
482       }
483
484       return buildAlignmentFrom(alignFile);
485
486     } catch (Exception e)
487     {
488       e.printStackTrace();
489       System.err.println("Failed to read alignment using the '" + format
490               + "' reader.\n" + e);
491
492       if (e.getMessage() != null
493               && e.getMessage().startsWith(INVALID_CHARACTERS))
494       {
495         throw new java.io.IOException(e.getMessage());
496       }
497
498       // Finally test if the user has pasted just the sequence, no id
499       if (type.equalsIgnoreCase("Paste"))
500       {
501         try
502         {
503           // Possible sequence is just residues with no label
504           alignFile = new FastaFile(">UNKNOWN\n" + inFile, "Paste");
505           return buildAlignmentFrom(alignFile);
506
507         } catch (Exception ex)
508         {
509           if (ex.toString().startsWith(INVALID_CHARACTERS))
510           {
511             throw new java.io.IOException(e.getMessage());
512           }
513
514           ex.printStackTrace();
515         }
516       }
517
518       // If we get to this stage, the format was not supported
519       throw new java.io.IOException(SUPPORTED_FORMATS);
520     }
521   }
522
523   /**
524    * boilerplate method to handle data from an AlignFile and construct a new
525    * alignment or import to an existing alignment
526    * 
527    * @param alignFile2
528    * @return AlignmentI instance ready to pass to a UI constructor
529    */
530   private AlignmentI buildAlignmentFrom(AlignFile alignFile2)
531   {
532     // Standard boilerplate for creating alignment from parser
533     // alignFile.configureForView(viewpanel);
534
535     AlignmentI al = new Alignment(alignFile.getSeqsAsArray());
536
537     alignFile.addAnnotations(al);
538
539     alignFile.addGroups(al);
540
541     return al;
542   }
543
544   /**
545    * create an alignment flatfile from a Jalview alignment view
546    * 
547    * @param format
548    * @param jvsuffix
549    * @param av
550    * @param selectedOnly
551    * @return flatfile in a string
552    */
553   public String formatSequences(String format, boolean jvsuffix,
554           AlignmentViewPanel ap, boolean selectedOnly)
555   {
556
557     AlignmentView selvew = ap.getAlignViewport().getAlignmentView(
558             selectedOnly, false);
559     AlignmentI aselview = selvew.getVisibleAlignment(ap.getAlignViewport()
560             .getGapCharacter());
561     List<AlignmentAnnotation> ala = (ap.getAlignViewport()
562             .getVisibleAlignmentAnnotation(selectedOnly));
563     if (ala != null)
564     {
565       for (AlignmentAnnotation aa : ala)
566       {
567         aselview.addAnnotation(aa);
568       }
569     }
570     viewpanel = ap;
571     return formatSequences(format, aselview, jvsuffix);
572   }
573
574   /**
575    * Construct an output class for an alignment in a particular filetype TODO:
576    * allow caller to detect errors and warnings encountered when generating
577    * output
578    *
579    * @param format
580    *          string name of alignment format
581    * @param alignment
582    *          the alignment to be written out
583    * @param jvsuffix
584    *          passed to AlnFile class controls whether /START-END is added to
585    *          sequence names
586    *
587    * @return alignment flat file contents
588    */
589   public String formatSequences(String format, AlignmentI alignment,
590           boolean jvsuffix)
591   {
592     try
593     {
594       AlignFile afile = null;
595       if (format.equalsIgnoreCase("FASTA"))
596       {
597         afile = new FastaFile();
598       }
599       else if (format.equalsIgnoreCase("MSF"))
600       {
601         afile = new MSFfile();
602       }
603       else if (format.equalsIgnoreCase("PileUp"))
604       {
605         afile = new PileUpfile();
606       }
607       else if (format.equalsIgnoreCase("CLUSTAL"))
608       {
609         afile = new ClustalFile();
610       }
611       else if (format.equalsIgnoreCase("BLC"))
612       {
613         afile = new BLCFile();
614       }
615       else if (format.equalsIgnoreCase("PIR"))
616       {
617         afile = new PIRFile();
618       }
619       else if (format.equalsIgnoreCase("PFAM"))
620       {
621         afile = new PfamFile();
622       }
623       else if (format.equalsIgnoreCase("STH"))
624       {
625         afile = new StockholmFile(alignment);
626       }
627       else if (format.equalsIgnoreCase("AMSA"))
628       {
629         afile = new AMSAFile(alignment);
630       }
631       else if (format.equalsIgnoreCase(PhylipFile.FILE_DESC))
632       {
633         afile = new PhylipFile();
634       }
635       else if (format.equalsIgnoreCase(JSONFile.FILE_DESC))
636       {
637         afile = new JSONFile();
638       }
639       else if (format.equalsIgnoreCase("RNAML"))
640       {
641         afile = new RnamlFile();
642       }
643
644       else
645       {
646         throw new Exception(
647                 MessageManager
648                         .getString("error.implementation_error_unknown_file_format_string"));
649       }
650
651       afile.setNewlineString(newline);
652       afile.addJVSuffix(jvsuffix);
653       afile.setExportSettings(exportSettings);
654       afile.configureForView(viewpanel);
655
656       // check whether we were given a specific alignment to export, rather than
657       // the one in the viewpanel
658       if (viewpanel == null || viewpanel.getAlignment() == null
659               || viewpanel.getAlignment() != alignment)
660       {
661         afile.setSeqs(alignment.getSequencesArray());
662       }
663       else
664       {
665         afile.setSeqs(viewpanel.getAlignment().getSequencesArray());
666       }
667
668       String afileresp = afile.print();
669       if (afile.hasWarningMessage())
670       {
671         System.err.println("Warning raised when writing as " + format
672                 + " : " + afile.getWarningMessage());
673       }
674       return afileresp;
675     } catch (Exception e)
676     {
677       System.err.println("Failed to write alignment as a '" + format
678               + "' file\n");
679       e.printStackTrace();
680     }
681
682     return null;
683   }
684
685   public static String checkProtocol(String file)
686   {
687     String protocol = FILE;
688     String ft = file.toLowerCase().trim();
689     if (ft.indexOf("http:") == 0 || ft.indexOf("https:") == 0
690             || ft.indexOf("file:") == 0)
691     {
692       protocol = URL;
693     }
694     return protocol;
695   }
696
697   public static void main(String[] args)
698   {
699     int i = 0;
700     while (i < args.length)
701     {
702       File f = new File(args[i]);
703       if (f.exists())
704       {
705         try
706         {
707           System.out.println("Reading file: " + f);
708           AppletFormatAdapter afa = new AppletFormatAdapter();
709           Runtime r = Runtime.getRuntime();
710           System.gc();
711           long memf = -r.totalMemory() + r.freeMemory();
712           long t1 = -System.currentTimeMillis();
713           AlignmentI al = afa.readFile(args[i], FILE,
714                   new IdentifyFile().identify(args[i], FILE));
715           t1 += System.currentTimeMillis();
716           System.gc();
717           memf += r.totalMemory() - r.freeMemory();
718           if (al != null)
719           {
720             System.out.println("Alignment contains " + al.getHeight()
721                     + " sequences and " + al.getWidth() + " columns.");
722             try
723             {
724               System.out.println(new AppletFormatAdapter().formatSequences(
725                       "FASTA", al, true));
726             } catch (Exception e)
727             {
728               System.err
729                       .println("Couln't format the alignment for output as a FASTA file.");
730               e.printStackTrace(System.err);
731             }
732           }
733           else
734           {
735             System.out.println("Couldn't read alignment");
736           }
737           System.out.println("Read took " + (t1 / 1000.0) + " seconds.");
738           System.out
739                   .println("Difference between free memory now and before is "
740                           + (memf / (1024.0 * 1024.0) * 1.0) + " MB");
741         } catch (Exception e)
742         {
743           System.err.println("Exception when dealing with " + i
744                   + "'th argument: " + args[i] + "\n" + e);
745         }
746       }
747       else
748       {
749         System.err.println("Ignoring argument '" + args[i] + "' (" + i
750                 + "'th)- not a readable file.");
751       }
752       i++;
753     }
754   }
755
756   /**
757    * try to discover how to access the given file as a valid datasource that
758    * will be identified as the given type.
759    *
760    * @param file
761    * @param format
762    * @return protocol that yields the data parsable as the given type
763    */
764   public static String resolveProtocol(String file, String format)
765   {
766     return resolveProtocol(file, format, false);
767   }
768
769   public static String resolveProtocol(String file, String format,
770           boolean debug)
771   {
772     // TODO: test thoroughly!
773     String protocol = null;
774     if (debug)
775     {
776       System.out.println("resolving datasource started with:\n>>file\n"
777               + file + ">>endfile");
778     }
779
780     // This might throw a security exception in certain browsers
781     // Netscape Communicator for instance.
782     try
783     {
784       boolean rtn = false;
785       InputStream is = System.getSecurityManager().getClass()
786               .getResourceAsStream("/" + file);
787       if (is != null)
788       {
789         rtn = true;
790         is.close();
791       }
792       if (debug)
793       {
794         System.err.println("Resource '" + file + "' was "
795                 + (rtn ? "" : "not") + " located by classloader.");
796       }
797       ;
798       if (rtn)
799       {
800         protocol = AppletFormatAdapter.CLASSLOADER;
801       }
802
803     } catch (Exception ex)
804     {
805       System.err
806               .println("Exception checking resources: " + file + " " + ex);
807     }
808
809     if (file.indexOf("://") > -1)
810     {
811       protocol = AppletFormatAdapter.URL;
812     }
813     else
814     {
815       // skipping codebase prepend check.
816       protocol = AppletFormatAdapter.FILE;
817     }
818     FileParse fp = null;
819     try
820     {
821       if (debug)
822       {
823         System.out.println("Trying to get contents of resource as "
824                 + protocol + ":");
825       }
826       fp = new FileParse(file, protocol);
827       if (!fp.isValid())
828       {
829         fp = null;
830       }
831       else
832       {
833         if (debug)
834         {
835           System.out.println("Successful.");
836         }
837       }
838     } catch (Exception e)
839     {
840       if (debug)
841       {
842         System.err.println("Exception when accessing content: " + e);
843       }
844       fp = null;
845     }
846     if (fp == null)
847     {
848       if (debug)
849       {
850         System.out.println("Accessing as paste.");
851       }
852       protocol = AppletFormatAdapter.PASTE;
853       fp = null;
854       try
855       {
856         fp = new FileParse(file, protocol);
857         if (!fp.isValid())
858         {
859           fp = null;
860         }
861       } catch (Exception e)
862       {
863         System.err.println("Failed to access content as paste!");
864         e.printStackTrace();
865         fp = null;
866       }
867     }
868     if (fp == null)
869     {
870       return null;
871     }
872     if (format == null || format.length() == 0)
873     {
874       return protocol;
875     }
876     else
877     {
878       try
879       {
880         String idformat = new jalview.io.IdentifyFile().identify(file,
881                 protocol);
882         if (idformat == null)
883         {
884           if (debug)
885           {
886             System.out.println("Format not identified. Inaccessible file.");
887           }
888           return null;
889         }
890         if (debug)
891         {
892           System.out.println("Format identified as " + idformat
893                   + "and expected as " + format);
894         }
895         if (idformat.equals(format))
896         {
897           if (debug)
898           {
899             System.out.println("Protocol identified as " + protocol);
900           }
901           return protocol;
902         }
903         else
904         {
905           if (debug)
906           {
907             System.out
908                     .println("File deemed not accessible via " + protocol);
909           }
910           fp.close();
911           return null;
912         }
913       } catch (Exception e)
914       {
915         if (debug)
916         {
917           System.err.println("File deemed not accessible via " + protocol);
918           e.printStackTrace();
919         }
920         ;
921
922       }
923     }
924     return null;
925   }
926
927   public AlignFile getAlignFile()
928   {
929     return alignFile;
930   }
931
932   public void setAlignFile(AlignFile alignFile)
933   {
934     this.alignFile = alignFile;
935   }
936 }