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