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